File size: 23,881 Bytes
76e08e0
5e231af
76e08e0
3cec557
ad98685
459e392
76e08e0
 
5e231af
69a39af
e53f54d
5e231af
e53f54d
 
 
 
72114b8
e5f80e3
 
3cec557
 
 
98b216f
3cec557
 
 
 
 
 
 
 
 
 
 
98b216f
3cec557
98b216f
3cec557
 
 
 
 
 
 
5e231af
98b216f
5e231af
 
 
 
 
 
 
98b216f
5e231af
 
 
98b216f
5e231af
 
 
 
 
 
459e392
e5f80e3
6d9d526
98b216f
e5f80e3
459e392
 
e35cc62
e5f80e3
e35cc62
 
98b216f
459e392
 
 
 
e5f80e3
459e392
e5f80e3
e53f54d
 
459e392
98b216f
459e392
 
 
 
 
 
 
 
98b216f
459e392
 
 
 
 
 
e53f54d
98b216f
e53f54d
 
 
 
 
459e392
e53f54d
 
98b216f
e53f54d
 
459e392
 
 
 
 
e53f54d
76e08e0
 
e53f54d
 
459e392
e53f54d
 
98b216f
 
e53f54d
98b216f
e53f54d
76e08e0
 
 
459e392
98b216f
459e392
 
 
 
 
98b216f
459e392
98b216f
459e392
 
 
 
 
 
98b216f
459e392
 
 
98b216f
459e392
 
 
 
 
 
 
 
 
 
 
 
76e08e0
c103d7c
e53f54d
459e392
c103d7c
 
5f1a404
 
e5f80e3
98b216f
 
 
 
 
5e231af
98b216f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e231af
 
98b216f
5e231af
 
 
98b216f
5e231af
98b216f
 
 
 
5e231af
e53f54d
5e231af
98b216f
5e231af
98b216f
5e231af
 
98b216f
 
5e231af
 
 
98b216f
 
459e392
5f1a404
98b216f
5e231af
98b216f
5e231af
98b216f
 
 
5e231af
 
 
98b216f
 
5e231af
 
 
 
98b216f
 
 
 
5e231af
98b216f
 
 
 
 
 
 
 
 
 
5e231af
5f1a404
5e231af
98b216f
5e231af
98b216f
 
5e231af
98b216f
5e231af
 
 
98b216f
5e231af
98b216f
 
 
 
 
 
 
 
5e231af
98b216f
 
 
 
 
 
5e231af
 
98b216f
 
 
5f1a404
459e392
5f1a404
 
459e392
98b216f
459e392
 
5e231af
 
 
 
 
 
 
 
 
 
 
 
5f1a404
 
6d9d526
98b216f
6d9d526
98b216f
 
 
6d9d526
 
 
 
 
 
e5f80e3
98b216f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e231af
98b216f
76e08e0
6d9d526
 
 
 
 
98b216f
0e757ea
ad98685
6d9d526
5f1a404
98b216f
 
459e392
 
 
98b216f
 
3cec557
98b216f
3cec557
 
 
 
 
 
 
98b216f
3cec557
98b216f
 
e53f54d
98b216f
5e231af
459e392
ad98685
98b216f
 
3cec557
98b216f
 
 
3cec557
98b216f
 
 
ad98685
98b216f
 
ad98685
98b216f
 
ad98685
98b216f
 
ad98685
98b216f
 
ad98685
98b216f
 
ad98685
98b216f
ad98685
98b216f
e53f54d
98b216f
 
 
 
 
e53f54d
98b216f
459e392
 
 
5e231af
98b216f
 
6d9d526
 
98b216f
6d9d526
98b216f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d9d526
 
 
 
98b216f
 
 
 
e5f80e3
 
98b216f
6d9d526
 
 
98b216f
6d9d526
 
98b216f
76e08e0
98b216f
 
 
 
 
 
 
 
 
ad98685
 
98b216f
 
 
 
 
 
 
 
 
 
 
 
6d9d526
 
 
 
98b216f
6d9d526
 
 
98b216f
 
5f1a404
98b216f
 
 
 
 
 
 
5f1a404
 
98b216f
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
import json
import os
import re
import time
import urllib.parse
from typing import Any, Dict, List, Optional

import gradio as gr
import requests
import spaces
import torch
from PIL import Image, ImageDraw, ImageFont
from transformers import (
    AutoModelForVision2Seq,
    AutoProcessor,
)

