186 lines
6.3 KiB
Python
186 lines
6.3 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
동물약 복약안내 PDF 렌더러 v2
|
|
- 마스터 JSON 구조 지원
|
|
- 카테고리별 템플릿 분기 (구충제/NSAIDs)
|
|
"""
|
|
|
|
import os
|
|
import json
|
|
import asyncio
|
|
from datetime import datetime
|
|
from typing import List, Dict, Optional
|
|
from jinja2 import Environment, FileSystemLoader
|
|
|
|
|
|
class AnimalMedRendererV2:
|
|
"""동물약 복약안내 PDF 렌더링 API v2"""
|
|
|
|
def __init__(self, master_dir: str = None, template_path: str = None):
|
|
base_dir = os.path.dirname(os.path.dirname(__file__))
|
|
|
|
self.master_dir = master_dir or os.path.join(base_dir, 'data', 'master')
|
|
self.template_dir = template_path or os.path.join(base_dir, 'templates')
|
|
|
|
# Jinja2 템플릿 환경
|
|
self.jinja_env = Environment(
|
|
loader=FileSystemLoader(self.template_dir),
|
|
autoescape=True
|
|
)
|
|
|
|
# 마스터 약품 데이터 로드
|
|
self._load_master_data()
|
|
|
|
def _load_master_data(self):
|
|
"""마스터 JSON 파일들 로드"""
|
|
self.drugs = {}
|
|
|
|
if not os.path.exists(self.master_dir):
|
|
os.makedirs(self.master_dir, exist_ok=True)
|
|
return
|
|
|
|
for filename in os.listdir(self.master_dir):
|
|
if filename.endswith('.json'):
|
|
filepath = os.path.join(self.master_dir, filename)
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
drug = json.load(f)
|
|
self.drugs[drug['product_id']] = drug
|
|
|
|
def get_drug(self, product_id: str) -> Optional[Dict]:
|
|
"""제품 ID로 약품 조회"""
|
|
return self.drugs.get(product_id)
|
|
|
|
def get_drugs(self, product_ids: List[str]) -> List[Dict]:
|
|
"""여러 제품 ID로 약품 조회"""
|
|
result = []
|
|
for pid in product_ids:
|
|
drug = self.get_drug(pid)
|
|
if drug:
|
|
result.append(drug)
|
|
return result
|
|
|
|
def render_html(
|
|
self,
|
|
product_ids: List[str],
|
|
patient_name: str = "홍길동",
|
|
pet_name: str = "뽀삐",
|
|
pet_species: str = "개",
|
|
pet_age: str = "3세",
|
|
pharmacy_name: str = "청춘약국",
|
|
pharmacy_tel: str = "033-481-7390",
|
|
pharmacy_address: str = "강원 양구군 양구읍"
|
|
) -> str:
|
|
"""
|
|
마스터 JSON 기반 HTML 복약안내문 렌더링 (v2)
|
|
"""
|
|
drugs = self.get_drugs(product_ids)
|
|
|
|
if not drugs:
|
|
raise ValueError(f"유효한 약품을 찾을 수 없습니다: {product_ids}")
|
|
|
|
template = self.jinja_env.get_template('medication_guide_v2.html')
|
|
|
|
html = template.render(
|
|
drugs=drugs,
|
|
patient_name=patient_name,
|
|
pet_name=pet_name,
|
|
pet_species=pet_species,
|
|
pet_age=pet_age,
|
|
pharmacy_name=pharmacy_name,
|
|
pharmacy_tel=pharmacy_tel,
|
|
pharmacy_address=pharmacy_address,
|
|
issue_date=datetime.now().strftime('%Y년 %m월 %d일')
|
|
)
|
|
|
|
return html
|
|
|
|
def render_to_pdf(
|
|
self,
|
|
product_ids: List[str],
|
|
output_path: str = None,
|
|
**kwargs
|
|
) -> Dict:
|
|
"""
|
|
마스터 JSON 기반 PDF 복약안내문 생성 (v2)
|
|
"""
|
|
# HTML 렌더링
|
|
html_content = self.render_html(product_ids, **kwargs)
|
|
|
|
# 출력 경로
|
|
if not output_path:
|
|
import tempfile
|
|
import time
|
|
output_path = os.path.join(tempfile.gettempdir(), f'animal_med_v2_{int(time.time())}.pdf')
|
|
|
|
# HTML → PDF
|
|
async def _convert():
|
|
from playwright.async_api import async_playwright
|
|
|
|
async with async_playwright() as p:
|
|
browser = await p.chromium.launch(headless=True)
|
|
page = await browser.new_page(viewport={'width': 794, 'height': 1123})
|
|
|
|
await page.set_content(html_content, wait_until='networkidle')
|
|
|
|
# 콘텐츠 크기 확인
|
|
rect = await page.evaluate('''() => {
|
|
const el = document.querySelector('.container');
|
|
const rect = el.getBoundingClientRect();
|
|
return { width: rect.width, height: rect.height };
|
|
}''')
|
|
|
|
# A4에 맞는 scale 계산
|
|
content_width_pt = rect['width'] * 0.75
|
|
content_height_pt = rect['height'] * 0.75
|
|
|
|
scale_x = 595 / content_width_pt if content_width_pt > 0 else 1
|
|
scale_y = 842 / content_height_pt if content_height_pt > 0 else 1
|
|
scale = min(scale_x, scale_y, 1.0)
|
|
|
|
await page.pdf(
|
|
path=output_path,
|
|
format='A4',
|
|
print_background=True,
|
|
margin={'top': '0', 'right': '0', 'bottom': '0', 'left': '0'},
|
|
scale=scale
|
|
)
|
|
|
|
await browser.close()
|
|
|
|
try:
|
|
try:
|
|
loop = asyncio.get_running_loop()
|
|
except RuntimeError:
|
|
loop = None
|
|
|
|
if loop and loop.is_running():
|
|
import concurrent.futures
|
|
with concurrent.futures.ThreadPoolExecutor() as executor:
|
|
future = executor.submit(asyncio.run, _convert())
|
|
future.result()
|
|
else:
|
|
asyncio.run(_convert())
|
|
|
|
drugs = self.get_drugs(product_ids)
|
|
|
|
return {
|
|
'success': True,
|
|
'pdf_path': output_path,
|
|
'drug_count': len(drugs),
|
|
'drugs': [d['name'] for d in drugs]
|
|
}
|
|
except Exception as e:
|
|
return {'success': False, 'error': str(e)}
|
|
|
|
def list_drugs(self) -> List[Dict]:
|
|
"""마스터 약품 목록 반환"""
|
|
return [
|
|
{
|
|
'product_id': d['product_id'],
|
|
'name': d['name'],
|
|
'category': d['category'],
|
|
'category_display': d.get('category_display', d['category'])
|
|
}
|
|
for d in self.drugs.values()
|
|
]
|