File size: 17,721 Bytes
76e08e0
 
149f48c
76e08e0
c103d7c
76e08e0
c103d7c
72114b8
76e08e0
6d9d526
76e08e0
 
72114b8
c103d7c
6d9d526
72114b8
 
 
c103d7c
 
72114b8
 
c103d7c
76e08e0
6d9d526
 
 
 
 
 
 
 
 
 
 
 
 
76e08e0
 
 
 
 
 
 
 
 
 
 
 
5f1a404
149f48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f1a404
76e08e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149f48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e08e0
 
149f48c
 
 
 
 
 
 
 
 
76e08e0
149f48c
76e08e0
 
 
149f48c
76e08e0
 
 
 
 
 
149f48c
76e08e0
 
 
 
c103d7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e08e0
 
 
 
 
 
 
 
c103d7c
 
 
 
 
 
5f1a404
 
 
76e08e0
 
 
5f1a404
76e08e0
 
 
5f1a404
76e08e0
5f1a404
76e08e0
 
 
 
 
 
5f1a404
76e08e0
 
 
5f1a404
76e08e0
 
5f1a404
76e08e0
 
 
5f1a404
 
76e08e0
 
 
 
 
 
 
 
 
5f1a404
 
149f48c
 
 
 
 
 
 
 
 
6d9d526
149f48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d9d526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c103d7c
 
 
 
 
 
 
 
 
 
 
 
6d9d526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e08e0
 
6d9d526
 
 
 
 
 
0e757ea
6d9d526
5f1a404
76e08e0
 
 
 
149f48c
6d9d526
0e757ea
6d9d526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e08e0
6d9d526
 
 
 
 
 
 
 
0e757ea
76e08e0
6d9d526
 
 
 
 
 
 
0e757ea
6d9d526
 
 
 
 
 
 
5f1a404
 
 
76e08e0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import json
import re
from typing import Any, Dict, List, Optional, Sequence

import easyocr
import gradio as gr
import numpy as np
import torch
from PIL import Image, ImageDraw
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

# --- OCR pipeline ---------------------------------------------------------
# Use a high-capacity OCR model for better accuracy on prescription labels.
OCR_LANGS = ["ko", "en"]
LLM_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"


def _load_ocr():
    use_gpu = torch.cuda.is_available()
    return easyocr.Reader(OCR_LANGS, gpu=use_gpu)


ocr_reader = _load_ocr()


def _load_llm():
    device_map = "auto" if torch.cuda.is_available() else None
    dtype = torch.float16 if torch.cuda.is_available() else torch.float32
    model = AutoModelForCausalLM.from_pretrained(LLM_MODEL_ID, device_map=device_map, torch_dtype=dtype)
    if device_map is None:
        model = model.to(torch.device("cpu"))
    tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID)
    return model, tokenizer


LLM_MODEL, LLM_TOKENIZER = _load_llm()

# Korean keywords describing time slots on prescription labels.
TIME_KEYWORDS = [
    "์•„์นจ",
    "์ ์‹ฌ",
    "์ €๋…",
    "์ทจ์นจ",
    "์ž๊ธฐ",
    "์‹์ „",
    "์‹ํ›„",
    "์‹๊ฐ„",
    "๊ธฐ์ƒ",
]

