IFMedTechdemo commited on
Commit
9f87d67
·
verified ·
1 Parent(s): 9c6701e

Update app.py

Browse files

image → OCR (Chandra/Dots via radio) → take final Raw stream text → ClinicalNER → spell-check (TF-IDF / SymSpell / RapidFuzz via radio) → show final Markdown with scores.

It also dynamically pulls ner.py, tfidf_phonetic.py, symspell_matcher.py, rapidfuzz_matcher.py, and your drug_dictionary.csv from your private HF repo

Files changed (1) hide show
  1. app.py +382 -4
app.py CHANGED
@@ -1,7 +1,385 @@
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
1
+ import os
2
+ import time
3
+ from threading import Thread
4
+ from typing import Iterable, Dict, Any, Optional, List
5
+
6
  import gradio as gr
7
+ import spaces
8
+ import torch
9
+ from PIL import Image
10
+
11
+ from transformers import (
12
+ Qwen3VLForConditionalGeneration,
13
+ AutoModelForCausalLM,
14
+ AutoProcessor,
15
+ TextIteratorStreamer,
16
+ )
17
+
18
+ from gradio.themes import Soft
19
+ from gradio.themes.utils import colors, fonts, sizes
20
+
21
+ # -----------------------------
22
+ # Private repo: dynamic import
23
+ # -----------------------------
24
+ import importlib.util
25
+ from huggingface_hub import hf_hub_download
26
+
27
+ REPO_ID = "IFMedTech/new_model_private" # your private backend repo
28
+
29
+ # Map filenames to exported class names
30
+ PY_MODULES = {
31
+ "ner.py": "ClinicalNER",
32
+ "tfidf_phonetic.py": "TfidfPhoneticMatcher",
33
+ "symspell_matcher.py": "SymSpellMatcher",
34
+ "rapidfuzz_matcher.py": "RapidFuzzMatcher",
35
+ # 'drug_dictionary.csv' is data, not a module
36
+ }
37
+
38
+ HF_TOKEN = os.environ.get("HUGGINGFACE_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
39
+
40
+ def _dynamic_import(module_path: str, class_name: str):
41
+ spec = importlib.util.spec_from_file_location(class_name, module_path)
42
+ module = importlib.util.module_from_spec(spec)
43
+ spec.loader.exec_module(module) # type: ignore
44
+ return getattr(module, class_name)
45
+
46
+ # Load all private classes and data (CSV)
47
+ priv_classes: Dict[str, Any] = {}
48
+ drug_csv_path: Optional[str] = None
49
+ try:
50
+ if HF_TOKEN is None:
51
+ print("[Private] WARNING: HUGGINGFACE_TOKEN not set; NER/Spell-check will be unavailable.")
52
+ else:
53
+ for fname, cls in PY_MODULES.items():
54
+ path = hf_hub_download(repo_id=REPO_ID, filename=fname, token=HF_TOKEN)
55
+ if cls:
56
+ priv_classes[cls] = _dynamic_import(path, cls)
57
+ print(f"[Private] Loaded class: {cls} from {fname}")
58
+ # Download the drug dictionary CSV
59
+ drug_csv_path = hf_hub_download(repo_id=REPO_ID, filename="drug_dictionary.csv", token=HF_TOKEN)
60
+ print(f"[Private] Downloaded CSV at: {drug_csv_path}")
61
+ except Exception as e:
62
+ print(f"[Private] ERROR loading private backend: {e}")
63
+ priv_classes = {}
64
+ drug_csv_path = None
65
+
66
+ # ----------------------------
67
+ # THEME
68
+ # ----------------------------
69
+ colors.steel_blue = colors.Color(
70
+ name="steel_blue",
71
+ c50="#EBF3F8",
72
+ c100="#D3E5F0",
73
+ c200="#A8CCE1",
74
+ c300="#7DB3D2",
75
+ c400="#529AC3",
76
+ c500="#4682B4",
77
+ c600="#3E72A0",
78
+ c700="#36638C",
79
+ c800="#2E5378",
80
+ c900="#264364",
81
+ c950="#1E3450",
82
+ )
83
+
84
+ class SteelBlueTheme(Soft):
85
+ def __init__(
86
+ self,
87
+ *,
88
+ primary_hue: colors.Color | str = colors.gray,
89
+ secondary_hue: colors.Color | str = colors.steel_blue,
90
+ neutral_hue: colors.Color | str = colors.slate,
91
+ text_size: sizes.Size | str = sizes.text_lg,
92
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
93
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
94
+ ),
95
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
96
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
97
+ ),
98
+ ):
99
+ super().__init__(
100
+ primary_hue=primary_hue,
101
+ secondary_hue=secondary_hue,
102
+ neutral_hue=neutral_hue,
103
+ text_size=text_size,
104
+ font=font,
105
+ font_mono=font_mono,
106
+ )
107
+ super().set(
108
+ background_fill_primary="*primary_50",
109
+ background_fill_primary_dark="*primary_900",
110
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
111
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
112
+ button_primary_text_color="white",
113
+ button_primary_text_color_hover="white",
114
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
115
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
116
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_800)",
117
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_500)",
118
+ button_secondary_text_color="black",
119
+ button_secondary_text_color_hover="white",
120
+ button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",
121
+ button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",
122
+ button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",
123
+ button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",
124
+ slider_color="*secondary_500",
125
+ slider_color_dark="*secondary_600",
126
+ block_title_text_weight="600",
127
+ block_border_width="3px",
128
+ block_shadow="*shadow_drop_lg",
129
+ button_primary_shadow="*shadow_drop_lg",
130
+ button_large_padding="11px",
131
+ color_accent_soft="*primary_100",
132
+ block_label_background_fill="*primary_200",
133
+ )
134
+
135
+ steel_blue_theme = SteelBlueTheme()
136
+
137
+ css = """
138
+ #main-title h1 { font-size: 2.3em !important; }
139
+ #output-title h2 { font-size: 2.1em !important; }
140
+ """
141
+
142
+ # ----------------------------
143
+ # RUNTIME / DEVICE
144
+ # ----------------------------
145
+ os.environ.setdefault("CUDA_VISIBLE_DEVICES", "0")
146
+ print("CUDA_VISIBLE_DEVICES =", os.environ.get("CUDA_VISIBLE_DEVICES"))
147
+ print("torch.__version__ =", torch.__version__)
148
+ print("torch.version.cuda =", torch.version.cuda)
149
+ print("cuda available =", torch.cuda.is_available())
150
+ print("cuda device count =", torch.cuda.device_count())
151
+ if torch.cuda.is_available():
152
+ print("using device =", torch.cuda.get_device_name(0))
153
+
154
+ use_cuda = torch.cuda.is_available()
155
+ device = torch.device("cuda:0" if use_cuda else "cpu")
156
+ if use_cuda:
157
+ torch.backends.cudnn.benchmark = True
158
+
159
+ DTYPE_FP16 = torch.float16 if use_cuda else torch.float32
160
+ DTYPE_BF16 = torch.bfloat16 if use_cuda else torch.float32
161
+
162
+ # ----------------------------
163
+ # MODELS: Chandra-OCR + Dots.OCR
164
+ # ----------------------------
165
+ # 1) Chandra-OCR (Qwen3VL)
166
+ MODEL_ID_V = "datalab-to/chandra"
167
+ processor_v = AutoProcessor.from_pretrained(MODEL_ID_V, trust_remote_code=True)
168
+ model_v = Qwen3VLForConditionalGeneration.from_pretrained(
169
+ MODEL_ID_V, trust_remote_code=True, torch_dtype=DTYPE_FP16
170
+ ).to(device).eval()
171
+
172
+ # 2) Dots.OCR (flash_attn2 if available, else SDPA)
173
+ MODEL_PATH_D = "prithivMLmods/Dots.OCR-Latest-BF16"
174
+ processor_d = AutoProcessor.from_pretrained(MODEL_PATH_D, trust_remote_code=True)
175
+ attn_impl = "sdpa"
176
+ try:
177
+ import flash_attn # noqa: F401
178
+ if use_cuda:
179
+ attn_impl = "flash_attention_2"
180
+ except Exception:
181
+ attn_impl = "sdpa"
182
+
183
+ model_d = AutoModelForCausalLM.from_pretrained(
184
+ MODEL_PATH_D,
185
+ attn_implementation=attn_impl,
186
+ torch_dtype=DTYPE_BF16,
187
+ device_map="auto" if use_cuda else None,
188
+ trust_remote_code=True
189
+ ).eval()
190
+ if not use_cuda:
191
+ model_d.to(device)
192
+
193
+ # ----------------------------
194
+ # GENERATION (OCR → NER → Spell-check)
195
+ # ----------------------------
196
+ MAX_MAX_NEW_TOKENS = 4096
197
+ DEFAULT_MAX_NEW_TOKENS = 2048
198
+
199
+ @spaces.GPU
200
+ def generate_image(model_name: str,
201
+ text: str,
202
+ image: Image.Image,
203
+ max_new_tokens: int,
204
+ temperature: float,
205
+ top_p: float,
206
+ top_k: int,
207
+ repetition_penalty: float,
208
+ spell_algo: str):
209
+ """
210
+ 1) Streams OCR tokens to Raw output (unchanged).
211
+ 2) After stream ends, runs ClinicalNER on FINAL RAW text → list[str] meds.
212
+ 3) Runs selected spell-check approach on that list (top-5 with scores).
213
+ 4) Markdown shows: OCR text + Clinical NER + Spell-check suggestions.
214
+ """
215
+ if image is None:
216
+ yield "Please upload an image.", "Please upload an image."
217
+ return
218
+
219
+ if model_name == "Chandra-OCR":
220
+ processor, model = processor_v, model_v
221
+ elif model_name == "Dots.OCR":
222
+ processor, model = processor_d, model_d
223
+ else:
224
+ yield "Invalid model selected.", "Invalid model selected."
225
+ return
226
+
227
+ # Prepare prompt
228
+ messages = [{
229
+ "role": "user",
230
+ "content": [
231
+ {"type": "image"},
232
+ {"type": "text", "text": text},
233
+ ]
234
+ }]
235
+ prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
236
+
237
+ # Preprocess
238
+ inputs = processor(text=[prompt_full], images=[image], return_tensors="pt", padding=True)
239
+ inputs = {k: (v.to(device) if hasattr(v, "to") else v) for k, v in inputs.items()}
240
+
241
+ # Streamer
242
+ tokenizer = getattr(processor, "tokenizer", None) or processor
243
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
244
+
245
+ gen_kwargs = dict(
246
+ **inputs,
247
+ streamer=streamer,
248
+ max_new_tokens=max_new_tokens,
249
+ do_sample=True,
250
+ temperature=temperature,
251
+ top_p=top_p,
252
+ top_k=top_k,
253
+ repetition_penalty=repetition_penalty,
254
+ )
255
+
256
+ # Start generation
257
+ thread = Thread(target=model.generate, kwargs=gen_kwargs)
258
+ thread.start()
259
+
260
+ # 1) live OCR stream to Raw & Markdown mirrors during stream
261
+ buffer = ""
262
+ for new_text in streamer:
263
+ buffer += new_text.replace("<|im_end|>", "")
264
+ time.sleep(0.01)
265
+ yield buffer, buffer
266
+
267
+ # >>> Final RAW text for downstream steps <<<
268
+ final_ocr_text = buffer
269
+
270
+ # 2) ClinicalNER
271
+ try:
272
+ if "ClinicalNER" in priv_classes:
273
+ ClinicalNER = priv_classes["ClinicalNER"]
274
+ ner = ClinicalNER(token=HF_TOKEN) # you can pass model_id=... if custom
275
+ meds: List[str] = ner(final_ocr_text) or []
276
+ else:
277
+ meds = []
278
+ print("[NER] ClinicalNER not available.")
279
+ except Exception as e:
280
+ meds = []
281
+ print(f"[NER] Error running ClinicalNER: {e}")
282
+
283
+ # Build Markdown with OCR + NER section
284
+ md = final_ocr_text
285
+ md += "\n\n---\n### Clinical NER (Medications)\n"
286
+ if meds:
287
+ for m in meds:
288
+ md += f"- {m}\n"
289
+ else:
290
+ md += "- None detected\n"
291
+
292
+ # 3) Spell-check on NER output using selected approach
293
+ spell_section = "\n---\n### Spell-check suggestions (" + spell_algo + ")\n"
294
+ corr: Dict[str, List] = {}
295
+ try:
296
+ if meds and drug_csv_path:
297
+ if spell_algo == "TF-IDF + Phonetic" and "TfidfPhoneticMatcher" in priv_classes:
298
+ Cls = priv_classes["TfidfPhoneticMatcher"]
299
+ checker = Cls(csv_path=drug_csv_path, column="drug_name", ngram_size=3, phonetic_weight=0.4)
300
+ corr = checker.match_list(meds, top_k=5, tfidf_threshold=0.15)
301
+
302
+ elif spell_algo == "SymSpell" and "SymSpellMatcher" in priv_classes:
303
+ Cls = priv_classes["SymSpellMatcher"]
304
+ checker = Cls(csv_path=drug_csv_path, column="drug_name", max_edit=2, prefix_len=7)
305
+ corr = checker.match_list(meds, top_k=5, min_score=0.4)
306
+
307
+ elif spell_algo == "RapidFuzz" and "RapidFuzzMatcher" in priv_classes:
308
+ Cls = priv_classes["RapidFuzzMatcher"]
309
+ checker = Cls(csv_path=drug_csv_path, column="drug_name")
310
+ corr = checker.match_list(meds, top_k=5, threshold=70.0)
311
+ else:
312
+ spell_section += "- Spell-check backend unavailable.\n"
313
+ else:
314
+ spell_section += "- No NER output or dictionary missing.\n"
315
+ except Exception as e:
316
+ spell_section += f"- Spell-check error: {e}\n"
317
+
318
+ # Format suggestions
319
+ if corr:
320
+ for raw in meds:
321
+ cand = corr.get(raw, [])
322
+ if cand:
323
+ spell_section += f"- **{raw}**\n"
324
+ for c, s in cand:
325
+ spell_section += f" - {c} (score={s:.3f})\n"
326
+ else:
327
+ spell_section += f"- **{raw}**\n - (no suggestions)\n"
328
+
329
+ final_md = md + spell_section
330
+
331
+ # 4) Final yield: raw unchanged; Markdown has NER + spell-check
332
+ yield final_ocr_text, final_md
333
+
334
+ # ----------------------------
335
+ # UI
336
+ # ----------------------------
337
+ image_examples = [
338
+ ["OCR the content perfectly.", "examples/3.jpg"],
339
+ ["Perform OCR on the image.", "examples/1.jpg"],
340
+ ["Extract the contents. [page].", "examples/2.jpg"],
341
+ ]
342
+
343
+ with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
344
+ gr.Markdown("# **Multimodal OCR3**", elem_id="main-title")
345
+ with gr.Row():
346
+ with gr.Column(scale=2):
347
+ image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
348
+ image_upload = gr.Image(type="pil", label="Upload Image", height=290)
349
+ image_submit = gr.Button("Submit", variant="primary")
350
+ gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
351
+
352
+ # Spell-check selection
353
+ spell_choice = gr.Radio(
354
+ choices=["TF-IDF + Phonetic", "SymSpell", "RapidFuzz"],
355
+ label="Select Spell-check Approach",
356
+ value="TF-IDF + Phonetic"
357
+ )
358
+
359
+ with gr.Accordion("Advanced options", open=False):
360
+ max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
361
+ temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.7)
362
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
363
+ top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
364
+ repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.1)
365
+
366
+ with gr.Column(scale=3):
367
+ gr.Markdown("## Output", elem_id="output-title")
368
+ output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=11, show_copy_button=True)
369
+ with gr.Accordion("(Result.md)", open=False):
370
+ markdown_output = gr.Markdown(label="(Result.Md)")
371
+
372
+ model_choice = gr.Radio(
373
+ choices=["Chandra-OCR", "Dots.OCR"],
374
+ label="Select OCR Model",
375
+ value="Chandra-OCR"
376
+ )
377
 
378
+ image_submit.click(
379
+ fn=generate_image,
380
+ inputs=[model_choice, image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty, spell_choice],
381
+ outputs=[output, markdown_output]
382
+ )
383
 
384
+ if __name__ == "__main__":
385
+ demo.queue(max_size=50).launch(mcp_server=True, ssr_mode=False, show_error=True)