# ์ตœ๊ณ  ํ’ˆ์งˆ์„ ์œ„ํ•œ ๋Œ€์šฉ๋Ÿ‰ ๋ชจ๋ธ (ZeroGPU duration ์ตœ์ ํ™”)
VL_MODEL_ID = "Qwen/Qwen2-VL-72B-Instruct"


def search_drug_web_simple(drug_name: str) -> str:
    """๊ฐ„๋‹จํ•œ ์›น ๊ฒ€์ƒ‰์œผ๋กœ ์•ฝ๋ฌผ ์ •๋ณด ๊ฒ€์ฆ"""
    try:
        clean_name = re.sub(r'\(.*?\)|\d+mg|\d+mL|์ •|ํฌ|์บก์А', '', drug_name).strip()
        sources = [
            f"https://www.health.kr/searchIdentity/search_result_detail.asp?searchStr={urllib.parse.quote(clean_name)}",
            f"https://terms.naver.com/search.naver?query={urllib.parse.quote(clean_name + ' ์•ฝ')}"
        ]

        for url in sources:
            try:
                response = requests.get(url, timeout=3, headers={'User-Agent': 'Mozilla/5.0'})
                if response.status_code == 200 and len(response.text) > 1000:
                    text = response.text[:3000]
                    if any(kw in text for kw in ["ํšจ๋Šฅ", "ํšจ๊ณผ", "๋ณต์šฉ", "์ฃผ์˜"]):
                        return f"โœ“ ์›น์—์„œ {clean_name} ์ •๋ณด๋ฅผ ์ฐพ์•˜์Šต๋‹ˆ๋‹ค."
            except:
                continue
        return ""
    except:
        return ""


def _load_font():
    """ํ•œ๊ธ€ ํฐํŠธ ๋กœ๋“œ"""
    font_path = "NotoSansKR-Regular.ttf"
    if not os.path.exists(font_path):
        try:
            url = "https://github.com/notofonts/noto-cjk/raw/main/Sans/OTF/Korean/NotoSansKR-Regular.otf"
            response = requests.get(url)
            with open(font_path, "wb") as f:
                f.write(response.content)
        except:
            return None
    try:
        return ImageFont.truetype(font_path, 16)
    except:
        return None


DEFAULT_FONT = _load_font()


def _load_vl_model():
    """๋Œ€์šฉ๋Ÿ‰ VL ๋ชจ๋ธ ๋กœ๋“œ - ์ตœ๋Œ€ ํ’ˆ์งˆ + ZeroGPU ์ตœ์ ํ™”"""
    device_map = "auto" if torch.cuda.is_available() else None

    # 8๋น„ํŠธ ์–‘์žํ™”๋กœ ๋ฉ”๋ชจ๋ฆฌ ์ ˆ์•ฝ (ํ’ˆ์งˆ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฉ”๋ชจ๋ฆฌ 1/2)
    model = AutoModelForVision2Seq.from_pretrained(
        VL_MODEL_ID,
        device_map=device_map,
        load_in_8bit=True,  # 8๋น„ํŠธ ์–‘์žํ™”
        trust_remote_code=True,
    )

    processor = AutoProcessor.from_pretrained(VL_MODEL_ID, trust_remote_code=True)
    return model, processor


print("๐Ÿ”„ Loading Qwen2-VL-72B model with 8-bit quantization...")
VL_MODEL, VL_PROCESSOR = _load_vl_model()
print("โœ… Model loaded successfully! (72B @ 8-bit)")


def _extract_assistant_content(decoded: str) -> str:
    """์–ด์‹œ์Šคํ„ดํŠธ ์‘๋‹ต ์ถ”์ถœ"""
    if "<|im_start|>assistant" in decoded:
        content = decoded.split("<|im_start|>assistant")[-1]
        content = content.replace("<|im_end|>", "").strip()
        return content
    return decoded.strip()


def _extract_json_block(text: str) -> Optional[str]:
    """JSON ๋ธ”๋ก ์ถ”์ถœ"""
    match = re.search(r"\{.*\}", text, re.DOTALL)
    if not match:
        return None
    return match.group(0)


def _sanitize_list(value: Any) -> List[str]:
    """๋ฆฌ์ŠคํŠธ ์ •์ œ"""
    if isinstance(value, (list, tuple)):
        return [str(v).strip() for v in value if str(v).strip()]
    if isinstance(value, str):
        return [v.strip() for v in re.split(r"[,;]", value) if v.strip()]
    return []