# Very small knowledge base for common Korean OTC medications.
MED_KNOWLEDGE: Sequence[Dict[str, Any]] = [
    {
        "keywords": ["ํƒ€์ด๋ ˆ๋†€", "์•„์„ธํŠธ์•„๋ฏธ๋…ธํŽœ", "acetaminophen"],
        "category": "์ง„ํ†ตยทํ•ด์—ด์ œ",
        "what_it_does": "๋ชธ์‚ด์ด๋‚˜ ๊ฐ๊ธฐ๋กœ ์—ด์ด ๋‚˜๊ฑฐ๋‚˜ ๋จธ๋ฆฌ๊ฐ€ ์•„ํ”Œ ๋•Œ ํ†ต์ฆ๊ณผ ์—ด์„ ๋‚ฎ์ถฐ ์ค๋‹ˆ๋‹ค.",
        "example": "์˜ˆ: ์ˆ˜ํ•™์‹œํ—˜ ์ค€๋น„๋กœ ๊ธด์žฅํ–ˆ๋Š”๋ฐ ๋จธ๋ฆฌ๊ฐ€ ์ง€๋ˆ๊ฑฐ๋ฆด ๋•Œ, ํ•œ ์•Œ ๋ณต์šฉํ•˜๋ฉด ํ†ต์ฆ์ด ์ค„์–ด๋“ญ๋‹ˆ๋‹ค.",
        "tip": "์œ„์— ๋ถ€๋‹ด์„ ์ค„์ด๊ธฐ ์œ„ํ•ด ๊ฐ„๋‹จํ•œ ๊ฐ„์‹๊ณผ ํ•จ๊ป˜ ๋ฌผ๊ณผ ๋ณต์šฉํ•˜๊ณ , ํ•˜๋ฃจ ์ด ๋ณต์šฉ ํšŸ์ˆ˜(์ผ๋ฐ˜์ ์œผ๋กœ 4ํšŒ ์ดํ•˜)๋ฅผ ๋„˜๊ธฐ์ง€ ๋งˆ์„ธ์š”.",
    },
    {
        "keywords": ["์ด๋ถ€ํ”„๋กœํŽœ", "๋ถ€๋ฃจํŽœ", "ibuprofen"],
        "category": "์ง„ํ†ตยท์†Œ์—ผ์ œ",
        "what_it_does": "๋ชธ์† ์—ผ์ฆ์„ ๊ฐ€๋ผ์•‰ํžˆ๊ณ  ํ†ต์ฆ์„ ์™„ํ™”ํ•ด์„œ ๊ทผ์œกํ†ต์ด๋‚˜ ์น˜ํ†ต์— ์ž์ฃผ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.",
        "example": "์˜ˆ: ์ฒด์œก ์‹œ๊ฐ„์— ๋ฌด๋ฆŽ์„ ์‚ด์ง ์‚์—ˆ์„ ๋•Œ ๋ถ“๊ธฐ์™€ ์•„ํ””์„ ์ค„์—ฌ ์ค๋‹ˆ๋‹ค.",
        "tip": "์‹ํ›„์— ๋ณต์šฉํ•˜๋ฉด ์† ์“ฐ๋ฆผ์„ ์ค„์ผ ์ˆ˜ ์žˆ๊ณ , ๋‹ค๋ฅธ ์†Œ์—ผ์ง„ํ†ต์ œ์™€๋Š” ์‹œ๊ฐ„ ๊ฐ„๊ฒฉ์„ ๋‘์„ธ์š”.",
    },
    {
        "keywords": ["์‹œ์ž˜", "์„ธํ‹ฐ๋ฆฌ์ง„", "cetirizine", "์ง€๋ฅดํ…"],
        "category": "์•Œ๋ ˆ๋ฅด๊ธฐ ์™„ํ™”์ œ",
        "what_it_does": "์ฝ”๊ฐ€ ๊ฐ„์งˆ๊ฑฐ๋ฆฌ๊ฑฐ๋‚˜ ํ”ผ๋ถ€๊ฐ€ ๊ฐ€๋ ค์šธ ๋•Œ ์•Œ๋ ˆ๋ฅด๊ธฐ ๋ฐ˜์‘์„ ๊ฐ€๋ผ์•‰ํ˜€ ์ค๋‹ˆ๋‹ค.",
        "example": "์˜ˆ: ๋ด„์ฒ  ๊ฝƒ๊ฐ€๋ฃจ ๋•Œ๋ฌธ์— ๊ธฐ์นจ๊ณผ ์ฝง๋ฌผ์ด ๋‚˜์˜ฌ ๋•Œ ์ฆ์ƒ์„ ์ค„์—ฌ ์ค๋‹ˆ๋‹ค.",
        "tip": "์กธ๋ฆด ์ˆ˜ ์žˆ์œผ๋‹ˆ ์ฒซ ๋ณต์šฉ ํ›„์—๋Š” ์šด์ „์ด๋‚˜ ์ง‘์ค‘์ด ํ•„์š”ํ•œ ํ™œ๋™์€ ํ”ผํ•˜์„ธ์š”.",
    },
    {
        "keywords": ["ํ›ผ์Šคํƒˆ", "pancreatin", "์œ„์žฅ", "์†Œํ™”์ œ"],
        "category": "์†Œํ™”์ œ",
        "what_it_does": "๊ธฐ๋ฆ„์ง„ ์Œ์‹์„ ๋จน๊ณ  ๋ฐฐ๊ฐ€ ๋”๋ถ€๋ฃฉํ•  ๋•Œ ์†Œํ™”๋ฅผ ๋„์™€ ์†์„ ํŽธํ•˜๊ฒŒ ํ•ด ์ค๋‹ˆ๋‹ค.",
        "example": "์˜ˆ: ์น˜ํ‚จ์„ ๋งŽ์ด ๋จน์–ด ์†์ด ๋”๋ถ€๋ฃฉํ•  ๋•Œ ์†์„ ๊ฐ€๋ณ๊ฒŒ ํ•ด ์ค๋‹ˆ๋‹ค.",
        "tip": "์‹ํ›„์— ๋ณต์šฉํ•˜๋ฉด ํšจ๊ณผ๊ฐ€ ์ข‹์œผ๋ฉฐ, ๋ณตํ†ต์ด ๊ณ„์†๋˜๋ฉด ๋ณ‘์›์„ ๋ฐฉ๋ฌธํ•˜์„ธ์š”.",
    },
    {
        "keywords": ["๋น„ํƒ€๋ฏผ", "multivitamin", "vitamin"],
        "category": "์˜์–‘์ œ",
        "what_it_does": "๋ชธ์— ํ•„์š”ํ•œ ๋น„ํƒ€๋ฏผ์„ ์ฑ„์›Œ ํ”ผ๊ณคํ•จ์„ ์ค„์ด๊ณ  ๋ฉด์—ญ๋ ฅ์„ ๋•์Šต๋‹ˆ๋‹ค.",
        "example": "์˜ˆ: ์‹œํ—˜ ์ค€๋น„๋กœ ์ž ์„ ์ค„์˜€์„ ๋•Œ ๋ชธ์ด ์ง€์น˜์ง€ ์•Š๋„๋ก ๋„์™€์ค๋‹ˆ๋‹ค.",
        "tip": "ํ•˜๋ฃจ ๊ถŒ์žฅ๋Ÿ‰์„ ์ง€์ผœ ๊พธ์ค€ํžˆ ๋ณต์šฉํ•˜๋ฉด ๋” ํšจ๊ณผ์ ์ด๋ฉฐ, ๋ฌผ๊ณผ ํ•จ๊ป˜ ์‚ผํ‚ค์„ธ์š”.",
    },
]


