Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModelForCausalLM, AutoProcessor
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
import gradio as gr
|
5 |
+
import requests
|
6 |
+
import tempfile
|
7 |
+
|
8 |
+
device = torch.device("cpu")
|
9 |
+
model = AutoModelForCausalLM.from_pretrained("microsoft/maira-2", trust_remote_code=True)
|
10 |
+
processor = AutoProcessor.from_pretrained("microsoft/maira-2", trust_remote_code=True)
|
11 |
+
model = model.eval().to(device)
|
12 |
+
|
13 |
+
def get_sample_data():
|
14 |
+
"""Download sample medical images and data"""
|
15 |
+
frontal_url = "https://openi.nlm.nih.gov/imgs/512/145/145/CXR145_IM-0290-1001.png"
|
16 |
+
lateral_url = "https://openi.nlm.nih.gov/imgs/512/145/145/CXR145_IM-0290-2001.png"
|
17 |
+
|
18 |
+
def download_image(url):
|
19 |
+
response = requests.get(url, headers={"User-Agent": "MAIRA-2"}, stream=True)
|
20 |
+
return Image.open(response.raw)
|
21 |
+
|
22 |
+
return {
|
23 |
+
"frontal": download_image(frontal_url),
|
24 |
+
"lateral": download_image(lateral_url),
|
25 |
+
"indication": "Dyspnea.",
|
26 |
+
"technique": "PA and lateral views of the chest.",
|
27 |
+
"comparison": "None.",
|
28 |
+
"phrase": "Pleural effusion."
|
29 |
+
}
|
30 |
+
|
31 |
+
def save_temp_image(img):
|
32 |
+
"""Save PIL image to temporary file"""
|
33 |
+
temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
|
34 |
+
img.save(temp_file.name)
|
35 |
+
return temp_file.name
|
36 |
+
|
37 |
+
def load_sample_findings():
|
38 |
+
"""Load sample data for findings generation"""
|
39 |
+
sample = get_sample_data()
|
40 |
+
return [
|
41 |
+
save_temp_image(sample["frontal"]),
|
42 |
+
save_temp_image(sample["lateral"]),
|
43 |
+
sample["indication"],
|
44 |
+
sample["technique"],
|
45 |
+
sample["comparison"],
|
46 |
+
None, None, None, False
|
47 |
+
]
|
48 |
+
|
49 |
+
def load_sample_phrase():
|
50 |
+
"""Load sample data for phrase grounding"""
|
51 |
+
sample = get_sample_data()
|
52 |
+
return [save_temp_image(sample["frontal"]), sample["phrase"]]
|
53 |
+
|
54 |
+
def generate_report(frontal_path, lateral_path, indication, technique, comparison,
|
55 |
+
prior_frontal_path, prior_lateral_path, prior_report, grounding):
|
56 |
+
"""Generate radiology report with optional grounding"""
|
57 |
+
try:
|
58 |
+
# Load images
|
59 |
+
current_frontal = Image.open(frontal_path)
|
60 |
+
current_lateral = Image.open(lateral_path)
|
61 |
+
prior_frontal = Image.open(prior_frontal_path) if prior_frontal_path else None
|
62 |
+
prior_lateral = Image.open(prior_lateral_path) if prior_lateral_path else None
|
63 |
+
|
64 |
+
# Process inputs
|
65 |
+
processed = processor.format_and_preprocess_reporting_input(
|
66 |
+
current_frontal=current_frontal,
|
67 |
+
current_lateral=current_lateral,
|
68 |
+
prior_frontal=prior_frontal,
|
69 |
+
prior_lateral=prior_lateral,
|
70 |
+
indication=indication,
|
71 |
+
technique=technique,
|
72 |
+
comparison=comparison,
|
73 |
+
prior_report=prior_report or None,
|
74 |
+
return_tensors="pt",
|
75 |
+
get_grounding=grounding
|
76 |
+
).to(device)
|
77 |
+
|
78 |
+
# Generate report
|
79 |
+
outputs = model.generate(**processed,
|
80 |
+
max_new_tokens=450 if grounding else 300,
|
81 |
+
use_cache=True)
|
82 |
+
|
83 |
+
# Decode and format
|
84 |
+
prompt_length = processed["input_ids"].shape[-1]
|
85 |
+
decoded = processor.decode(outputs[0][prompt_length:], skip_special_tokens=True)
|
86 |
+
return processor.convert_output_to_plaintext_or_grounded_sequence(decoded.lstrip())
|
87 |
+
|
88 |
+
except Exception as e:
|
89 |
+
return f"Error: {str(e)}"
|
90 |
+
|
91 |
+
def ground_phrase(frontal_path, phrase):
|
92 |
+
"""Perform phrase grounding on image"""
|
93 |
+
try:
|
94 |
+
frontal = Image.open(frontal_path)
|
95 |
+
processed = processor.format_and_preprocess_phrase_grounding_input(
|
96 |
+
frontal_image=frontal,
|
97 |
+
phrase=phrase,
|
98 |
+
return_tensors="pt"
|
99 |
+
).to(device)
|
100 |
+
|
101 |
+
outputs = model.generate(**processed, max_new_tokens=150, use_cache=True)
|
102 |
+
|
103 |
+
prompt_length = processed["input_ids"].shape[-1]
|
104 |
+
decoded = processor.decode(outputs[0][prompt_length:], skip_special_tokens=True)
|
105 |
+
return processor.convert_output_to_plaintext_or_grounded_sequence(decoded)
|
106 |
+
|
107 |
+
except Exception as e:
|
108 |
+
return f"Error: {str(e)}"
|
109 |
+
|
110 |
+
# Gradio UI
|
111 |
+
with gr.Blocks(title="MAIRA-2 Medical Imaging Assistant") as demo:
|
112 |
+
gr.Markdown("# MAIRA-2 Medical Imaging Assistant\nAI-powered radiology report generation and phrase grounding")
|
113 |
+
|
114 |
+
with gr.Tab("Report Generation"):
|
115 |
+
with gr.Row():
|
116 |
+
with gr.Column():
|
117 |
+
gr.Markdown("## Current Study")
|
118 |
+
frontal = gr.Image(label="Frontal View", type="filepath")
|
119 |
+
lateral = gr.Image(label="Lateral View", type="filepath")
|
120 |
+
indication = gr.Textbox(label="Clinical Indication")
|
121 |
+
technique = gr.Textbox(label="Imaging Technique")
|
122 |
+
comparison = gr.Textbox(label="Comparison")
|
123 |
+
|
124 |
+
gr.Markdown("## Prior Study (Optional)")
|
125 |
+
prior_frontal = gr.Image(label="Prior Frontal View", type="filepath")
|
126 |
+
prior_lateral = gr.Image(label="Prior Lateral View", type="filepath")
|
127 |
+
prior_report = gr.Textbox(label="Prior Report")
|
128 |
+
|
129 |
+
grounding = gr.Checkbox(label="Include Grounding")
|
130 |
+
sample_btn = gr.Button("Load Sample Data")
|
131 |
+
|
132 |
+
with gr.Column():
|
133 |
+
report_output = gr.Textbox(label="Generated Report", lines=10)
|
134 |
+
generate_btn = gr.Button("Generate Report")
|
135 |
+
|
136 |
+
sample_btn.click(load_sample_findings,
|
137 |
+
outputs=[frontal, lateral, indication, technique, comparison,
|
138 |
+
prior_frontal, prior_lateral, prior_report, grounding])
|
139 |
+
generate_btn.click(generate_report,
|
140 |
+
inputs=[frontal, lateral, indication, technique, comparison,
|
141 |
+
prior_frontal, prior_lateral, prior_report, grounding],
|
142 |
+
outputs=report_output)
|
143 |
+
|
144 |
+
with gr.Tab("Phrase Grounding"):
|
145 |
+
with gr.Row():
|
146 |
+
with gr.Column():
|
147 |
+
pg_frontal = gr.Image(label="Frontal View", type="filepath")
|
148 |
+
phrase = gr.Textbox(label="Phrase to Ground")
|
149 |
+
pg_sample_btn = gr.Button("Load Sample Data")
|
150 |
+
with gr.Column():
|
151 |
+
pg_output = gr.Textbox(label="Grounding Result", lines=3)
|
152 |
+
pg_btn = gr.Button("Find Phrase")
|
153 |
+
|
154 |
+
pg_sample_btn.click(load_sample_phrase,
|
155 |
+
outputs=[pg_frontal, phrase])
|
156 |
+
pg_btn.click(ground_phrase,
|
157 |
+
inputs=[pg_frontal, phrase],
|
158 |
+
outputs=pg_output)
|
159 |
+
|
160 |
+
demo.launch()
|