def _sanitize_medication(item: Dict[str, Any]) -> Dict[str, Any]:
    """์•ฝ๋ฌผ ์ •๋ณด ์ •์ œ"""
    def _to_str(val: Any) -> str:
        return "" if val is None else str(val).strip()

    times = item.get("times_per_day")
    if isinstance(times, (int, float)):
        times_str = str(int(times)) if float(times).is_integer() else str(times)
    else:
        times_str = _to_str(times)

    return {
        "name": _to_str(item.get("name")),
        "dose_per_intake": _to_str(item.get("dose_per_intake")),
        "times_per_day": times_str,
        "time_slots": _sanitize_list(item.get("time_slots")),
        "description": _to_str(item.get("description")),
        "efficacy": _to_str(item.get("efficacy")),
        "usage_precautions": _to_str(item.get("usage_precautions")),
        "side_effects": _to_str(item.get("side_effects")),
        "drug_interactions": _to_str(item.get("drug_interactions")),
        "warnings": _to_str(item.get("warnings")),
    }


def _parse_vl_response(text: str) -> Dict[str, Any]:
    """VL ๋ชจ๋ธ ์‘๋‹ต ํŒŒ์‹ฑ"""
    json_block = _extract_json_block(text)
    if not json_block:
        return {
            "raw_text": "",
            "medications": [],
            "warnings": ["๋ชจ๋ธ ์‘๋‹ต์—์„œ JSON ํ˜•์‹์„ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."],
        }

    try:
        data = json.loads(json_block)
    except json.JSONDecodeError:
        return {
            "raw_text": "",
            "medications": [],
            "warnings": ["JSON ํŒŒ์‹ฑ ์‹คํŒจ"],
        }

    meds_raw = data.get("medications") or []
    medications = []
    if isinstance(meds_raw, list):
        for item in meds_raw:
            if isinstance(item, dict):
                medications.append(_sanitize_medication(item))

    warnings_raw = data.get("warnings")
    if isinstance(warnings_raw, list):
        warnings = [str(w).strip() for w in warnings_raw if str(w).strip()]
    elif warnings_raw:
        warnings = [str(warnings_raw).strip()]
    else:
        warnings = []

    return {
        "raw_text": str(data.get("raw_text", "")).strip(),
        "medications": medications,
        "warnings": warnings,
    }


@spaces.GPU(duration=120)  # ์ตœ๋Œ€ 2๋ถ„ ํ—ˆ์šฉ
def analyze_with_vl_model(image: Image.Image, task: str = "ocr") -> Any:
    """
    ๋‹จ์ผ VL ๋ชจ๋ธ๋กœ ๋ชจ๋“  ์ž‘์—… ์ˆ˜ํ–‰
    task: "ocr" (์•ฝ๋ด‰ํˆฌ ๋ถ„์„) | "explain" (์„ค๋ช… ์ƒ์„ฑ) | "image_prompt" (์ด๋ฏธ์ง€ ํ”„๋กฌํ”„ํŠธ)
    """
    try:
        if task == "ocr":
            # ์•ฝ๋ด‰ํˆฌ OCR ๋ฐ ์ •๋ณด ์ถ”์ถœ
            instructions = """์‚ฌ์ง„ ์† ์•ฝ๋ด‰ํˆฌ/์ฒ˜๋ฐฉ์ „์„ ์ฝ๊ณ  JSON ํ˜•์‹์œผ๋กœ ๋‹ต๋ณ€ํ•˜์„ธ์š”."""

            schema = """{
  "raw_text": "OCR๋กœ ์ฝ์€ ์ „์ฒด ๋ฌธ์žฅ",
  "medications": [
    {
      "name": "์•ฝ ์ด๋ฆ„ (์ƒํ’ˆ๋ช…๊ณผ ์„ฑ๋ถ„๋ช…)",
      "dose_per_intake": "1ํšŒ ์šฉ๋Ÿ‰",
      "times_per_day": "ํ•˜๋ฃจ ๋ณต์šฉ ํšŸ์ˆ˜",
      "time_slots": ["๋ณต์šฉ ์‹œ๊ฐ„๋Œ€"],
      "description": "์•ฝ ์„ค๋ช…",
      "efficacy": "์ด ์•ฝ์€ ๋ฌด์—‡์ž…๋‹ˆ๊นŒ? (์ƒ์„ธํ•œ ํšจ๋Šฅํšจ๊ณผ)",
      "usage_precautions": "์ด ์•ฝ์€ ์–ด๋–ป๊ฒŒ ๋ณต์šฉํ•ฉ๋‹ˆ๊นŒ? (์ƒ์„ธํ•œ ๋ณต์šฉ๋ฒ•)",
      "side_effects": "์ฃผ์š” ๋ถ€์ž‘์šฉ",
      "drug_interactions": "์•ฝ๋ฌผ ์ƒํ˜ธ์ž‘์šฉ",
      "warnings": "ํŠน๋ณ„ ์ฃผ์˜์‚ฌํ•ญ"
    }
  ],
  "warnings": ["์ „์ฒด ๊ฒฝ๊ณ "]
}"""

            messages = [
                {
                    "role": "system",
                    "content": "๋‹น์‹ ์€ ๋Œ€ํ•œ๋ฏผ๊ตญ ์•ฝ์‚ฌ์ž…๋‹ˆ๋‹ค. ์•ฝ๋ด‰ํˆฌ๋ฅผ ์ •ํ™•ํžˆ ์ฝ๊ณ  ์ƒ์„ธํ•œ ์•ฝ๋ฌผ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.",
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": instructions},
                        {"type": "text", "text": schema},
                        {"type": "image"},
                    ],
                },
            ]

            chat_text = VL_PROCESSOR.apply_chat_template(messages, add_generation_prompt=True)
            inputs = VL_PROCESSOR(text=[chat_text], images=[image], return_tensors="pt").to(VL_MODEL.device)

            output_ids = VL_MODEL.generate(
                **inputs,
                max_new_tokens=3072,
                temperature=0.3,
                top_p=0.95,
                do_sample=True,
            )

            decoded = VL_PROCESSOR.batch_decode(output_ids, skip_special_tokens=False)[0]
            assistant_text = _extract_assistant_content(decoded)
            return _parse_vl_response(assistant_text)

        elif task == "explain":
            # ์„ค๋ช… ์ƒ์„ฑ (image๋Š” None, text๋งŒ ์‚ฌ์šฉ)
            return {"elderly_narrative": "", "child_narrative": "", "image_description": ""}

    except Exception as e:
        return {"error": str(e)}