def _extract_time_slots(text: str) -> List[str]:
    slots = []
    for kw in TIME_KEYWORDS:
        if kw in text:
            slots.append(kw)
    # Also capture explicit times like 08:00 ํ˜น์€ 8์‹œ
    for match in re.findall(r"(\d{1,2}[:์‹œ]\d{0,2})", text):
        norm = match.replace("์‹œ", ":")
        if norm.endswith(":"):
            norm += "00"
        if norm not in slots:
            slots.append(norm)
    return slots


STOPWORDS = {"์šฉ๋ฒ•", "์šฉ๋Ÿ‰", "๋ณต์šฉ", "๋ฐฉ๋ฒ•", "์•ฝ", "์ •"}


def _extract_medications(text: str) -> List[Dict[str, Optional[str]]]:
    meds: List[Dict[str, Optional[str]]] = []
    pattern = re.compile(
        r"([๊ฐ€-ํžฃA-Za-z]{2,})[\sยท]*(\d+[\./]?\d*\s*(?:mg|mL|ML|ml|์ •|์บก์А))?"
    )
    seen: set[str] = set()
    for match in pattern.finditer(text):
        name = match.group(1)
        if name in STOPWORDS or len(name) <= 1:
            continue
        if any(sw in name for sw in STOPWORDS):
            continue
        name_norm = name.strip()
        if name_norm in seen:
            continue
        seen.add(name_norm)
        dose = match.group(2).strip() if match.group(2) else None
        meds.append({"name": name_norm, "dose": dose})
    return meds


