SIATCN commited on
Commit
08b56e6
·
verified ·
1 Parent(s): e5dc9f1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -0
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def _generate_medical_report(self, has_tumor: bool, tumor_size: str, metadata: PatientMetadata) -> str:
2
+ """Generate a standardized medical report using Mistral."""
3
+ prompt = f"""<s>[INST] Generate a structured medical report for a breast imaging scan using the following format exactly.
4
+ Keep sections consistent and use proper medical terminology. Be concise yet thorough.
5
+
6
+ EXAMINATION PERFORMED:
7
+ - Diagnostic Digital Mammogram
8
+ - Date: {datetime.now().strftime('%B %d, %Y')}
9
+
10
+ CLINICAL FINDINGS:
11
+ Primary Finding: {'Abnormal area detected' if has_tumor else 'No abnormalities detected'}
12
+ {f'Lesion Size: {tumor_size} cm' if has_tumor else ''}
13
+
14
+ PATIENT HISTORY:
15
+ - Age: {metadata.age} years
16
+ - Menopausal Status: {metadata.menopause_status}
17
+ - Previous Mammogram: {'Yes' if metadata.previous_mammogram else 'No'}
18
+ - Breast Tissue Density: {metadata.breast_density}
19
+
20
+ RISK FACTORS:
21
+ {f'• Family History: {"Present" if metadata.family_history else "None"}'}
22
+ • Smoking Status: {metadata.smoking_status}
23
+ • Hormone Therapy: {'Yes' if metadata.hormone_therapy else 'No'}
24
+
25
+ Please generate a report with these exact sections:
26
+
27
+ 1. DETAILED FINDINGS
28
+ [Describe the mammographic findings in detail, including location, characteristics, and comparison with any previous studies if available]
29
+
30
+ 2. IMPRESSION
31
+ [Provide a clear assessment using BI-RADS classification if applicable]
32
+
33
+ 3. RECOMMENDATIONS
34
+ [List specific follow-up actions and timeline]
35
+
36
+ 4. ADDITIONAL NOTES
37
+ [Include any relevant screening considerations or risk-management suggestions]
38
+
39
+ Format each section consistently and maintain professional medical terminology throughout. [/INST]</s>"""
40
+
41
+ # Generate response using Mistral
42
+ response = self.report_generator.text_generation(
43
+ prompt,
44
+ max_new_tokens=800, # Increased for comprehensive report
45
+ temperature=0.3, # Low temperature for consistency
46
+ top_p=0.9,
47
+ repetition_penalty=1.1,
48
+ do_sample=True,
49
+ seed=42
50
+ )
51
+
52
+ # Post-process the response to ensure consistent formatting
53
+ formatted_response = f"""MAMMOGRAM REPORT
54
+ Date: {datetime.now().strftime('%B %d, %Y')}
55
+ ----------------------------------------
56
+
57
+ {response.strip()}
58
+
59
+ ----------------------------------------
60
+ NOTE: This report was generated using AI assistance and should be reviewed by a qualified healthcare professional.
61
+ All findings and recommendations should be clinically verified."""
62
+
63
+ return formatted_response
64
+
65
+ # Update the analyze method to ensure consistent output formatting
66
+ def analyze(self, image: Image.Image) -> str:
67
+ """Main analysis pipeline with standardized output."""
68
+ try:
69
+ processed_image = self._process_image(image)
70
+ metadata = self._generate_synthetic_metadata()
71
+
72
+ # Detect tumor
73
+ tumor_result = self.tumor_classifier(processed_image)
74
+ has_tumor = tumor_result[0]['label'] == 'tumor'
75
+ tumor_confidence = tumor_result[0]['score']
76
+
77
+ # Measure size if tumor detected
78
+ size_result = self.size_classifier(processed_image)
79
+ tumor_size = size_result[0]['label'].replace('tumor-', '')
80
+
81
+ # Generate report
82
+ report = self._generate_medical_report(has_tumor, tumor_size, metadata)
83
+
84
+ return f"""BREAST IMAGING ANALYSIS REPORT
85
+ ========================================
86
+
87
+ INITIAL SCAN ASSESSMENT:
88
+ {'⚠️ ABNORMAL FINDING DETECTED' if has_tumor else '✓ NO ABNORMALITIES DETECTED'}
89
+ Detection Confidence: {tumor_confidence:.2%}
90
+ {f'Estimated Size: {tumor_size} cm' if has_tumor else ''}
91
+
92
+ ----------------------------------------
93
+ {report}"""
94
+
95
+ except Exception as e:
96
+ import traceback
97
+ return f"ERROR IN ANALYSIS:\n{str(e)}\n\nDebug Information:\n{traceback.format_exc()}"