def render_card(medications: List[Dict[str, Any]]) -> Image.Image:
    """ํ˜„๋Œ€์ ์ธ ์•ฝ๋ฌผ ์นด๋“œ ๋ Œ๋”๋ง"""
    try:
        font_large = ImageFont.truetype("NotoSansKR-Regular.ttf", 28)
        font_medium = ImageFont.truetype("NotoSansKR-Regular.ttf", 20)
        font_small = ImageFont.truetype("NotoSansKR-Regular.ttf", 16)
    except:
        font_large = font_medium = font_small = None

    if not medications:
        canvas = Image.new("RGB", (900, 300), (255, 255, 255))
        draw = ImageDraw.Draw(canvas)
        draw.text((350, 130), "์•ฝ ์ •๋ณด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค", fill=(140, 140, 140), font=font_medium)
        return canvas

    card_height_per_med = 240
    header_height = 120
    footer_height = 80
    total_height = header_height + (card_height_per_med * len(medications)) + footer_height

    width = 900
    canvas = Image.new("RGB", (width, total_height), (248, 250, 252))
    draw = ImageDraw.Draw(canvas)

    # ๋ชจ๋˜ ํ—ค๋”
    for i in range(header_height):
        alpha = i / header_height
        color = (
            int(99 + (248 - 99) * alpha),
            int(102 + (250 - 102) * alpha),
            int(241 + (252 - 241) * alpha),
        )
        draw.rectangle((0, i, width, i + 1), fill=color)

    draw.text((40, 35), "๐Ÿ’Š ๋ณต์šฉ ์•ˆ๋‚ด", fill=(30, 41, 59), font=font_large)
    draw.text((40, 75), f"{len(medications)}๊ฐœ ์•ฝํ’ˆ", fill=(71, 85, 105), font=font_small)

    y = header_height + 30

    for idx, med in enumerate(medications):
        card_y_start = y - 15
        card_y_end = y + 200

        # ์นด๋“œ ๊ทธ๋ฆผ์ž
        draw.rounded_rectangle(
            (35, card_y_start + 5, width - 35, card_y_end + 5),
            radius=16,
            fill=(203, 213, 225),
        )

        # ์นด๋“œ ๋ณธ์ฒด
        draw.rounded_rectangle(
            (30, card_y_start, width - 30, card_y_end),
            radius=16,
            fill=(255, 255, 255),
        )

        # ์•ฝ ๋ฒˆํ˜ธ ๋ฐฐ์ง€
        badge_x, badge_y = 45, y
        draw.ellipse(
            (badge_x, badge_y, badge_x + 45, badge_y + 45),
            fill=(99, 102, 241),
        )
        draw.text((badge_x + 12, badge_y + 8), str(idx + 1), fill=(255, 255, 255), font=font_medium)

        # ์•ฝ ์ด๋ฆ„
        name_text = med.get("name", "์•ฝ ์ด๋ฆ„ ๋ฏธํ™•์ธ")
        draw.text((105, y + 8), name_text, fill=(15, 23, 42), font=font_medium)

        y += 60

        # ์ •๋ณด ์„น์…˜
        info_items = [
            ("๐Ÿ“ฆ", "์šฉ๋Ÿ‰", med.get('dose_per_intake', '-')),
            ("๐Ÿ”ข", "ํšŸ์ˆ˜", f"{med.get('times_per_day', '-')}ํšŒ/์ผ"),
            ("๐Ÿ•", "์‹œ๊ฐ„", ", ".join(med.get('time_slots') or ["-"])),
        ]

        for icon, label, value in info_items:
            draw.text((50, y), f"{icon} {label}", fill=(100, 116, 139), font=font_small)
            draw.text((160, y), value, fill=(30, 41, 59), font=font_small)
            y += 38

        y += 30

    # ํ‘ธํ„ฐ
    footer_y = total_height - footer_height + 25
    draw.text((40, footer_y), "โ€ป ๋ณธ ์•ฑ์€ ์ฐธ๊ณ ์šฉ์ด๋ฉฐ, ์‹ค์ œ ๋ณต์•ฝ์€ ์˜์‚ฌยท์•ฝ์‚ฌ์˜ ์ง€์‹œ๋ฅผ ๋”ฐ๋ผ์ฃผ์„ธ์š”.",
              fill=(148, 163, 184), font=font_small)

    return canvas