def parse_fields(raw: str) -> Dict[str, Any]:
    """Extract drug name and dosage information from OCR text."""
    collapsed = raw.replace("\n", " ")
    collapsed = re.sub(r"\s+", " ", collapsed)

    medications = _extract_medications(collapsed)

    first = medications[0] if medications else {"name": None, "dose": None}
    drug_name = first.get("name")
    dose_per_intake = first.get("dose")

    times_per_day: Optional[int] = None
    times_match = re.search(r"(?:1์ผ|ํ•˜๋ฃจ)\s*(\d+)\s*ํšŒ", collapsed)
    if times_match:
        times_per_day = int(times_match.group(1))

    time_slots = _extract_time_slots(collapsed)

    return {
        "drug_name": drug_name,
        "dose_per_intake": dose_per_intake,
        "times_per_day": times_per_day,
        "time_slots": time_slots or None,
        "medications": medications,
    }


def ocr_and_parse(image: Image.Image) -> Dict[str, Any]:
    np_img = np.array(image.convert("RGB"))
    results = ocr_reader.readtext(np_img, detail=1, paragraph=False)

    segments: List[Dict[str, Any]] = []
    lines: List[str] = []
    for bbox, text, confidence in results:
        cleaned = text.strip()
        if not cleaned:
            continue
        lines.append(cleaned)
        segments.append({
            "text": cleaned,
            "confidence": float(confidence),
            "bbox": bbox,
        })

    raw_text = "\n".join(lines)
    fields = parse_fields(raw_text)

    warnings: List[str] = []
    if not fields["drug_name"]:
        warnings.append("์•ฝ ์ด๋ฆ„ ์ธ์‹์ด ๋ถˆํ™•์‹คํ•ฉ๋‹ˆ๋‹ค.")
    if not fields["times_per_day"]:
        warnings.append("1์ผ ํšŸ์ˆ˜๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค (์˜ˆ: 1์ผ 3ํšŒ).")

    return {
        "raw_text": raw_text,
        "fields": fields,
        "warnings": warnings,
        "segments": segments,
    }


def render_card(fields: Dict[str, Any]) -> Image.Image:
    width, height = 720, 400
    img = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(img)

    header_text = "์˜ค๋Š˜ ๋ณต์šฉ ์ผ์ •"
    draw.rectangle((0, 0, width, 60), fill=(230, 240, 255))
    draw.text((24, 18), header_text, fill=(0, 0, 0))

    y = 90

    def add_line(label: str, value: Optional[str]):
        nonlocal y
        draw.text((24, y), label, fill=(60, 60, 60))
        display = value if value else "-"
        draw.text((180, y), f": {display}", fill=(0, 0, 0))
        y += 34

    add_line("์•ฝ ์ด๋ฆ„", fields.get("drug_name"))
    add_line("1ํšŒ ์šฉ๋Ÿ‰", fields.get("dose_per_intake"))
    add_line("1์ผ ํšŸ์ˆ˜", str(fields.get("times_per_day") or ""))

    slots = fields.get("time_slots") or []
    add_line("์‹œ๊ฐ„๋Œ€", ", ".join(slots) if slots else None)

    footer = "โ€ป ์˜๋ฃŒ์ง„ ์ฒ˜๋ฐฉ์ด ์šฐ์„ ์ด๋ฉฐ, ๋ณธ ์•ฑ์€ ์ฐธ๊ณ ์šฉ์ž…๋‹ˆ๋‹ค."
    draw.text((24, height - 60), footer, fill=(120, 120, 120))
    return img


def to_csv_row(output: Dict[str, Any]) -> str:
    fields = output["fields"]
    row = [
        fields.get("drug_name") or "",
        fields.get("dose_per_intake") or "",
        str(fields.get("times_per_day") or ""),
        ";".join(fields.get("time_slots") or []),
    ]
    return ",".join(row)


def _match_knowledge(name: str) -> Optional[Dict[str, Any]]:
    lowered = name.lower()
    for info in MED_KNOWLEDGE:
        for kw in info["keywords"]:
            if kw.lower() in lowered or lowered in kw.lower():
                return info
    return None


