sdfdsfads2333
Browse files
app.py
CHANGED
|
@@ -1,39 +1,58 @@
|
|
| 1 |
import json
|
| 2 |
import re
|
| 3 |
-
from typing import List, Optional
|
| 4 |
|
| 5 |
import gradio as gr
|
| 6 |
import spaces
|
| 7 |
import torch
|
| 8 |
from PIL import Image
|
| 9 |
-
from transformers import
|
| 10 |
-
Qwen2VLForConditionalGeneration,
|
| 11 |
-
AutoProcessor,
|
| 12 |
-
)
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
def _load_vl_model():
|
| 19 |
-
"""VL ๋ชจ๋ธ ๋ก๋ - 8๋นํธ ์์ํ + FP16"""
|
| 20 |
-
device_map = "auto" if torch.cuda.is_available() else None
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
load_in_8bit=True,
|
| 26 |
torch_dtype=torch.float16,
|
| 27 |
trust_remote_code=True,
|
| 28 |
)
|
| 29 |
|
| 30 |
-
|
| 31 |
-
return model,
|
| 32 |
|
| 33 |
|
| 34 |
-
print("๐ Loading
|
| 35 |
-
|
| 36 |
-
print("โ
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def _extract_assistant_content(decoded: str) -> str:
|
|
@@ -53,84 +72,120 @@ def _extract_json_block(text: str) -> Optional[str]:
|
|
| 53 |
return match.group(0)
|
| 54 |
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
"""์ด๋ฏธ์ง์์ ์ฝ ์ด๋ฆ๋ง ์ถ์ถ"""
|
| 59 |
try:
|
| 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 |
return ["์ฝ ์ด๋ฆ์ ์ฐพ์ง ๋ชปํ์ต๋๋ค."]
|
| 104 |
|
| 105 |
except Exception as e:
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
|
| 109 |
-
def
|
| 110 |
-
"""
|
| 111 |
-
|
| 112 |
-
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
return
|
| 119 |
|
| 120 |
|
| 121 |
def run_analysis(image: Optional[Image.Image], progress=gr.Progress()):
|
| 122 |
-
"""๋ฉ์ธ ๋ถ์
|
| 123 |
if image is None:
|
| 124 |
-
return "๐ท ์ฝ ๋ดํฌ๋ ์ฒ๋ฐฉ์ ์ฌ์ง์ ์
๋ก๋ํด์ฃผ์ธ์."
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
| 127 |
-
medications = extract_medication_names(image)
|
| 128 |
|
| 129 |
progress(0.9, desc="๐ ๊ฒฐ๊ณผ ์ ๋ฆฌ ์ค...")
|
| 130 |
-
|
| 131 |
|
| 132 |
progress(1.0, desc="โ
์๋ฃ!")
|
| 133 |
-
return
|
| 134 |
|
| 135 |
|
| 136 |
# ์ฌํํ CSS
|
|
@@ -228,23 +283,31 @@ with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
|
|
| 228 |
with gr.Column(elem_classes=["upload-section"]):
|
| 229 |
gr.Markdown("### ๐ธ ์ฌ์ง ์
๋ก๋")
|
| 230 |
image_input = gr.Image(type="pil", label="์ฝ๋ดํฌ ๋๋ ์ฒ๋ฐฉ์ ์ฌ์ง", height=350)
|
| 231 |
-
analyze_button = gr.Button("๐
|
| 232 |
|
| 233 |
-
with gr.
|
| 234 |
-
gr.
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
analyze_button.click(
|
| 238 |
run_analysis,
|
| 239 |
inputs=image_input,
|
| 240 |
-
outputs=
|
| 241 |
)
|
| 242 |
|
| 243 |
gr.Markdown("""
|
| 244 |
---
|
| 245 |
|
| 246 |
-
**โน๏ธ
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
| 248 |
""")
|
| 249 |
|
| 250 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import json
|
| 2 |
import re
|
| 3 |
+
from typing import List, Optional, Tuple
|
| 4 |
|
| 5 |
import gradio as gr
|
| 6 |
import spaces
|
| 7 |
import torch
|
| 8 |
from PIL import Image
|
| 9 |
+
from transformers import AutoModel, AutoProcessor, AutoTokenizer, AutoModelForCausalLM
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# Stage 1: OCR ๋ชจ๋ธ (๋ฌธ์์์ ํ
์คํธ ์ถ์ถ)
|
| 12 |
+
OCR_MODEL_ID = "ibm-granite/granite-docling-258M"
|
| 13 |
|
| 14 |
+
# Stage 2: LLM ๋ชจ๋ธ (ํ
์คํธ์์ ์ฝ ์ด๋ฆ ์ถ์ถ)
|
| 15 |
+
LLM_MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
def _load_ocr_model():
|
| 19 |
+
"""Granite Docling OCR ๋ชจ๋ธ ๋ก๋"""
|
| 20 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 21 |
+
|
| 22 |
+
model = AutoModel.from_pretrained(
|
| 23 |
+
OCR_MODEL_ID,
|
| 24 |
+
trust_remote_code=True
|
| 25 |
+
).to(device)
|
| 26 |
+
|
| 27 |
+
processor = AutoProcessor.from_pretrained(
|
| 28 |
+
OCR_MODEL_ID,
|
| 29 |
+
trust_remote_code=True
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
return model, processor
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _load_llm_model():
|
| 36 |
+
"""Llama 3.1 8B ๋ชจ๋ธ ๋ก๋ (8bit ์์ํ)"""
|
| 37 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 38 |
+
LLM_MODEL_ID,
|
| 39 |
+
device_map="auto",
|
| 40 |
load_in_8bit=True,
|
| 41 |
torch_dtype=torch.float16,
|
| 42 |
trust_remote_code=True,
|
| 43 |
)
|
| 44 |
|
| 45 |
+
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID, trust_remote_code=True)
|
| 46 |
+
return model, tokenizer
|
| 47 |
|
| 48 |
|
| 49 |
+
print("๐ Loading Granite Docling OCR model...")
|
| 50 |
+
OCR_MODEL, OCR_PROCESSOR = _load_ocr_model()
|
| 51 |
+
print("โ
OCR model loaded!")
|
| 52 |
+
|
| 53 |
+
print("๐ Loading Llama-3.1-8B-Instruct...")
|
| 54 |
+
LLM_MODEL, LLM_TOKENIZER = _load_llm_model()
|
| 55 |
+
print("โ
LLM model loaded!")
|
| 56 |
|
| 57 |
|
| 58 |
def _extract_assistant_content(decoded: str) -> str:
|
|
|
|
| 72 |
return match.group(0)
|
| 73 |
|
| 74 |
|
| 75 |
+
def extract_text_from_image(image: Image.Image) -> str:
|
| 76 |
+
"""Stage 1: Granite Docling์ผ๋ก ์ด๋ฏธ์ง์์ ํ
์คํธ ์ถ์ถ"""
|
|
|
|
| 77 |
try:
|
| 78 |
+
inputs = OCR_PROCESSOR(images=image, return_tensors="pt").to(OCR_MODEL.device)
|
| 79 |
+
|
| 80 |
+
with torch.no_grad():
|
| 81 |
+
outputs = OCR_MODEL(**inputs)
|
| 82 |
+
|
| 83 |
+
extracted_text = OCR_PROCESSOR.batch_decode(outputs, skip_special_tokens=True)[0]
|
| 84 |
+
return extracted_text.strip()
|
| 85 |
+
|
| 86 |
+
except Exception as e:
|
| 87 |
+
raise Exception(f"OCR ์ค๋ฅ: {str(e)}")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def extract_medications_from_text(text: str) -> List[str]:
|
| 91 |
+
"""Stage 2: Llama 3.1๋ก ํ
์คํธ์์ ์ฝ ์ด๋ฆ๋ง ์ถ์ถ"""
|
| 92 |
+
try:
|
| 93 |
+
prompt = f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|>
|
| 94 |
+
|
| 95 |
+
You are a medical text analyzer. Extract only medication names from the given text and return them as a JSON array.
|
| 96 |
+
Return ONLY valid JSON format: {{"medications": ["name1", "name2"]}}
|
| 97 |
+
<|eot_id|><|start_header_id|>user<|end_header_id|>
|
| 98 |
+
|
| 99 |
+
Extract all medication names from this text:
|
| 100 |
+
|
| 101 |
+
{text}
|
| 102 |
+
|
| 103 |
+
Return only the JSON array of medication names.<|eot_id|><|start_header_id|>assistant<|end_header_id|>
|
| 104 |
+
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
inputs = LLM_TOKENIZER(prompt, return_tensors="pt").to(LLM_MODEL.device)
|
| 108 |
+
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
outputs = LLM_MODEL.generate(
|
| 111 |
+
**inputs,
|
| 112 |
+
max_new_tokens=512,
|
| 113 |
+
temperature=0.3,
|
| 114 |
+
top_p=0.9,
|
| 115 |
+
do_sample=True,
|
| 116 |
+
pad_token_id=LLM_TOKENIZER.eos_token_id,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
response = LLM_TOKENIZER.decode(outputs[0], skip_special_tokens=True)
|
| 120 |
+
|
| 121 |
+
# Extract assistant response
|
| 122 |
+
if "<|start_header_id|>assistant<|end_header_id|>" in response:
|
| 123 |
+
response = response.split("<|start_header_id|>assistant<|end_header_id|>")[-1].strip()
|
| 124 |
+
|
| 125 |
+
# Parse JSON
|
| 126 |
+
json_match = re.search(r'\{.*?\}', response, re.DOTALL)
|
| 127 |
+
if json_match:
|
| 128 |
+
data = json.loads(json_match.group(0))
|
| 129 |
+
medications = data.get("medications", [])
|
| 130 |
+
if isinstance(medications, list) and medications:
|
| 131 |
+
return [str(m).strip() for m in medications if str(m).strip()]
|
| 132 |
|
| 133 |
return ["์ฝ ์ด๋ฆ์ ์ฐพ์ง ๋ชปํ์ต๋๋ค."]
|
| 134 |
|
| 135 |
except Exception as e:
|
| 136 |
+
raise Exception(f"LLM ๋ถ์ ์ค๋ฅ: {str(e)}")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@spaces.GPU(duration=120)
|
| 140 |
+
def extract_medication_names(image: Image.Image) -> Tuple[str, List[str]]:
|
| 141 |
+
"""2๋จ๊ณ ํ์ดํ๋ผ์ธ: OCR โ LLM ๋ถ์"""
|
| 142 |
+
try:
|
| 143 |
+
# Stage 1: OCR๋ก ํ
์คํธ ์ถ์ถ
|
| 144 |
+
extracted_text = extract_text_from_image(image)
|
| 145 |
+
|
| 146 |
+
if not extracted_text:
|
| 147 |
+
return "", ["ํ
์คํธ๋ฅผ ์ถ์ถํ์ง ๋ชปํ์ต๋๋ค."]
|
| 148 |
+
|
| 149 |
+
# Stage 2: LLM์ผ๋ก ์ฝ ์ด๋ฆ ์ถ์ถ
|
| 150 |
+
medications = extract_medications_from_text(extracted_text)
|
| 151 |
+
|
| 152 |
+
return extracted_text, medications
|
| 153 |
+
|
| 154 |
+
except Exception as e:
|
| 155 |
+
return "", [f"์ค๋ฅ ๋ฐ์: {str(e)}"]
|
| 156 |
|
| 157 |
|
| 158 |
+
def format_results(extracted_text: str, medications: List[str]) -> Tuple[str, str]:
|
| 159 |
+
"""๊ฒฐ๊ณผ๋ฅผ ํฌ๋งทํ
"""
|
| 160 |
+
# ์ถ์ถ๋ ์ ์ฒด ํ
์คํธ
|
| 161 |
+
text_output = f"### ๐ ์ถ์ถ๋ ํ
์คํธ\n\n```\n{extracted_text}\n```"
|
| 162 |
|
| 163 |
+
# ์ฝ ์ด๋ฆ ๋ฆฌ์คํธ
|
| 164 |
+
if not medications or medications[0].startswith("์ค๋ฅ") or medications[0].startswith("์ฝ ์ด๋ฆ์ ์ฐพ์ง") or medications[0].startswith("ํ
์คํธ๋ฅผ"):
|
| 165 |
+
med_output = f"### โ ๏ธ {medications[0] if medications else '์ฝ ์ด๋ฆ์ ์ฐพ์ง ๋ชปํ์ต๋๋ค.'}"
|
| 166 |
+
else:
|
| 167 |
+
med_output = f"### ๐ ๊ฒ์ถ๋ ์ฝ๋ฌผ ({len(medications)}๊ฐ)\n\n"
|
| 168 |
+
for idx, med_name in enumerate(medications, 1):
|
| 169 |
+
med_output += f"{idx}. **{med_name}**\n"
|
| 170 |
|
| 171 |
+
return text_output, med_output
|
| 172 |
|
| 173 |
|
| 174 |
def run_analysis(image: Optional[Image.Image], progress=gr.Progress()):
|
| 175 |
+
"""๋ฉ์ธ ๋ถ์ ํ์ดํ๋ผ์ธ: OCR โ LLM"""
|
| 176 |
if image is None:
|
| 177 |
+
return "๐ท ์ฝ ๋ดํฌ๋ ์ฒ๋ฐฉ์ ์ฌ์ง์ ์
๋ก๋ํด์ฃผ์ธ์.", ""
|
| 178 |
+
|
| 179 |
+
progress(0.2, desc="๐ธ Stage 1: OCR ํ
์คํธ ์ถ์ถ ์ค...")
|
| 180 |
+
progress(0.6, desc="๐ค Stage 2: LLM ์ฝ๋ฌผ ๋ถ์ ์ค...")
|
| 181 |
|
| 182 |
+
extracted_text, medications = extract_medication_names(image)
|
|
|
|
| 183 |
|
| 184 |
progress(0.9, desc="๐ ๊ฒฐ๊ณผ ์ ๋ฆฌ ์ค...")
|
| 185 |
+
text_output, med_output = format_results(extracted_text, medications)
|
| 186 |
|
| 187 |
progress(1.0, desc="โ
์๋ฃ!")
|
| 188 |
+
return text_output, med_output
|
| 189 |
|
| 190 |
|
| 191 |
# ์ฌํํ CSS
|
|
|
|
| 283 |
with gr.Column(elem_classes=["upload-section"]):
|
| 284 |
gr.Markdown("### ๐ธ ์ฌ์ง ์
๋ก๋")
|
| 285 |
image_input = gr.Image(type="pil", label="์ฝ๋ดํฌ ๋๋ ์ฒ๋ฐฉ์ ์ฌ์ง", height=350)
|
| 286 |
+
analyze_button = gr.Button("๐ 2๋จ๊ณ ๋ถ์ ์์ (OCR โ LLM)", elem_classes=["analyze-btn"], size="lg")
|
| 287 |
|
| 288 |
+
with gr.Row():
|
| 289 |
+
with gr.Column(elem_classes=["result-section"]):
|
| 290 |
+
gr.Markdown("### ๐ Stage 1: OCR ๊ฒฐ๊ณผ")
|
| 291 |
+
text_output = gr.Markdown("OCR๋ก ์ถ์ถ๋ ์ ์ฒด ํ
์คํธ๊ฐ ์ฌ๊ธฐ ํ์๋ฉ๋๋ค.")
|
| 292 |
+
|
| 293 |
+
with gr.Column(elem_classes=["result-section"]):
|
| 294 |
+
gr.Markdown("### ๐ Stage 2: LLM ๋ถ์ ๊ฒฐ๊ณผ")
|
| 295 |
+
med_output = gr.Markdown("LLM์ด ๋ถ์ํ ์ฝ๋ฌผ ๋ฆฌ์คํธ๊ฐ ์ฌ๊ธฐ ํ์๋ฉ๋๋ค.")
|
| 296 |
|
| 297 |
analyze_button.click(
|
| 298 |
run_analysis,
|
| 299 |
inputs=image_input,
|
| 300 |
+
outputs=[text_output, med_output],
|
| 301 |
)
|
| 302 |
|
| 303 |
gr.Markdown("""
|
| 304 |
---
|
| 305 |
|
| 306 |
+
**โน๏ธ 2๋จ๊ณ ํ์ดํ๋ผ์ธ**
|
| 307 |
+
- **Stage 1**: Granite Docling (OCR) - ์ด๋ฏธ์ง์์ ๋ชจ๋ ํ
์คํธ ์ถ์ถ
|
| 308 |
+
- **Stage 2**: Llama 3.1 8B (LLM) - ์ถ์ถ๋ ํ
์คํธ์์ ์ฝ ์ด๋ฆ๋ง ์๋ณ
|
| 309 |
+
|
| 310 |
+
์ค์ ๋ณต์ฝ์ ์์ฌยท์ฝ์ฌ์ ์ง์๋ฅผ ๋ฐ๋ฅด์ธ์.
|
| 311 |
""")
|
| 312 |
|
| 313 |
if __name__ == "__main__":
|