def medications_to_csv(medications: List[Dict[str, Any]]) -> str:
    """CSV ์ƒ์„ฑ"""
    if not medications:
        return ""

    rows = ["์•ฝ๋ช…,1ํšŒ์šฉ๋Ÿ‰,1์ผํšŸ์ˆ˜,์‹œ๊ฐ„๋Œ€"]
    for med in medications:
        row = [
            med.get("name", ""),
            med.get("dose_per_intake", ""),
            med.get("times_per_day", ""),
            ";".join(med.get("time_slots") or []),
        ]
        rows.append(",".join(row))

    return "\n".join(rows)


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)


@spaces.GPU(duration=90)  # ์„ค๋ช… ์ƒ์„ฑ์€ 90์ดˆ
def generate_full_explanation(medications: List[Dict[str, Any]], raw_text: str, web_info: str = "") -> Dict[str, str]:
    """VL ๋ชจ๋ธ๋กœ ์„ค๋ช… ์ƒ์„ฑ"""
    try:
        med_summary = "\n".join([
            f"- {med.get('name')} {med.get('dose_per_intake')} (ํ•˜๋ฃจ {med.get('times_per_day')}ํšŒ)"
            for med in medications
        ])

        web_context = f"\n\n์›น ๊ฒ€์ฆ: {web_info}" if web_info else ""

        prompt = f"""๋‹ค์Œ ์•ฝ๋ฌผ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์–ด๋ฅด์‹ ๊ณผ ์–ด๋ฆฐ์ด๋ฅผ ์œ„ํ•œ ์„ค๋ช…์„ ์ž‘์„ฑํ•˜์„ธ์š”.

์•ฝ ์ •๋ณด:
{med_summary}

์›๋ฌธ: {raw_text}{web_context}

JSON ํ˜•์‹์œผ๋กœ ๋‹ต๋ณ€:
{{
  "elderly": {{
    "narrative": "์–ด๋ฅด์‹ ์„ ์œ„ํ•œ ์„ค๋ช… (์กด๋Œ“๋ง, ๊ตฌ์ฒด์ , 5-7๋ฌธ์žฅ)",
    "image_description": "์•ฝ ๋ณต์šฉ ์žฅ๋ฉด ๋ฌ˜์‚ฌ (ํ•œ๊ตญ์–ด)"
  }},
  "child": {{
    "narrative": "์–ด๋ฆฐ์ด๋ฅผ ์œ„ํ•œ ์„ค๋ช… (์‰ฌ์šด ๋ง, ์žฌ๋ฏธ์žˆ๊ฒŒ, 4-6๋ฌธ์žฅ)",
    "image_description": "์•ฝ ๋ณต์šฉ ์žฅ๋ฉด ๋ฌ˜์‚ฌ (ํ•œ๊ตญ์–ด)"
  }}
}}"""

        messages = [
            {
                "role": "system",
                "content": "๋‹น์‹ ์€ 20๋…„ ๊ฒฝ๋ ฅ ์ž„์ƒ์•ฝ์‚ฌ์ž…๋‹ˆ๋‹ค. ํ™˜์ž ๊ต์œก ์ „๋ฌธ๊ฐ€์ž…๋‹ˆ๋‹ค.",
            },
            {
                "role": "user",
                "content": prompt,
            },
        ]

        chat_text = VL_PROCESSOR.apply_chat_template(messages, add_generation_prompt=True)
        inputs = VL_PROCESSOR(text=[chat_text], images=None, return_tensors="pt").to(VL_MODEL.device)

        output_ids = VL_MODEL.generate(
            **inputs,
            max_new_tokens=2048,
            temperature=0.8,
            top_p=0.92,
            do_sample=True,
        )

        decoded = VL_PROCESSOR.batch_decode(output_ids, skip_special_tokens=False)[0]
        text = _extract_assistant_content(decoded)

        json_block = _extract_json_block(text)
        if json_block:
            data = json.loads(json_block)
            elderly = data.get("elderly", {})
            child = data.get("child", {})

            return {
                "elderly_narrative": str(elderly.get("narrative", "")).strip(),
                "child_narrative": str(child.get("narrative", "")).strip(),
            }

        return {
            "elderly_narrative": "์„ค๋ช…์„ ์ƒ์„ฑํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.",
            "child_narrative": "์„ค๋ช…์„ ์ƒ์„ฑํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.",
        }

    except Exception as e:
        return {
            "elderly_narrative": "์„ค๋ช… ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ",
            "child_narrative": "์„ค๋ช… ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ",
        }


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

    progress(0, desc="๐Ÿ” ์•ฝ๋ด‰ํˆฌ ์ด๋ฏธ์ง€ ๋ถ„์„ ์ค‘...")
    result = analyze_with_vl_model(image, task="ocr")

    medications = result.get("medications") or []

    # ์›น ๊ฒ€์ƒ‰
    progress(0.25, desc="๐ŸŒ ์›น์—์„œ ์•ฝ๋ฌผ ์ •๋ณด ๊ฒ€์ฆ ์ค‘...")
    web_info_results = []
    for med in medications[:3]:
        drug_name = med.get("name", "")
        if drug_name:
            web_info = search_drug_web_simple(drug_name)
            if web_info:
                web_info_results.append(web_info)
                med["web_verified"] = True

    web_search_info = "\n".join(web_info_results) if web_info_results else ""

    progress(0.5, desc="๐Ÿ’ฌ ์„ค๋ช… ์ƒ์„ฑ ์ค‘...")
    narratives = generate_full_explanation(medications, result.get("raw_text", ""), web_search_info)

    progress(0.75, desc="๐ŸŽจ ์นด๋“œ ๋ Œ๋”๋ง ์ค‘...")
    card_img = render_card(medications)
    csv_row = medications_to_csv(medications)

    # ์ƒ์„ธ ์ •๋ณด
    detailed_info = "# ๐Ÿ’Š ์•ฝ๋ฌผ ์ƒ์„ธ ์ •๋ณด\n\n"

    if web_search_info:
        detailed_info += "โœ… **์›น ๊ฒ€์ฆ ์™„๋ฃŒ**\n\n"
        detailed_info += f"> {web_search_info}\n\n---\n\n"

    for idx, med in enumerate(medications):
        web_badge = " ๐ŸŒ" if med.get("web_verified") else ""
        detailed_info += f"## {idx + 1}. {med.get('name', '์•ฝ ์ด๋ฆ„ ๋ฏธํ™•์ธ')}{web_badge}\n\n"

        if med.get("efficacy"):
            detailed_info += f"### ๐Ÿ” ์ด ์•ฝ์€ ๋ฌด์—‡์ž…๋‹ˆ๊นŒ?\n{med.get('efficacy')}\n\n"

        if med.get("usage_precautions"):
            detailed_info += f"### ๐Ÿ“‹ ์ด ์•ฝ์€ ์–ด๋–ป๊ฒŒ ๋ณต์šฉํ•ฉ๋‹ˆ๊นŒ?\n{med.get('usage_precautions')}\n\n"

        if med.get("side_effects"):
            detailed_info += f"### โš ๏ธ ๋ถ€์ž‘์šฉ\n{med.get('side_effects')}\n\n"

        if med.get("drug_interactions"):
            detailed_info += f"### ๐Ÿ”„ ์•ฝ๋ฌผ ์ƒํ˜ธ์ž‘์šฉ\n{med.get('drug_interactions')}\n\n"

        if med.get("warnings"):
            detailed_info += f"### โšก ํŠน๋ณ„ ์ฃผ์˜์‚ฌํ•ญ\n{med.get('warnings')}\n\n"

        detailed_info += "---\n\n"

    # ์„ค๋ช… ๋งˆํฌ๋‹ค์šด
    markdown = (
        "## ๐Ÿ‘ด ์–ด๋ฅด์‹ ์„ ์œ„ํ•œ ์„ค๋ช…\n\n"
        + (narratives.get("elderly_narrative") or "์„ค๋ช…์„ ์ค€๋น„ํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
        + "\n\n## ๐Ÿ‘ถ ์–ด๋ฆฐ์ด๋ฅผ ์œ„ํ•œ ์„ค๋ช…\n\n"
        + (narratives.get("child_narrative") or "์„ค๋ช…์„ ์ค€๋น„ํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
        + "\n\n> ๐Ÿ’ก ํ•ญ์ƒ ์˜๋ฃŒ์ง„์˜ ์•ˆ๋‚ด๋ฅผ ์šฐ์„ ํ•˜์„ธ์š”."
    )

    warnings_md = format_warnings(result.get("warnings", []))
    raw_text = result.get("raw_text", "")
    json_text = json.dumps(result, ensure_ascii=False, indent=2)

    progress(1.0, desc="โœ… ์™„๋ฃŒ!")
    return json_text, card_img, csv_row, markdown, warnings_md, raw_text, detailed_info


# ํ˜„๋Œ€์ ์ธ CSS
CUSTOM_CSS = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

:root {
    --primary: #6366f1;
    --primary-dark: #4f46e5;
    --secondary: #8b5cf6;
    --success: #10b981;
    --warning: #f59e0b;
    --danger: #ef4444;
    --gray-50: #f9fafb;
    --gray-100: #f3f4f6;
    --gray-200: #e5e7eb;
    --gray-300: #d1d5db;
    --gray-600: #4b5563;
    --gray-800: #1f2937;
    --gray-900: #111827;
}

body {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.gradio-container {
    max-width: 1400px !important;
    margin: auto;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 24px;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    padding: 40px;
}

.hero-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20px;
    padding: 50px 40px;
    margin-bottom: 40px;
    color: white;
    box-shadow: 0 20px 40px -10px rgba(102, 126, 234, 0.4);
}

.hero-section h1 {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 16px;
    text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.hero-section p {
    font-size: 1.15rem;
    opacity: 0.95;
    line-height: 1.6;
}

.card {
    background: white;
    border-radius: 16px;
    padding: 32px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
}

.card:hover {
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    transform: translateY(-2px);
}

.primary-btn button {
    background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600 !important;
    font-size: 1.05rem !important;
    padding: 16px 32px !important;
    border-radius: 12px !important;
    box-shadow: 0 10px 20px -5px rgba(99, 102, 241, 0.4) !important;
    transition: all 0.3s ease !important;
}

.primary-btn button:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 15px 30px -5px rgba(99, 102, 241, 0.5) !important;
}

.tab-nav button {
    font-weight: 500 !important;
    border-radius: 8px !important;
    transition: all 0.2s ease !important;
}

.tab-nav button.selected {
    background: var(--primary) !important;
    color: white !important;
}

.notice {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-left: 4px solid var(--warning);
    border-radius: 12px;
    padding: 20px;
    color: var(--gray-800);
}

.output-card {
    background: var(--gray-50);
    border-radius: 16px;
    padding: 28px;
    border: 1px solid var(--gray-200);
}

.gr-image {
    border-radius: 16px !important;
    box-shadow: 0 10px 20px -5px rgba(0, 0, 0, 0.1) !important;
}

.csv-box textarea {
    font-family: 'JetBrains Mono', 'Courier New', monospace !important;
    font-size: 0.9rem !important;
    background: var(--gray-900) !important;
    color: #10b981 !important;
    border-radius: 12px !important;
}

.accordion {
    border-radius: 12px !important;
    border: 1px solid var(--gray-200) !important;
}

h1, h2, h3 {
    font-weight: 600;
    color: var(--gray-900);
}

.markdown-text {
    line-height: 1.8;
    color: var(--gray-800);
}
"""

HERO_HTML = """
<div class="hero-section">
    <h1>๐Ÿฅ MedCard Pro</h1>
    <p>
        <strong>AI ๊ธฐ๋ฐ˜ ์Šค๋งˆํŠธ ์•ฝ๋ฌผ ๊ด€๋ฆฌ ์‹œ์Šคํ…œ</strong><br>
        Qwen2-VL-72B (8๋น„ํŠธ ์ตœ์ ํ™”)๊ฐ€ ์•ฝ๋ด‰ํˆฌ๋ฅผ ์ตœ๊ณ  ์ •ํ™•๋„๋กœ ๋ถ„์„ํ•˜๊ณ ,<br>
        ์›น์—์„œ ์‹ค์‹œ๊ฐ„์œผ๋กœ ์ •๋ณด๋ฅผ ๊ฒ€์ฆํ•˜์—ฌ ํ”„๋กœํŽ˜์…”๋„ํ•œ ๋ณต์•ฝ ์•ˆ๋‚ด๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.
    </p>
</div>
"""

# Gradio ์ธํ„ฐํŽ˜์ด์Šค
with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
    gr.HTML(HERO_HTML)

    with gr.Row():
        with gr.Column(scale=5, elem_classes=["card"]):
            gr.Markdown("### ๐Ÿ“ธ ์•ฝ ๋ด‰ํˆฌ ์‚ฌ์ง„ ์—…๋กœ๋“œ")
            img_in = gr.Image(type="pil", label="์•ฝ๋ด‰ํˆฌ/์ฒ˜๋ฐฉ์ „ ์‚ฌ์ง„", height=400)
            warn_md = gr.Markdown("๐Ÿ’ก ์•ฝ ๋ด‰ํˆฌ ์‚ฌ์ง„์„ ์˜ฌ๋ ค์ฃผ์„ธ์š”. AI๊ฐ€ ์ž๋™์œผ๋กœ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค.", elem_classes=["notice"])
            btn = gr.Button("๐Ÿš€ ๋ถ„์„ ์‹œ์ž‘", elem_classes=["primary-btn"], size="lg")

        with gr.Column(scale=7, elem_classes=["card"]):
            gr.Markdown("### ๐Ÿ“Š ๋ถ„์„ ๊ฒฐ๊ณผ")

            with gr.Tabs():
                with gr.Tab("๐Ÿ“š ์•ฝ๋ฌผ ์ƒ์„ธ ์ •๋ณด"):
                    detailed_info_md = gr.Markdown("๋ถ„์„์„ ์‹œ์ž‘ํ•˜๋ฉด ์—ฌ๊ธฐ์— ์•ฝ๋ฌผ ์ •๋ณด๊ฐ€ ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.", elem_classes=["output-card"])

                with gr.Tab("๐Ÿ‘ฅ ์‰ฌ์šด ์„ค๋ช…"):
                    explain_md = gr.Markdown("์–ด๋ฅด์‹ ๊ณผ ์–ด๋ฆฐ์ด๋ฅผ ์œ„ํ•œ ์„ค๋ช…์ด ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.", elem_classes=["output-card"])

                with gr.Tab("๐Ÿ“… ๋ณต์šฉ ์ผ์ •"):
                    card_out = gr.Image(type="pil", label="์ผ์ • ์นด๋“œ")

            with gr.Accordion("๐Ÿ” ์ƒ์„ธ ๋ถ„์„ ๊ฒฐ๊ณผ", open=False):
                raw_box = gr.Textbox(label="OCR ์›๋ฌธ", lines=4, interactive=False)
                csv_box = gr.Textbox(label="CSV ๋ฐ์ดํ„ฐ", lines=3, elem_classes=["csv-box"])
                json_out = gr.Code(label="JSON ๋ฐ์ดํ„ฐ", language="json")

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

    gr.Markdown(
        """
        ---

        ### โ„น๏ธ ์ฃผ์˜์‚ฌํ•ญ

        ์ด ์„œ๋น„์Šค๋Š” **์ฐธ๊ณ ์šฉ ๋„๊ตฌ**์ž…๋‹ˆ๋‹ค. ์‹ค์ œ ๋ณต์•ฝ์€ ๋ฐ˜๋“œ์‹œ **์˜์‚ฌยท์•ฝ์‚ฌ์˜ ์ง€์‹œ**์— ๋”ฐ๋ผ์ฃผ์„ธ์š”.

        ๐Ÿ”’ ๊ฐœ์ธ์ •๋ณด๋Š” ์ €์žฅ๋˜์ง€ ์•Š์œผ๋ฉฐ, ๋ชจ๋“  ์ฒ˜๋ฆฌ๋Š” ์‹ค์‹œ๊ฐ„์œผ๋กœ ์ด๋ฃจ์–ด์ง‘๋‹ˆ๋‹ค.
        """
    )

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