def build_kb_explanations(output: Dict[str, Any]) -> str:
    meds = output["fields"].get("medications") or []
    if not meds:
        return (
            "### ์•ฝ ์„ค๋ช…\n"
            "- ์•ฝ ์ด๋ฆ„์„ ์ •ํ™•ํžˆ ์ธ์‹ํ•˜์ง€ ๋ชปํ–ˆ์–ด์š”. ์‚ฌ์ง„์„ ๋‹ค์‹œ ์ฐ๊ฑฐ๋‚˜ ์•ฝ์‚ฌ์—๊ฒŒ ์ง์ ‘ ํ™•์ธํ•ด ์ฃผ์„ธ์š”.\n"
            "\n> โš ๏ธ ์˜๋ฃŒ์ง„ ์ฒ˜๋ฐฉ๊ณผ ๋ณต์•ฝ ์ง€์‹œ๊ฐ€ ๊ฐ€์žฅ ์šฐ์„ ์ž…๋‹ˆ๋‹ค."
        )

    lines = ["### ์‰ฝ๊ฒŒ ์•Œ์•„๋ณด๋Š” ์•ฝ ์„ค๋ช…"]
    for med in meds:
        name = med.get("name") or "์ด๋ฆ„ ๋ฏธํ™•์ธ"
        info = _match_knowledge(name) if name else None
        dose = med.get("dose")
        if info:
            lines.append(
                f"- **{name}** ({info['category']})"
            )
            if dose:
                lines.append(f"  - ์•ฝ ๋ด‰ํˆฌ์— ์ ํžŒ ์šฉ๋Ÿ‰: `{dose}`")
            lines.append(f"  - ํ•˜๋Š” ์ผ: {info['what_it_does']}")
            lines.append(f"  - ์ค‘ํ•™์ƒ ์˜ˆ์‹œ: {info['example']}")
            lines.append(f"  - ๋ณต์šฉ ํŒ: {info['tip']}")
        else:
            lines.append(f"- **{name}**")
            if dose:
                lines.append(f"  - ์•ฝ ๋ด‰ํˆฌ ์šฉ๋Ÿ‰: `{dose}`")
            lines.append(
                "  - ์•„์ง ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์–ด์š”. ์•ฝ ์ด๋ฆ„์„ ๋‹ค์‹œ ํ™•์ธํ•˜๊ฑฐ๋‚˜ ์•ฝ์‚ฌ์—๊ฒŒ ๋ฌผ์–ด๋ณด์„ธ์š”."
            )

    lines.append("\n> โš ๏ธ ์‹ค์ œ ๋ณต์•ฝ์€ ์˜์‚ฌยท์•ฝ์‚ฌ์˜ ์ง€์‹œ์— ๋ฐ˜๋“œ์‹œ ๋”ฐ๋ฅด์„ธ์š”.")
    return "\n".join(lines)


