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() |