Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,13 +1,14 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import
|
3 |
from PIL import Image
|
4 |
import torch
|
5 |
-
from typing import Tuple, Optional, Dict, Any
|
6 |
from dataclasses import dataclass
|
7 |
import random
|
8 |
from datetime import datetime, timedelta
|
9 |
import os
|
10 |
from qwen_agent.agents import Assistant
|
|
|
11 |
|
12 |
@dataclass
|
13 |
class PatientMetadata:
|
@@ -26,15 +27,30 @@ class AnalysisResult:
|
|
26 |
confidence: float
|
27 |
metadata: PatientMetadata
|
28 |
|
29 |
-
class
|
30 |
def __init__(self):
|
31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
print("Initializing system...")
|
33 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
34 |
print(f"Using device: {self.device}")
|
35 |
|
36 |
self._init_vision_models()
|
37 |
-
self._init_llm()
|
38 |
print("Initialization complete!")
|
39 |
|
40 |
def _init_vision_models(self) -> None:
|
@@ -52,50 +68,6 @@ class BreastSinogramAnalyzer:
|
|
52 |
"SIATCN/vit_tumor_radius_detection_finetuned"
|
53 |
)
|
54 |
|
55 |
-
def _init_llm(self) -> None:
|
56 |
-
"""Initialize the Qwen model for report generation."""
|
57 |
-
print("Loading language model...")
|
58 |
-
self.agent = Assistant(
|
59 |
-
llm={
|
60 |
-
'model': os.environ.get("MODELNAME"),
|
61 |
-
'generate_cfg': {
|
62 |
-
'max_input_tokens': 32768,
|
63 |
-
'max_retries': 10,
|
64 |
-
'temperature': float(os.environ.get("T", 0.001)),
|
65 |
-
'repetition_penalty': float(os.environ.get("R", 1.0)),
|
66 |
-
"top_k": int(os.environ.get("K", 20)),
|
67 |
-
"top_p": float(os.environ.get("P", 0.8)),
|
68 |
-
}
|
69 |
-
},
|
70 |
-
name='QwQ-32B-preview',
|
71 |
-
description='Medical report generation model based on QwQ-32B-Preview',
|
72 |
-
system_message='You are an experienced radiologist providing clear and concise medical reports. You should think step-by-step and be precise in your analysis.',
|
73 |
-
rag_cfg={'max_ref_token': 32768, 'rag_searchers': []},
|
74 |
-
)
|
75 |
-
|
76 |
-
def _generate_synthetic_metadata(self) -> PatientMetadata:
|
77 |
-
"""Generate realistic patient metadata for breast cancer screening."""
|
78 |
-
age = random.randint(40, 75)
|
79 |
-
smoking_status = random.choice(["Never Smoker", "Former Smoker", "Current Smoker"])
|
80 |
-
family_history = random.choice([True, False])
|
81 |
-
menopause_status = "Post-menopausal" if age > 50 else "Pre-menopausal"
|
82 |
-
previous_mammogram = random.choice([True, False])
|
83 |
-
breast_density = random.choice(["A: Almost entirely fatty",
|
84 |
-
"B: Scattered fibroglandular",
|
85 |
-
"C: Heterogeneously dense",
|
86 |
-
"D: Extremely dense"])
|
87 |
-
hormone_therapy = random.choice([True, False])
|
88 |
-
|
89 |
-
return PatientMetadata(
|
90 |
-
age=age,
|
91 |
-
smoking_status=smoking_status,
|
92 |
-
family_history=family_history,
|
93 |
-
menopause_status=menopause_status,
|
94 |
-
previous_mammogram=previous_mammogram,
|
95 |
-
breast_density=breast_density,
|
96 |
-
hormone_therapy=hormone_therapy
|
97 |
-
)
|
98 |
-
|
99 |
def _process_image(self, image: Image.Image) -> Image.Image:
|
100 |
"""Process input image for model consumption."""
|
101 |
if image.mode != 'RGB':
|
@@ -105,17 +77,14 @@ class BreastSinogramAnalyzer:
|
|
105 |
@torch.no_grad()
|
106 |
def _analyze_image(self, image: Image.Image) -> AnalysisResult:
|
107 |
"""Perform abnormality detection and size measurement."""
|
108 |
-
# Generate metadata
|
109 |
metadata = self._generate_synthetic_metadata()
|
110 |
-
|
111 |
-
# Detect abnormality
|
112 |
tumor_inputs = self.tumor_processor(image, return_tensors="pt").to(self.device)
|
113 |
tumor_outputs = self.tumor_detector(**tumor_inputs)
|
114 |
tumor_probs = tumor_outputs.logits.softmax(dim=-1)[0].cpu()
|
115 |
has_tumor = tumor_probs[1] > tumor_probs[0]
|
116 |
confidence = float(tumor_probs[1] if has_tumor else tumor_probs[0])
|
117 |
|
118 |
-
# Measure size
|
119 |
size_inputs = self.size_processor(image, return_tensors="pt").to(self.device)
|
120 |
size_outputs = self.size_detector(**size_inputs)
|
121 |
size_pred = size_outputs.logits.softmax(dim=-1)[0].cpu()
|
@@ -124,63 +93,40 @@ class BreastSinogramAnalyzer:
|
|
124 |
|
125 |
return AnalysisResult(has_tumor, tumor_size, confidence, metadata)
|
126 |
|
127 |
-
def
|
128 |
-
"""Generate
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
'hormone therapy' if analysis.metadata.hormone_therapy else ''
|
140 |
-
]).strip(', ')}
|
141 |
-
|
142 |
-
Provide:
|
143 |
-
1. One sentence interpreting the findings
|
144 |
-
2. One clear management recommendation"""
|
145 |
-
|
146 |
-
try:
|
147 |
-
response = self.agent.chat(prompt)
|
148 |
-
if len(response.split()) >= 10:
|
149 |
-
return f"""INTERPRETATION AND RECOMMENDATION:
|
150 |
-
{response}"""
|
151 |
-
|
152 |
-
print("Report too short, using fallback")
|
153 |
-
return self._generate_fallback_report(analysis)
|
154 |
-
|
155 |
-
except Exception as e:
|
156 |
-
print(f"Error in report generation: {str(e)}")
|
157 |
-
return self._generate_fallback_report(analysis)
|
158 |
-
|
159 |
-
def _generate_fallback_report(self, analysis: AnalysisResult) -> str:
|
160 |
-
"""Generate a simple fallback report."""
|
161 |
-
if analysis.has_tumor:
|
162 |
-
return f"""INTERPRETATION AND RECOMMENDATION:
|
163 |
-
Microwave imaging reveals abnormal dielectric properties measuring {analysis.tumor_size} cm with {analysis.confidence:.1%} confidence level.
|
164 |
-
|
165 |
-
{'Immediate conventional imaging and clinical correlation recommended.' if analysis.tumor_size in ['1.0', '1.5'] else 'Follow-up imaging recommended in 6 months.'}"""
|
166 |
-
else:
|
167 |
-
return f"""INTERPRETATION AND RECOMMENDATION:
|
168 |
-
Microwave imaging shows normal dielectric properties with {analysis.confidence:.1%} confidence level.
|
169 |
|
170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
|
172 |
-
def
|
173 |
-
"""
|
174 |
try:
|
|
|
175 |
processed_image = self._process_image(image)
|
176 |
analysis = self._analyze_image(processed_image)
|
177 |
-
report = self._generate_medical_report(analysis)
|
178 |
|
179 |
-
|
180 |
• Detection: {'Positive' if analysis.has_tumor else 'Negative'}
|
181 |
• Size: {analysis.tumor_size} cm
|
182 |
|
183 |
-
|
184 |
PATIENT INFO:
|
185 |
• Age: {analysis.metadata.age} years
|
186 |
• Risk Factors: {', '.join([
|
@@ -190,29 +136,33 @@ PATIENT INFO:
|
|
190 |
]).strip(', ')}
|
191 |
|
192 |
REPORT:
|
193 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
except Exception as e:
|
195 |
return f"Error during analysis: {str(e)}"
|
196 |
|
197 |
-
def
|
198 |
-
"""Create the
|
199 |
-
|
200 |
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
]
|
209 |
-
|
210 |
-
description="Upload a breast microwave image for comprehensive analysis and medical assessment.",
|
211 |
-
)
|
212 |
|
213 |
-
|
|
|
214 |
|
215 |
if __name__ == "__main__":
|
216 |
print("Starting application...")
|
217 |
-
|
218 |
-
interface.launch(debug=True, share=True)
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
3 |
from PIL import Image
|
4 |
import torch
|
5 |
+
from typing import Tuple, Optional, Dict, Any, List
|
6 |
from dataclasses import dataclass
|
7 |
import random
|
8 |
from datetime import datetime, timedelta
|
9 |
import os
|
10 |
from qwen_agent.agents import Assistant
|
11 |
+
from qwen_agent.gui.web_ui import WebUI
|
12 |
|
13 |
@dataclass
|
14 |
class PatientMetadata:
|
|
|
27 |
confidence: float
|
28 |
metadata: PatientMetadata
|
29 |
|
30 |
+
class BreastCancerAgent(Assistant):
|
31 |
def __init__(self):
|
32 |
+
super().__init__(
|
33 |
+
llm={
|
34 |
+
'model': os.environ.get("MODELNAME", "qwen-vl-chat"),
|
35 |
+
'generate_cfg': {
|
36 |
+
'max_input_tokens': 32768,
|
37 |
+
'max_retries': 10,
|
38 |
+
'temperature': float(os.environ.get("T", 0.001)),
|
39 |
+
'repetition_penalty': float(os.environ.get("R", 1.0)),
|
40 |
+
"top_k": int(os.environ.get("K", 20)),
|
41 |
+
"top_p": float(os.environ.get("P", 0.8)),
|
42 |
+
}
|
43 |
+
},
|
44 |
+
name='Breast Cancer Analyzer',
|
45 |
+
description='Medical imaging analysis system specializing in breast cancer detection and reporting.',
|
46 |
+
system_message='You are an expert medical imaging system analyzing breast cancer scans. Provide clear, accurate, and professional analysis.'
|
47 |
+
)
|
48 |
+
|
49 |
print("Initializing system...")
|
50 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
51 |
print(f"Using device: {self.device}")
|
52 |
|
53 |
self._init_vision_models()
|
|
|
54 |
print("Initialization complete!")
|
55 |
|
56 |
def _init_vision_models(self) -> None:
|
|
|
68 |
"SIATCN/vit_tumor_radius_detection_finetuned"
|
69 |
)
|
70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
def _process_image(self, image: Image.Image) -> Image.Image:
|
72 |
"""Process input image for model consumption."""
|
73 |
if image.mode != 'RGB':
|
|
|
77 |
@torch.no_grad()
|
78 |
def _analyze_image(self, image: Image.Image) -> AnalysisResult:
|
79 |
"""Perform abnormality detection and size measurement."""
|
|
|
80 |
metadata = self._generate_synthetic_metadata()
|
81 |
+
|
|
|
82 |
tumor_inputs = self.tumor_processor(image, return_tensors="pt").to(self.device)
|
83 |
tumor_outputs = self.tumor_detector(**tumor_inputs)
|
84 |
tumor_probs = tumor_outputs.logits.softmax(dim=-1)[0].cpu()
|
85 |
has_tumor = tumor_probs[1] > tumor_probs[0]
|
86 |
confidence = float(tumor_probs[1] if has_tumor else tumor_probs[0])
|
87 |
|
|
|
88 |
size_inputs = self.size_processor(image, return_tensors="pt").to(self.device)
|
89 |
size_outputs = self.size_detector(**size_inputs)
|
90 |
size_pred = size_outputs.logits.softmax(dim=-1)[0].cpu()
|
|
|
93 |
|
94 |
return AnalysisResult(has_tumor, tumor_size, confidence, metadata)
|
95 |
|
96 |
+
def _generate_synthetic_metadata(self) -> PatientMetadata:
|
97 |
+
"""Generate realistic patient metadata for breast cancer screening."""
|
98 |
+
age = random.randint(40, 75)
|
99 |
+
smoking_status = random.choice(["Never Smoker", "Former Smoker", "Current Smoker"])
|
100 |
+
family_history = random.choice([True, False])
|
101 |
+
menopause_status = "Post-menopausal" if age > 50 else "Pre-menopausal"
|
102 |
+
previous_mammogram = random.choice([True, False])
|
103 |
+
breast_density = random.choice(["A: Almost entirely fatty",
|
104 |
+
"B: Scattered fibroglandular",
|
105 |
+
"C: Heterogeneously dense",
|
106 |
+
"D: Extremely dense"])
|
107 |
+
hormone_therapy = random.choice([True, False])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
+
return PatientMetadata(
|
110 |
+
age=age,
|
111 |
+
smoking_status=smoking_status,
|
112 |
+
family_history=family_history,
|
113 |
+
menopause_status=menopause_status,
|
114 |
+
previous_mammogram=previous_mammogram,
|
115 |
+
breast_density=breast_density,
|
116 |
+
hormone_therapy=hormone_therapy
|
117 |
+
)
|
118 |
|
119 |
+
def run(self, image_path: str) -> str:
|
120 |
+
"""Run analysis on an image."""
|
121 |
try:
|
122 |
+
image = Image.open(image_path)
|
123 |
processed_image = self._process_image(image)
|
124 |
analysis = self._analyze_image(processed_image)
|
|
|
125 |
|
126 |
+
report = f"""MICROWAVE IMAGING ANALYSIS:
|
127 |
• Detection: {'Positive' if analysis.has_tumor else 'Negative'}
|
128 |
• Size: {analysis.tumor_size} cm
|
129 |
|
|
|
130 |
PATIENT INFO:
|
131 |
• Age: {analysis.metadata.age} years
|
132 |
• Risk Factors: {', '.join([
|
|
|
136 |
]).strip(', ')}
|
137 |
|
138 |
REPORT:
|
139 |
+
{'Abnormal scan showing potential mass.' if analysis.has_tumor else 'Normal scan with no significant findings.'}
|
140 |
+
Confidence level: {analysis.confidence:.1%}
|
141 |
+
|
142 |
+
RECOMMENDATION:
|
143 |
+
{('Immediate follow-up imaging recommended.' if analysis.tumor_size in ['1.0', '1.5'] else 'Follow-up imaging in 6 months recommended.') if analysis.has_tumor else 'Continue routine screening per protocol.'}"""
|
144 |
+
|
145 |
+
return report
|
146 |
except Exception as e:
|
147 |
return f"Error during analysis: {str(e)}"
|
148 |
|
149 |
+
def run_interface():
|
150 |
+
"""Create and run the WebUI interface."""
|
151 |
+
agent = BreastCancerAgent()
|
152 |
|
153 |
+
chatbot_config = {
|
154 |
+
'user.name': 'Medical Staff',
|
155 |
+
'input.placeholder': 'Upload a breast microwave image for analysis...',
|
156 |
+
'prompt.suggestions': [
|
157 |
+
{'text': 'Can you analyze this mammogram?'},
|
158 |
+
{'text': 'What should I look for in the results?'},
|
159 |
+
{'text': 'How reliable is the detection?'}
|
160 |
+
]
|
161 |
+
}
|
|
|
|
|
162 |
|
163 |
+
app = WebUI(agent, chatbot_config=chatbot_config)
|
164 |
+
app.run(share=True, concurrency_limit=80)
|
165 |
|
166 |
if __name__ == "__main__":
|
167 |
print("Starting application...")
|
168 |
+
run_interface()
|
|