def generate_llm_explanations(output: Dict[str, Any]) -> str:
    meds = output["fields"].get("medications") or []
    if not meds:
        return (
            "์•ฝ ์ด๋ฆ„์„ ์ œ๋Œ€๋กœ ์ธ์‹ํ•˜์ง€ ๋ชปํ–ˆ์–ด์š”. ์‚ฌ์ง„์„ ๋‹ค์‹œ ์ฐ๊ฑฐ๋‚˜ ์•ฝ์‚ฌ์—๊ฒŒ ์ง์ ‘ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."
        )

    med_lines = []
    for idx, med in enumerate(meds, 1):
        name = med.get("name") or "์ด๋ฆ„ ๋ฏธํ™•์ธ"
        dose = med.get("dose") or "์šฉ๋Ÿ‰ ์ •๋ณด ์—†์Œ"
        med_lines.append(f"{idx}. {name} โ€” {dose}")

    context = "\n".join(med_lines)
    raw_text = output.get("raw_text", "")

    system_prompt = (
        "๋‹น์‹ ์€ ์•ฝ์‚ฌ ์„ ์ƒ๋‹˜์ž…๋‹ˆ๋‹ค. ์–ด๋ ค์šด ์˜ํ•™ ์šฉ์–ด๋ฅผ ์“ฐ์ง€ ๋ง๊ณ , ์ค‘ํ•™์ƒ๋„ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ๋งํˆฌ๋กœ ์นœ์ ˆํ•˜๊ฒŒ ์„ค๋ช…ํ•˜์„ธ์š”."
    )
    user_prompt = (
        "๋‹ค์Œ์€ ์•ฝ๋ด‰ํˆฌ์—์„œ OCR๋กœ ์ถ”์ถœํ•œ ์ „์ฒด ํ…์ŠคํŠธ์ž…๋‹ˆ๋‹ค. ์•ฝ ์ด๋ฆ„๊ณผ ๋ณต์šฉ ์ง€์‹œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ฐ ์•ฝ์˜ ์ •๋ณด๋ฅผ ์•„์ฃผ ์‰ฝ๊ฒŒ ์ •๋ฆฌํ•ด ์ฃผ์„ธ์š”.\n"
        "์š”๊ตฌ ์‚ฌํ•ญ:\n"
        "1. ๊ฐ ์•ฝ๋งˆ๋‹ค ์•„๋ž˜ ํ•ญ๋ชฉ์„ bullet ํ˜•์‹์œผ๋กœ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.\n"
        "   - ์•ฝ ์ด๋ฆ„: (๊ฐ€๋Šฅํ•˜๋ฉด ํ•œ๊ธ€/์˜๋ฌธ ๋ณ‘๊ธฐ)\n"
        "   - ์–ด๋–ค ์•ฝ์ธ์ง€ ํ•œ ์ค„ ์„ค๋ช…\n"
        "   - ๋ณต์šฉ ์˜ˆ์‹œ: ์–ธ์ œ, ์–ด๋–ค ์ƒํ™ฉ์—์„œ ๋ณต์šฉํ•˜๋ฉด ์ข‹์€์ง€ ์˜ˆ์‹œ\n"
        "   - ๋ณต์šฉ ๋ฐฉ๋ฒ• ์˜ˆ์‹œ: 1ํšŒ ์šฉ๋Ÿ‰/ํ•˜๋ฃจ ํšŸ์ˆ˜๊ฐ€ ์žˆ๋‹ค๋ฉด ์–ธ๊ธ‰\n"
        "   - ๋ถ€์ž‘์šฉ ๋˜๋Š” ์ฃผ์˜์‚ฌํ•ญ: ํ”ํ•œ ๋ถ€์ž‘์šฉ, ํ”ผํ•ด์•ผ ํ•  ํ–‰๋™\n"
        "2. ์–ด๋ ค์šด ์˜ํ•™ ์šฉ์–ด๋Š” ํ”ผํ•˜๊ณ , ์ค‘ํ•™์ƒ๋„ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ๋งํˆฌ๋กœ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.\n"
        "3. ์•ฝ ์ด๋ฆ„์„ ํ™•์‹คํžˆ ๋ชจ๋ฅด๋ฉด โ€˜์ด๋ฆ„ ๋ฏธํ™•์ธโ€™์ด๋ผ๊ณ  ์“ฐ๊ณ , ์•ฝ์‚ฌ์—๊ฒŒ ํ™•์ธํ•˜๋ผ๊ณ  ์•ˆ๋‚ดํ•ฉ๋‹ˆ๋‹ค.\n"
        "4. ๋งˆ์ง€๋ง‰ ๋ฌธ๋‹จ์— ๋ฐ˜๋“œ์‹œ โ€˜์‹ค์ œ ๋ณต์•ฝ์€ ์˜์‚ฌยท์•ฝ์‚ฌ์˜ ์ง€์‹œ๋ฅผ ๋”ฐ๋ฅด์„ธ์š”โ€™ ๋ฌธ์žฅ์„ ํฌํ•จํ•˜์„ธ์š”.\n"
        f"\n์•ฝ ๋ชฉ๋ก(์ถ”์ถœ ์š”์•ฝ):\n{context}\n\nOCR ์›๋ฌธ ์ „์ฒด:\n{raw_text}\n"
    )

    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt},
    ]

    input_ids = LLM_TOKENIZER.apply_chat_template(
        messages,
        add_generation_prompt=True,
        return_tensors="pt",
    )
    input_ids = input_ids.to(LLM_MODEL.device)

    with torch.no_grad():
        output_ids = LLM_MODEL.generate(
            input_ids,
            max_new_tokens=480,
            temperature=0.7,
            top_p=0.9,
            do_sample=True,
            eos_token_id=LLM_TOKENIZER.eos_token_id,
        )

    generated_ids = output_ids[0][input_ids.shape[1]:]
    text = LLM_TOKENIZER.decode(generated_ids, skip_special_tokens=True).strip()
    return text


