feat: add qwen explanations and refined ui
Browse files- app.py +157 -18
- requirements.txt +1 -1
app.py
CHANGED
|
@@ -5,20 +5,34 @@ from typing import Any, Dict, List, Optional, Sequence
|
|
| 5 |
import gradio as gr
|
| 6 |
import torch
|
| 7 |
from PIL import Image, ImageDraw
|
| 8 |
-
from transformers import pipeline
|
| 9 |
|
| 10 |
# --- OCR pipeline ---------------------------------------------------------
|
| 11 |
# Use a high-capacity OCR model for better accuracy on prescription labels.
|
| 12 |
-
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def _load_ocr():
|
| 16 |
device = 0 if torch.cuda.is_available() else -1
|
| 17 |
-
return pipeline("image-to-text", model=
|
| 18 |
|
| 19 |
|
| 20 |
ocr = _load_ocr()
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
# Korean keywords describing time slots on prescription labels.
|
| 23 |
TIME_KEYWORDS = [
|
| 24 |
"μμΉ¨",
|
|
@@ -201,7 +215,7 @@ def _match_knowledge(name: str) -> Optional[Dict[str, Any]]:
|
|
| 201 |
return None
|
| 202 |
|
| 203 |
|
| 204 |
-
def
|
| 205 |
meds = output["fields"].get("medications") or []
|
| 206 |
if not meds:
|
| 207 |
return (
|
|
@@ -236,30 +250,155 @@ def build_explanations(output: Dict[str, Any]) -> str:
|
|
| 236 |
return "\n".join(lines)
|
| 237 |
|
| 238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
def run_pipeline(image: Optional[Image.Image]):
|
| 240 |
if image is None:
|
| 241 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
output = ocr_and_parse(image)
|
| 244 |
card = render_card(output["fields"])
|
| 245 |
csv_row = to_csv_row(output)
|
| 246 |
json_text = json.dumps(output, ensure_ascii=False, indent=2)
|
| 247 |
explanations = build_explanations(output)
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
with gr.Row():
|
| 254 |
-
with gr.Column():
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
| 260 |
card_out = gr.Image(type="pil", label="μΌμ μΉ΄λ(미리보기)")
|
| 261 |
-
|
| 262 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
|
| 265 |
if __name__ == "__main__":
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
import torch
|
| 7 |
from PIL import Image, ImageDraw
|
| 8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 9 |
|
| 10 |
# --- OCR pipeline ---------------------------------------------------------
|
| 11 |
# Use a high-capacity OCR model for better accuracy on prescription labels.
|
| 12 |
+
OCR_MODEL_ID = "microsoft/trocr-large-printed"
|
| 13 |
+
LLM_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 14 |
|
| 15 |
|
| 16 |
def _load_ocr():
|
| 17 |
device = 0 if torch.cuda.is_available() else -1
|
| 18 |
+
return pipeline("image-to-text", model=OCR_MODEL_ID, device=device)
|
| 19 |
|
| 20 |
|
| 21 |
ocr = _load_ocr()
|
| 22 |
|
| 23 |
+
|
| 24 |
+
def _load_llm():
|
| 25 |
+
device_map = "auto" if torch.cuda.is_available() else None
|
| 26 |
+
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 27 |
+
model = AutoModelForCausalLM.from_pretrained(LLM_MODEL_ID, device_map=device_map, torch_dtype=dtype)
|
| 28 |
+
if device_map is None:
|
| 29 |
+
model = model.to(torch.device("cpu"))
|
| 30 |
+
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID)
|
| 31 |
+
return model, tokenizer
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
LLM_MODEL, LLM_TOKENIZER = _load_llm()
|
| 35 |
+
|
| 36 |
# Korean keywords describing time slots on prescription labels.
|
| 37 |
TIME_KEYWORDS = [
|
| 38 |
"μμΉ¨",
|
|
|
|
| 215 |
return None
|
| 216 |
|
| 217 |
|
| 218 |
+
def build_kb_explanations(output: Dict[str, Any]) -> str:
|
| 219 |
meds = output["fields"].get("medications") or []
|
| 220 |
if not meds:
|
| 221 |
return (
|
|
|
|
| 250 |
return "\n".join(lines)
|
| 251 |
|
| 252 |
|
| 253 |
+
def generate_llm_explanations(output: Dict[str, Any]) -> str:
|
| 254 |
+
meds = output["fields"].get("medications") or []
|
| 255 |
+
if not meds:
|
| 256 |
+
return (
|
| 257 |
+
"μ½ μ΄λ¦μ μ λλ‘ μΈμνμ§ λͺ»νμ΄μ. μ¬μ§μ λ€μ μ°κ±°λ μ½μ¬μκ² μ§μ νμΈν΄ μ£ΌμΈμ."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
med_lines = []
|
| 261 |
+
for idx, med in enumerate(meds, 1):
|
| 262 |
+
name = med.get("name") or "μ΄λ¦ λ―ΈνμΈ"
|
| 263 |
+
dose = med.get("dose") or "μ©λ μ 보 μμ"
|
| 264 |
+
med_lines.append(f"{idx}. {name} β {dose}")
|
| 265 |
+
|
| 266 |
+
context = "\n".join(med_lines)
|
| 267 |
+
raw_text = output.get("raw_text", "")
|
| 268 |
+
|
| 269 |
+
system_prompt = (
|
| 270 |
+
"λΉμ μ μ½μ¬ μ μλμ
λλ€. μ΄λ €μ΄ μν μ©μ΄λ₯Ό μ°μ§ λ§κ³ , μ€νμλ μ΄ν΄ν μ μλ λ§ν¬λ‘ μΉμ νκ² μ€λͺ
νμΈμ."
|
| 271 |
+
)
|
| 272 |
+
user_prompt = (
|
| 273 |
+
"λ€μμ μ½λ΄ν¬ OCR κ²°κ³Όμ
λλ€. μ½ μ΄λ¦κ³Ό μ©λ μ 보λ₯Ό μ°Έκ³ ν΄ κ° μ½μ μν μ μ½κ² μ€λͺ
νκ³ , μΈμ 볡μ©νλ©΄ μ’μμ§ μμ, μ£Όμμ¬νμ bulletλ‘ μ λ¦¬ν΄ μ£ΌμΈμ.\n"
|
| 274 |
+
f"μ½ λͺ©λ‘:\n{context}\n\nOCR μλ¬Έ:\n{raw_text}\n\nμΆλ ₯ νμ:\n- μ½ μ΄λ¦: ...\n - ν μ€ μ€λͺ
\n - μμ μν©\n - μ£Όμν μ \nλ§μ§λ§μλ μλ£μ§ λ³΅μ½ μ§μλ₯Ό λ°λμ λ°λΌμΌ νλ€λ λ¬Έμ₯μ λ§λΆμ¬ μ£ΌμΈμ."
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
messages = [
|
| 278 |
+
{"role": "system", "content": system_prompt},
|
| 279 |
+
{"role": "user", "content": user_prompt},
|
| 280 |
+
]
|
| 281 |
+
|
| 282 |
+
input_ids = LLM_TOKENIZER.apply_chat_template(
|
| 283 |
+
messages,
|
| 284 |
+
add_generation_prompt=True,
|
| 285 |
+
return_tensors="pt",
|
| 286 |
+
)
|
| 287 |
+
input_ids = input_ids.to(LLM_MODEL.device)
|
| 288 |
+
|
| 289 |
+
with torch.no_grad():
|
| 290 |
+
output_ids = LLM_MODEL.generate(
|
| 291 |
+
input_ids,
|
| 292 |
+
max_new_tokens=480,
|
| 293 |
+
temperature=0.7,
|
| 294 |
+
top_p=0.9,
|
| 295 |
+
do_sample=True,
|
| 296 |
+
eos_token_id=LLM_TOKENIZER.eos_token_id,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
generated_ids = output_ids[0][input_ids.shape[1]:]
|
| 300 |
+
text = LLM_TOKENIZER.decode(generated_ids, skip_special_tokens=True).strip()
|
| 301 |
+
return text
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def build_explanations(output: Dict[str, Any]) -> str:
|
| 305 |
+
try:
|
| 306 |
+
llm_text = generate_llm_explanations(output)
|
| 307 |
+
if llm_text:
|
| 308 |
+
return llm_text
|
| 309 |
+
except Exception as err: # pragma: no cover - safe fallback
|
| 310 |
+
print(f"[WARN] LLM generation failed: {err}", flush=True)
|
| 311 |
+
return build_kb_explanations(output)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def format_warnings(warnings: List[str]) -> str:
|
| 315 |
+
if not warnings:
|
| 316 |
+
return "β
μΈμλ μ λ³΄κ° μΆ©λΆν΄μ. λ³΅μ½ μκ°λ§ μ μ§μΌ μ£ΌμΈμ."
|
| 317 |
+
lines = ["### νμΈν΄ μ£ΌμΈμ"]
|
| 318 |
+
for warn in warnings:
|
| 319 |
+
lines.append(f"- {warn}")
|
| 320 |
+
lines.append("\n> μλ£μ§μ μ§μκ° κ°μ₯ μ νν©λλ€.")
|
| 321 |
+
return "\n".join(lines)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
def run_pipeline(image: Optional[Image.Image]):
|
| 325 |
if image is None:
|
| 326 |
+
return (
|
| 327 |
+
"μ΄λ―Έμ§λ₯Ό μ
λ‘λνμΈμ.",
|
| 328 |
+
None,
|
| 329 |
+
None,
|
| 330 |
+
"μ΄λ―Έμ§λ₯Ό λ¨Όμ μ
λ‘λν΄ μ£ΌμΈμ.",
|
| 331 |
+
"π· μ½ λ΄ν¬ μ¬μ§μ μ¬λ¦¬λ©΄ μΈμμ΄ μμλΌμ.",
|
| 332 |
+
)
|
| 333 |
|
| 334 |
output = ocr_and_parse(image)
|
| 335 |
card = render_card(output["fields"])
|
| 336 |
csv_row = to_csv_row(output)
|
| 337 |
json_text = json.dumps(output, ensure_ascii=False, indent=2)
|
| 338 |
explanations = build_explanations(output)
|
| 339 |
+
warnings_md = format_warnings(output.get("warnings", []))
|
| 340 |
+
return json_text, card, csv_row, explanations, warnings_md
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
CUSTOM_CSS = """
|
| 344 |
+
body {background: radial-gradient(circle at top left, #f5f0ff 0%, #fff7ec 60%, #ffffff 100%);}
|
| 345 |
+
.gradio-container {max-width: 1180px !important; margin: auto; font-family: 'Noto Sans KR', sans-serif;}
|
| 346 |
+
.hero {
|
| 347 |
+
background: linear-gradient(120deg, rgba(123, 97, 255, 0.12), rgba(255, 207, 117, 0.18));
|
| 348 |
+
border-radius: 28px;
|
| 349 |
+
padding: 36px 44px;
|
| 350 |
+
box-shadow: 0 20px 40px rgba(66, 46, 138, 0.08);
|
| 351 |
+
margin-bottom: 32px;
|
| 352 |
+
}
|
| 353 |
+
.hero h1 {font-size: 2.4rem; font-weight: 700; color: #1f1c3b; margin-bottom: 12px;}
|
| 354 |
+
.hero p {color: #514c7b; font-size: 1.05rem; line-height: 1.6; max-width: 640px;}
|
| 355 |
+
.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);}
|
| 356 |
+
.panel-title {font-weight: 700; font-size: 1.2rem; margin-bottom: 18px; color: #2f2355;}
|
| 357 |
+
.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);}
|
| 358 |
+
.primary-btn button:hover {opacity: 0.95; transform: translateY(-1px);}
|
| 359 |
+
.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);}
|
| 360 |
+
.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);}
|
| 361 |
+
.csv-box textarea {font-family: 'JetBrains Mono', monospace;}
|
| 362 |
+
.gr-image {border-radius: 20px !important; box-shadow: 0 10px 20px rgba(60, 40, 120, 0.15);}
|
| 363 |
+
.accordion {border-radius: 20px !important;}
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
HERO_HTML = """
|
| 367 |
+
<div class="hero">
|
| 368 |
+
<h1>MedCard-KR Β· μ½λ΄ν¬ ν μ»·μΌλ‘ μ΄ν΄νλ λ³΅μ© μλ΄</h1>
|
| 369 |
+
<p>μ¬μ§ μ μ½ μ΄λ¦μ OCRλ‘ μ½μ΄ λ€μ΄κ³ , Qwen LLMμ΄ μ€νμλ μ΄ν΄ν μ μλ λ§ν¬λ‘ μ½μ μ€λͺ
ν΄ λ립λλ€.
|
| 370 |
+
λ³΅μ© μΌμ μΉ΄λμ CSVκΉμ§ ν λ²μ λ°μ 보μΈμ.</p>
|
| 371 |
+
</div>
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
|
| 376 |
+
gr.HTML(HERO_HTML)
|
| 377 |
with gr.Row():
|
| 378 |
+
with gr.Column(scale=4, elem_classes=["glass-panel"]):
|
| 379 |
+
gr.Markdown("### 1. μ½ λ΄ν¬ μ¬μ§μ μ
λ‘λνμΈμ")
|
| 380 |
+
img_in = gr.Image(type="pil", label="μ½ λ΄ν¬/λΌλ²¨ μ¬μ§", height=360)
|
| 381 |
+
warn_md = gr.Markdown("π· μ½ λ΄ν¬ μ¬μ§μ μ¬λ¦¬λ©΄ μΈμμ΄ μμλΌμ.", elem_classes=["notice"])
|
| 382 |
+
btn = gr.Button("μΈμ & μ€λͺ
μμ±", elem_classes=["primary-btn"])
|
| 383 |
+
with gr.Column(scale=6, elem_classes=["glass-panel"]):
|
| 384 |
+
gr.Markdown("### 2. κ²°κ³Όλ₯Ό νμΈνμΈμ")
|
| 385 |
+
explain_md = gr.Markdown("μ¬κΈ°μ μ½ μ€λͺ
μ΄ νμλ©λλ€.", elem_classes=["output-card"])
|
| 386 |
card_out = gr.Image(type="pil", label="μΌμ μΉ΄λ(미리보기)")
|
| 387 |
+
csv_box = gr.Textbox(label="CSV(μ½λͺ
,1νμ©λ,1μΌνμ,μκ°λ)", lines=2, elem_classes=["csv-box"])
|
| 388 |
+
with gr.Accordion("μΈλΆ JSON κ²°κ³Ό", open=False, elem_classes=["accordion"]):
|
| 389 |
+
json_out = gr.Code(label="μΈμ κ²°κ³Ό(JSON)")
|
| 390 |
+
|
| 391 |
+
btn.click(
|
| 392 |
+
run_pipeline,
|
| 393 |
+
inputs=img_in,
|
| 394 |
+
outputs=[json_out, card_out, csv_box, explain_md, warn_md],
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
gr.Markdown(
|
| 398 |
+
"""
|
| 399 |
+
> βΉοΈ **μ£Όμ**: μ΄ μλΉμ€λ μ°Έκ³ μ© λꡬμ΄λ©°, μ€μ 볡μ½μ λ°λμ μμ¬Β·μ½μ¬μ μ§μμ λ°λΌ μ£ΌμΈμ.
|
| 400 |
+
"""
|
| 401 |
+
)
|
| 402 |
|
| 403 |
|
| 404 |
if __name__ == "__main__":
|
requirements.txt
CHANGED
|
@@ -2,4 +2,4 @@ transformers
|
|
| 2 |
torch
|
| 3 |
gradio
|
| 4 |
Pillow
|
| 5 |
-
|
|
|
|
| 2 |
torch
|
| 3 |
gradio
|
| 4 |
Pillow
|
| 5 |
+
sentencepiece
|