def build_explanations(output: Dict[str, Any]) -> str:
    try:
        llm_text = generate_llm_explanations(output)
        if llm_text:
            return llm_text
    except Exception as err:  # pragma: no cover - safe fallback
        print(f"[WARN] LLM generation failed: {err}", flush=True)
    return build_kb_explanations(output)


def format_warnings(warnings: List[str]) -> str:
    if not warnings:
        return "โœ… ์ธ์‹๋œ ์ •๋ณด๊ฐ€ ์ถฉ๋ถ„ํ•ด์š”. ๋ณต์•ฝ ์‹œ๊ฐ„๋งŒ ์ž˜ ์ง€์ผœ ์ฃผ์„ธ์š”."
    lines = ["### ํ™•์ธํ•ด ์ฃผ์„ธ์š”"]
    for warn in warnings:
        lines.append(f"- {warn}")
    lines.append("\n> ์˜๋ฃŒ์ง„์˜ ์ง€์‹œ๊ฐ€ ๊ฐ€์žฅ ์ •ํ™•ํ•ฉ๋‹ˆ๋‹ค.")
    return "\n".join(lines)


def run_pipeline(image: Optional[Image.Image]):
    if image is None:
        return (
            "์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•˜์„ธ์š”.",
            None,
            None,
            "์ด๋ฏธ์ง€๋ฅผ ๋จผ์ € ์—…๋กœ๋“œํ•ด ์ฃผ์„ธ์š”.",
            "๐Ÿ“ท ์•ฝ ๋ด‰ํˆฌ ์‚ฌ์ง„์„ ์˜ฌ๋ฆฌ๋ฉด ์ธ์‹์ด ์‹œ์ž‘๋ผ์š”.",
            "",
        )

    output = ocr_and_parse(image)
    card = render_card(output["fields"])
    csv_row = to_csv_row(output)
    json_text = json.dumps(output, ensure_ascii=False, indent=2)
    explanations = build_explanations(output)
    warnings_md = format_warnings(output.get("warnings", []))
    return json_text, card, csv_row, explanations, warnings_md, output.get("raw_text", "")


CUSTOM_CSS = """
body {background: radial-gradient(circle at top left, #f5f0ff 0%, #fff7ec 60%, #ffffff 100%);}
.gradio-container {max-width: 1180px !important; margin: auto; font-family: 'Noto Sans KR', sans-serif;}
.hero {
  background: linear-gradient(120deg, rgba(123, 97, 255, 0.12), rgba(255, 207, 117, 0.18));
  border-radius: 28px;
  padding: 36px 44px;
  box-shadow: 0 20px 40px rgba(66, 46, 138, 0.08);
  margin-bottom: 32px;
}
.hero h1 {font-size: 2.4rem; font-weight: 700; color: #1f1c3b; margin-bottom: 12px;}
.hero p {color: #514c7b; font-size: 1.05rem; line-height: 1.6; max-width: 640px;}
.glass-panel {background: rgba(255, 255, 255, 0.72); backdrop-filter: blur(18px); border-radius: 26px; padding: 28px; box-shadow: 0 12px 32px rgba(80, 60, 160, 0.12);}
.panel-title {font-weight: 700; font-size: 1.2rem; margin-bottom: 18px; color: #2f2355;}
.primary-btn button {background: linear-gradient(120deg, #7c62ff, #ffa74d); border: none; color: white; font-weight: 600; border-radius: 999px; padding: 12px 22px; box-shadow: 0 12px 24px rgba(124, 98, 255, 0.25);} 
.primary-btn button:hover {opacity: 0.95; transform: translateY(-1px);}
.output-card {background: rgba(255, 255, 255, 0.88); border-radius: 22px; padding: 24px; box-shadow: inset 0 0 0 1px rgba(124, 98, 255, 0.08), 0 14px 30px rgba(49, 32, 114, 0.12);}
.notice {background: rgba(255, 247, 226, 0.9); border-radius: 18px; padding: 18px; color: #7a4b00; box-shadow: inset 0 0 0 1px rgba(255, 193, 96, 0.3);}
.csv-box textarea {font-family: 'JetBrains Mono', monospace;}
.gr-image {border-radius: 20px !important; box-shadow: 0 10px 20px rgba(60, 40, 120, 0.15);}
.accordion {border-radius: 20px !important;}
"""

HERO_HTML = """
<div class="hero">
  <h1>MedCard-KR ยท ์•ฝ๋ด‰ํˆฌ ํ•œ ์ปท์œผ๋กœ ์ดํ•ดํ•˜๋Š” ๋ณต์šฉ ์•ˆ๋‚ด</h1>
  <p>์‚ฌ์ง„ ์† ์•ฝ ์ด๋ฆ„์„ OCR๋กœ ์ฝ์–ด ๋“ค์ด๊ณ , Qwen LLM์ด ์ค‘ํ•™์ƒ๋„ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ๋งํˆฌ๋กœ ์•ฝ์„ ์„ค๋ช…ํ•ด ๋“œ๋ฆฝ๋‹ˆ๋‹ค.
     ๋ณต์šฉ ์ผ์ • ์นด๋“œ์™€ CSV๊นŒ์ง€ ํ•œ ๋ฒˆ์— ๋ฐ›์•„ ๋ณด์„ธ์š”.</p>
</div>
"""


with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
    gr.HTML(HERO_HTML)
    with gr.Row():
        with gr.Column(scale=4, elem_classes=["glass-panel"]):
            gr.Markdown("### 1. ์•ฝ ๋ด‰ํˆฌ ์‚ฌ์ง„์„ ์—…๋กœ๋“œํ•˜์„ธ์š”")
            img_in = gr.Image(type="pil", label="์•ฝ ๋ด‰ํˆฌ/๋ผ๋ฒจ ์‚ฌ์ง„", height=360)
            warn_md = gr.Markdown("๐Ÿ“ท ์•ฝ ๋ด‰ํˆฌ ์‚ฌ์ง„์„ ์˜ฌ๋ฆฌ๋ฉด ์ธ์‹์ด ์‹œ์ž‘๋ผ์š”.", elem_classes=["notice"])
            btn = gr.Button("์ธ์‹ & ์„ค๋ช… ์ƒ์„ฑ", elem_classes=["primary-btn"])
        with gr.Column(scale=6, elem_classes=["glass-panel"]):
            gr.Markdown("### 2. ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ•˜์„ธ์š”")
            explain_md = gr.Markdown("์—ฌ๊ธฐ์— ์•ฝ ์„ค๋ช…์ด ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.", elem_classes=["output-card"])
            raw_box = gr.Textbox(label="OCR ์›๋ฌธ ํ…์ŠคํŠธ", lines=5, interactive=False)
            card_out = gr.Image(type="pil", label="์ผ์ • ์นด๋“œ(๋ฏธ๋ฆฌ๋ณด๊ธฐ)")
            csv_box = gr.Textbox(label="CSV(์•ฝ๋ช…,1ํšŒ์šฉ๋Ÿ‰,1์ผํšŸ์ˆ˜,์‹œ๊ฐ„๋Œ€)", lines=2, elem_classes=["csv-box"])
            with gr.Accordion("์„ธ๋ถ€ JSON ๊ฒฐ๊ณผ", open=False, elem_classes=["accordion"]):
                json_out = gr.Code(label="์ธ์‹ ๊ฒฐ๊ณผ(JSON)")

    btn.click(
        run_pipeline,
        inputs=img_in,
        outputs=[json_out, card_out, csv_box, explain_md, warn_md, raw_box],
    )

    gr.Markdown(
        """
        > โ„น๏ธ **์ฃผ์˜**: ์ด ์„œ๋น„์Šค๋Š” ์ฐธ๊ณ ์šฉ ๋„๊ตฌ์ด๋ฉฐ, ์‹ค์ œ ๋ณต์•ฝ์€ ๋ฐ˜๋“œ์‹œ ์˜์‚ฌยท์•ฝ์‚ฌ์˜ ์ง€์‹œ์— ๋”ฐ๋ผ ์ฃผ์„ธ์š”.
        """
    )


if __name__ == "__main__":
    demo.queue().launch()