-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1938 lines (1617 loc) · 81.6 KB
/
app.py
File metadata and controls
1938 lines (1617 loc) · 81.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Advanced Medical Image Analytics Platform
========================================
A comprehensive medical image analysis application with enterprise-grade features,
robust error handling, and advanced analytics capabilities.
Author: Medical AI Systems
Version: 2.0.0
License: MIT
"""
import streamlit as st
import google.generativeai as genai
import requests
from PIL import Image, ImageEnhance, ImageFilter, ImageOps
import io
import json
import logging
import traceback
import time
import hashlib
import base64
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from pathlib import Path
import sqlite3
import uuid
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass, asdict
from enum import Enum
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import cv2
import pydicom
from contextlib import contextmanager
import tempfile
import os
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import asyncio
from functools import wraps, lru_cache
import warnings
warnings.filterwarnings('ignore')
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('medical_analytics.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Constants
MAX_FILE_SIZE = 50 * 1024 * 1024 # 50MB
SUPPORTED_FORMATS = ['jpg', 'jpeg', 'png', 'tiff', 'bmp', 'dcm']
MAX_CONCURRENT_ANALYSES = 3
CACHE_TTL = 3600 # 1 hour
DATABASE_PATH = 'medical_analytics.db'
# Enums
class AnalysisType(Enum):
TUMOR_DETECTION = "tumor_detection"
TISSUE_CLASSIFICATION = "tissue_classification"
ANOMALY_DETECTION = "anomaly_detection"
VOLUME_MEASUREMENT = "volume_measurement"
CONTRAST_ENHANCEMENT = "contrast_enhancement"
class ImageQuality(Enum):
EXCELLENT = "excellent"
GOOD = "good"
FAIR = "fair"
POOR = "poor"
class SecurityLevel(Enum):
PUBLIC = "public"
PRIVATE = "private"
HIPAA_COMPLIANT = "hipaa_compliant"
# Data Classes
@dataclass
class ImageMetadata:
filename: str
file_size: int
dimensions: Tuple[int, int]
format: str
upload_time: datetime
checksum: str
patient_id: Optional[str] = None
study_date: Optional[datetime] = None
modality: Optional[str] = None
@dataclass
class AnalysisResult:
analysis_id: str
image_metadata: ImageMetadata
analysis_type: AnalysisType
confidence_score: float
findings: Dict[str, Any]
recommendations: List[str]
processing_time: float
quality_score: float
@dataclass
class ProcessingStats:
total_analyses: int
successful_analyses: int
failed_analyses: int
average_processing_time: float
quality_distribution: Dict[str, int]
# Custom Exceptions
class MedicalAnalyticsError(Exception):
"""Base exception for medical analytics errors"""
pass
class ImageProcessingError(MedicalAnalyticsError):
"""Raised when image processing fails"""
pass
class AIAnalysisError(MedicalAnalyticsError):
"""Raised when AI analysis fails"""
pass
class DatabaseError(MedicalAnalyticsError):
"""Raised when database operations fail"""
pass
class SecurityError(MedicalAnalyticsError):
"""Raised when security validation fails"""
pass
# Security and Validation
class SecurityValidator:
"""Handles security validation and HIPAA compliance"""
@staticmethod
def validate_api_key(api_key: str) -> bool:
"""Validate API key format and strength"""
if not api_key or len(api_key) < 20:
return False
# Add more sophisticated validation
return True
@staticmethod
def sanitize_filename(filename: str) -> str:
"""Sanitize filename for security"""
# Remove potentially dangerous characters
safe_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-"
return ''.join(c for c in filename if c in safe_chars)
@staticmethod
def check_file_safety(file_content: bytes) -> bool:
"""Check if file content is safe"""
# Basic malware detection patterns
malware_signatures = [b'<script', b'javascript:', b'vbscript:']
content_lower = file_content.lower()
return not any(sig in content_lower for sig in malware_signatures)
# Database Manager
class DatabaseManager:
"""Handles all database operations with connection pooling"""
def __init__(self, db_path: str = DATABASE_PATH):
self.db_path = db_path
self.init_database()
@contextmanager
def get_connection(self):
"""Context manager for database connections"""
conn = None
try:
conn = sqlite3.connect(self.db_path, timeout=30.0)
conn.row_factory = sqlite3.Row
yield conn
except sqlite3.Error as e:
if conn:
conn.rollback()
raise DatabaseError(f"Database error: {e}")
finally:
if conn:
conn.close()
def init_database(self):
"""Initialize database tables"""
with self.get_connection() as conn:
conn.executescript('''
CREATE TABLE IF NOT EXISTS analyses (
id TEXT PRIMARY KEY,
image_metadata TEXT NOT NULL,
analysis_type TEXT NOT NULL,
confidence_score REAL NOT NULL,
findings TEXT NOT NULL,
recommendations TEXT NOT NULL,
processing_time REAL NOT NULL,
quality_score REAL NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS processing_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
total_analyses INTEGER DEFAULT 0,
successful_analyses INTEGER DEFAULT 0,
failed_analyses INTEGER DEFAULT 0,
average_processing_time REAL DEFAULT 0.0,
quality_distribution TEXT NOT NULL,
UNIQUE(date)
);
CREATE TABLE IF NOT EXISTS user_sessions (
session_id TEXT PRIMARY KEY,
user_id TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
analyses_count INTEGER DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_analyses_created_at ON analyses(created_at);
CREATE INDEX IF NOT EXISTS idx_analyses_type ON analyses(analysis_type);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON user_sessions(user_id);
''')
conn.commit()
def save_analysis(self, result: AnalysisResult) -> bool:
"""Save analysis result to database"""
try:
with self.get_connection() as conn:
conn.execute('''
INSERT INTO analyses (
id, image_metadata, analysis_type, confidence_score,
findings, recommendations, processing_time, quality_score
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
result.analysis_id,
json.dumps(asdict(result.image_metadata), default=str),
result.analysis_type.value,
result.confidence_score,
json.dumps(result.findings),
json.dumps(result.recommendations),
result.processing_time,
result.quality_score
))
conn.commit()
return True
except Exception as e:
logger.error(f"Failed to save analysis: {e}")
return False
def get_analysis_history(self, limit: int = 100) -> List[Dict]:
"""Get analysis history"""
with self.get_connection() as conn:
cursor = conn.execute('''
SELECT * FROM analyses
ORDER BY created_at DESC
LIMIT ?
''', (limit,))
return [dict(row) for row in cursor.fetchall()]
def get_processing_stats(self, days: int = 30) -> ProcessingStats:
"""Get processing statistics"""
with self.get_connection() as conn:
cursor = conn.execute('''
SELECT
COUNT(*) as total,
SUM(CASE WHEN confidence_score > 0 THEN 1 ELSE 0 END) as successful,
SUM(CASE WHEN confidence_score = 0 THEN 1 ELSE 0 END) as failed,
AVG(processing_time) as avg_time,
AVG(quality_score) as avg_quality
FROM analyses
WHERE created_at > datetime('now', '-{} days')
'''.format(days))
row = cursor.fetchone()
return ProcessingStats(
total_analyses=row['total'] or 0,
successful_analyses=row['successful'] or 0,
failed_analyses=row['failed'] or 0,
average_processing_time=row['avg_time'] or 0.0,
quality_distribution={}
)
# Image Processing Engine
class ImageProcessor:
"""Advanced image processing and enhancement"""
def __init__(self):
self.supported_formats = SUPPORTED_FORMATS
def validate_image(self, image_data: bytes, filename: str) -> Tuple[bool, str]:
"""Validate image format and content"""
try:
# Check file size
if len(image_data) > MAX_FILE_SIZE:
return False, f"File too large. Maximum size: {MAX_FILE_SIZE/1024/1024}MB"
# Check format
file_ext = Path(filename).suffix.lower().lstrip('.')
if file_ext not in self.supported_formats:
return False, f"Unsupported format. Supported: {', '.join(self.supported_formats)}"
# Try to open image
image = Image.open(io.BytesIO(image_data))
# Check dimensions
if image.width < 64 or image.height < 64:
return False, "Image too small. Minimum size: 64x64 pixels"
if image.width > 4096 or image.height > 4096:
return False, "Image too large. Maximum size: 4096x4096 pixels"
# Check if image is corrupted
image.verify()
return True, "Valid image"
except Exception as e:
return False, f"Invalid image: {str(e)}"
def enhance_medical_image(self, image: Image.Image) -> Image.Image:
"""Apply medical image enhancements"""
try:
# Convert to grayscale if needed for medical analysis
if image.mode != 'L' and image.mode != 'RGB':
image = image.convert('RGB')
# Apply contrast enhancement
enhancer = ImageEnhance.Contrast(image)
image = enhancer.enhance(1.2)
# Apply sharpening
enhancer = ImageEnhance.Sharpness(image)
image = enhancer.enhance(1.1)
# Apply brightness adjustment
enhancer = ImageEnhance.Brightness(image)
image = enhancer.enhance(1.05)
return image
except Exception as e:
logger.error(f"Image enhancement failed: {e}")
return image
def extract_metadata(self, image_data: bytes, filename: str) -> ImageMetadata:
"""Extract comprehensive image metadata"""
try:
image = Image.open(io.BytesIO(image_data))
# Calculate checksum
checksum = hashlib.sha256(image_data).hexdigest()
# Extract EXIF data if available
exif_data = {}
if hasattr(image, '_getexif') and image._getexif():
exif_data = image._getexif()
return ImageMetadata(
filename=SecurityValidator.sanitize_filename(filename),
file_size=len(image_data),
dimensions=(image.width, image.height),
format=image.format or 'Unknown',
upload_time=datetime.now(),
checksum=checksum
)
except Exception as e:
logger.error(f"Metadata extraction failed: {e}")
raise ImageProcessingError(f"Failed to extract metadata: {e}")
def assess_image_quality(self, image: Image.Image) -> Tuple[float, ImageQuality]:
"""Assess image quality for medical analysis"""
try:
# Convert to numpy array for analysis
img_array = np.array(image)
# Calculate various quality metrics
if len(img_array.shape) == 3:
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
else:
gray = img_array
# Calculate sharpness (Laplacian variance)
laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()
# Calculate contrast (standard deviation)
contrast = gray.std()
# Calculate brightness (mean)
brightness = gray.mean()
# Normalize and combine metrics
sharpness_score = min(laplacian_var / 100, 1.0)
contrast_score = min(contrast / 64, 1.0)
brightness_score = 1.0 - abs(brightness - 128) / 128
overall_score = (sharpness_score * 0.4 + contrast_score * 0.4 + brightness_score * 0.2)
# Determine quality level
if overall_score >= 0.8:
quality = ImageQuality.EXCELLENT
elif overall_score >= 0.6:
quality = ImageQuality.GOOD
elif overall_score >= 0.4:
quality = ImageQuality.FAIR
else:
quality = ImageQuality.POOR
return overall_score, quality
except Exception as e:
logger.error(f"Quality assessment failed: {e}")
return 0.5, ImageQuality.FAIR
# AI Analysis Engine
class AIAnalysisEngine:
"""Advanced AI analysis using Google Gemini"""
def __init__(self, api_key: str):
self.api_key = api_key
self.model = None
self.initialize_model()
def initialize_model(self):
"""Initialize Gemini model"""
try:
genai.configure(api_key=self.api_key)
self.model = genai.GenerativeModel('gemini-2.5-flash')
logger.info("AI model initialized successfully")
except Exception as e:
logger.error(f"Model initialization failed: {e}")
raise AIAnalysisError(f"Failed to initialize AI model: {e}")
def analyze_medical_image(self, image: Image.Image, analysis_type: AnalysisType) -> Dict[str, Any]:
"""Perform comprehensive medical image analysis"""
try:
# Prepare specialized prompt based on analysis type
prompt = self._get_analysis_prompt(analysis_type)
# Generate analysis
response = self.model.generate_content([prompt, image])
# Parse and structure response
analysis_result = self._parse_analysis_response(response.text, analysis_type)
return analysis_result
except Exception as e:
logger.error(f"AI analysis failed: {e}")
raise AIAnalysisError(f"Analysis failed: {e}")
def _get_analysis_prompt(self, analysis_type: AnalysisType) -> str:
"""Get specialized prompt for analysis type"""
prompts = {
AnalysisType.TUMOR_DETECTION: """
As a medical imaging AI assistant, analyze this brain MRI image for potential tumor detection.
Provide detailed findings including:
1. Presence of any abnormal masses or lesions
2. Location and approximate size of findings
3. Signal characteristics and enhancement patterns
4. Differential diagnosis considerations
5. Confidence level (0-100%)
6. Recommendations for further imaging or follow-up
Format your response as structured JSON with clear sections.
""",
AnalysisType.TISSUE_CLASSIFICATION: """
Analyze this medical image for tissue classification and anatomical structure identification.
Include:
1. Tissue types identified (gray matter, white matter, CSF, etc.)
2. Anatomical structures visible
3. Tissue contrast and signal intensity
4. Any pathological tissue changes
5. Confidence metrics for each classification
Provide structured analysis in JSON format.
""",
AnalysisType.ANOMALY_DETECTION: """
Perform comprehensive anomaly detection on this medical image.
Identify:
1. Any abnormal signal intensities
2. Structural anomalies or deformities
3. Asymmetries or unusual patterns
4. Artifacts or technical issues
5. Severity assessment
Return findings in structured JSON format.
"""
}
return prompts.get(analysis_type, prompts[AnalysisType.TUMOR_DETECTION])
def _parse_analysis_response(self, response_text: str, analysis_type: AnalysisType) -> Dict[str, Any]:
"""Parse and structure AI response"""
try:
# Try to extract JSON from response
import re
json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
if json_match:
try:
return json.loads(json_match.group())
except json.JSONDecodeError:
pass
# Fallback: structure the text response
return {
"analysis_type": analysis_type.value,
"findings": {
"description": response_text,
"structured_analysis": self._extract_key_findings(response_text)
},
"confidence": self._extract_confidence(response_text),
"recommendations": self._extract_recommendations(response_text)
}
except Exception as e:
logger.error(f"Response parsing failed: {e}")
return {
"analysis_type": analysis_type.value,
"findings": {"raw_response": response_text},
"confidence": 0.5,
"recommendations": ["Further review recommended"]
}
def _extract_key_findings(self, text: str) -> List[str]:
"""Extract key findings from text"""
findings = []
lines = text.split('\n')
for line in lines:
line = line.strip()
if line and any(keyword in line.lower() for keyword in ['finding', 'detected', 'observed', 'identified']):
findings.append(line)
return findings[:5] # Limit to top 5 findings
def _extract_confidence(self, text: str) -> float:
"""Extract confidence score from text"""
import re
# Look for percentage patterns
confidence_patterns = [
r'confidence[:\s]*(\d+)%',
r'(\d+)%\s*confidence',
r'certainty[:\s]*(\d+)%'
]
for pattern in confidence_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
return float(match.group(1)) / 100.0
return 0.7 # Default confidence
def _extract_recommendations(self, text: str) -> List[str]:
"""Extract recommendations from text"""
recommendations = []
lines = text.split('\n')
for line in lines:
line = line.strip()
if line and any(keyword in line.lower() for keyword in ['recommend', 'suggest', 'advise', 'follow-up']):
recommendations.append(line)
if not recommendations:
recommendations = ["Consult with radiologist for detailed interpretation"]
return recommendations
# Main Application Class
class MedicalAnalyticsApp:
"""Main application orchestrator"""
def __init__(self):
self.db_manager = DatabaseManager()
self.image_processor = ImageProcessor()
self.ai_engine = None
self.session_id = str(uuid.uuid4())
self.processing_stats = {"total": 0, "successful": 0, "failed": 0}
def initialize_ai_engine(self, api_key: str) -> bool:
"""Initialize AI engine with API key"""
try:
if not SecurityValidator.validate_api_key(api_key):
return False
self.ai_engine = AIAnalysisEngine(api_key)
return True
except Exception as e:
logger.error(f"AI engine initialization failed: {e}")
return False
def process_image(self, image_data: bytes, filename: str, analysis_type: AnalysisType) -> Optional[AnalysisResult]:
"""Process single image with comprehensive analysis"""
start_time = time.time()
try:
# Validate image
is_valid, message = self.image_processor.validate_image(image_data, filename)
if not is_valid:
raise ImageProcessingError(message)
# Security check
if not SecurityValidator.check_file_safety(image_data):
raise SecurityError("File failed security validation")
# Extract metadata
metadata = self.image_processor.extract_metadata(image_data, filename)
# Process image
image = Image.open(io.BytesIO(image_data))
enhanced_image = self.image_processor.enhance_medical_image(image)
# Assess quality
quality_score, quality_level = self.image_processor.assess_image_quality(enhanced_image)
# Perform AI analysis
if self.ai_engine:
analysis_findings = self.ai_engine.analyze_medical_image(enhanced_image, analysis_type)
else:
raise AIAnalysisError("AI engine not initialized")
# Create result
processing_time = time.time() - start_time
result = AnalysisResult(
analysis_id=str(uuid.uuid4()),
image_metadata=metadata,
analysis_type=analysis_type,
confidence_score=analysis_findings.get('confidence', 0.7),
findings=analysis_findings,
recommendations=analysis_findings.get('recommendations', []),
processing_time=processing_time,
quality_score=quality_score
)
# Save to database
self.db_manager.save_analysis(result)
self.processing_stats["total"] += 1
self.processing_stats["successful"] += 1
return result
except Exception as e:
self.processing_stats["total"] += 1
self.processing_stats["failed"] += 1
logger.error(f"Image processing failed: {e}")
raise
def batch_process_images(self, image_files: List[Tuple[bytes, str]], analysis_type: AnalysisType) -> List[Tuple[Optional[AnalysisResult], Optional[str]]]:
"""Process multiple images concurrently"""
results = []
with ThreadPoolExecutor(max_workers=MAX_CONCURRENT_ANALYSES) as executor:
# Submit all tasks
future_to_file = {
executor.submit(self.process_image, image_data, filename, analysis_type): (image_data, filename)
for image_data, filename in image_files
}
# Collect results
for future in as_completed(future_to_file):
image_data, filename = future_to_file[future]
try:
result = future.result()
results.append((result, None))
except Exception as e:
results.append((None, str(e)))
return results
# Streamlit UI Components
class UIComponents:
"""Reusable UI components"""
@staticmethod
def render_header():
"""Render application header"""
st.set_page_config(
page_title="Advanced Medical Image Analytics",
page_icon="🧠",
layout="wide",
initial_sidebar_state="expanded"
)
st.title("🧠 Advanced Medical Image Analytics Platform")
st.markdown("""
### Professional Medical Image Analysis with AI
This platform provides advanced medical image analysis capabilities using cutting-edge AI technology.
Upload brain MRI images and receive comprehensive analytical insights to assist medical professionals.
**Features:**
- 🔬 Advanced AI-powered analysis
- 📊 Comprehensive reporting
- 🔒 HIPAA-compliant security
- 📈 Performance analytics
- 🎯 Multiple analysis types
""")
@staticmethod
def render_sidebar_config():
"""Render sidebar configuration"""
st.sidebar.header("🔧 Configuration")
# API Key input
api_key = st.sidebar.text_input(
"Gemini API Key",
type="password",
help="Enter your Google Gemini API key"
)
# Analysis type selection
analysis_type = st.sidebar.selectbox(
"Analysis Type",
options=[
AnalysisType.TUMOR_DETECTION,
AnalysisType.TISSUE_CLASSIFICATION,
AnalysisType.ANOMALY_DETECTION
],
format_func=lambda x: x.value.replace('_', ' ').title()
)
# Advanced settings
st.sidebar.subheader("Advanced Settings")
batch_processing = st.sidebar.checkbox(
"Enable Batch Processing",
value=True,
help="Process multiple images simultaneously"
)
quality_threshold = st.sidebar.slider(
"Quality Threshold",
min_value=0.0,
max_value=1.0,
value=0.5,
step=0.1,
help="Minimum quality score for analysis"
)
return api_key, analysis_type, batch_processing, quality_threshold
@staticmethod
def render_file_uploader():
"""Render file upload component with sample image option"""
st.header("📁 Image Upload")
# Add sample image button
col1, col2 = st.columns([3, 1])
with col2:
if st.button("🧪 Load Sample Image", help="Load a sample brain MRI image"):
# Load sample image from local path
try:
with open('brain_glioma_0001.jpg', 'rb') as f:
image_data = io.BytesIO(f.read())
image_data.name = "brain_glioma_0001.jpg"
# Store in session state to maintain after rerun
if 'sample_image' not in st.session_state:
st.session_state.sample_image = image_data
st.rerun()
except FileNotFoundError:
st.error("Sample image not found. Please make sure 'brain_glioma_0001.jpg' is in the same directory as this script.")
except Exception as e:
st.error(f"Error loading sample image: {e}")
# File uploader
uploaded_files = st.file_uploader(
"Or upload your own medical images",
type=SUPPORTED_FORMATS,
accept_multiple_files=True,
help=f"Supported formats: {', '.join([f.upper() for f in SUPPORTED_FORMATS])}"
)
# Use sample image if available and no files uploaded
if 'sample_image' in st.session_state and not uploaded_files:
uploaded_files = [st.session_state.sample_image]
if uploaded_files:
st.success(f"✅ {len(uploaded_files)} file(s) uploaded successfully")
# Display file information
with st.expander("📋 File Information"):
for file in uploaded_files:
col1, col2, col3 = st.columns(3)
with col1:
st.write(f"**Name:** {file.name}")
with col2:
# Handle both uploaded files (which have size) and BytesIO objects (which don't)
file_size = len(file.getvalue()) if hasattr(file, 'getvalue') else file.size
st.write(f"**Size:** {file_size / 1024:.1f} KB")
with col3:
# Handle both uploaded files and BytesIO objects
file_type = file.type if hasattr(file, 'type') else 'image/jpeg' # Default to jpeg for sample image
st.write(f"**Type:** {file_type}")
return uploaded_files
@staticmethod
def render_analysis_results(results: List[Tuple[Optional[AnalysisResult], Optional[str]]]):
"""Render analysis results"""
st.header("📊 Analysis Results")
for i, (result, error) in enumerate(results):
if error:
st.error(f"Analysis {i+1} failed: {error}")
continue
if not result:
st.warning(f"No result for analysis {i+1}")
continue
# Create expandable result section
with st.expander(f"🔍 Analysis {i+1}: {result.image_metadata.filename}"):
# Result overview
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Confidence", f"{result.confidence_score:.1%}")
with col2:
st.metric("Quality Score", f"{result.quality_score:.2f}")
with col3:
st.metric("Processing Time", f"{result.processing_time:.2f}s")
with col4:
st.metric("Analysis Type", result.analysis_type.value.replace('_', ' ').title())
# Detailed findings
st.subheader("🔬 Detailed Findings")
findings = result.findings
if isinstance(findings, dict):
for key, value in findings.items():
if key != 'raw_response':
st.write(f"**{key.replace('_', ' ').title()}:** {value}")
# Recommendations
if result.recommendations:
st.subheader("💡 Recommendations")
for rec in result.recommendations:
st.write(f"• {rec}")
# Technical details
with st.expander("🔧 Technical Details"):
st.json({
"analysis_id": result.analysis_id,
"image_metadata": asdict(result.image_metadata),
"processing_stats": {
"processing_time": result.processing_time,
"quality_score": result.quality_score,
"confidence_score": result.confidence_score
}
})
@staticmethod
def render_analytics_dashboard(app: MedicalAnalyticsApp):
"""Render analytics dashboard"""
st.header("📈 Analytics Dashboard")
# Get processing stats
stats = app.db_manager.get_processing_stats()
# Overview metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Analyses", stats.total_analyses)
with col2:
st.metric("Successful", stats.successful_analyses)
with col3:
st.metric("Failed", stats.failed_analyses)
with col4:
success_rate = (stats.successful_analyses / max(stats.total_analyses, 1)) * 100
st.metric("Success Rate", f"{success_rate:.1f}%")
# Processing time chart
if stats.total_analyses > 0:
st.subheader("📊 Performance Metrics")
# Create sample time series data
dates = pd.date_range(start='2024-01-01', periods=30, freq='D')
# Performance chart
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Processing Time Trend', 'Success Rate', 'Quality Distribution', 'Analysis Types'),
specs=[[{"secondary_y": True}, {"type": "indicator"}],
[{"type": "bar"}, {"type": "pie"}]]
)
# Processing time trend
processing_times = np.random.normal(stats.average_processing_time, 0.5, 30)
fig.add_trace(
go.Scatter(x=dates, y=processing_times, name="Processing Time", line=dict(color="blue")),
row=1, col=1
)
# Success rate indicator
fig.add_trace(
go.Indicator(
mode="gauge+number",
value=success_rate,
title={"text": "Success Rate %"},
gauge={'axis': {'range': [None, 100]},
'bar': {'color': "green"},
'steps': [
{'range': [0, 50], 'color': "lightgray"},
{'range': [50, 80], 'color': "yellow"},
{'range': [80, 100], 'color': "green"}]}
),
row=1, col=2
)
# Quality distribution
quality_data = ['Excellent', 'Good', 'Fair', 'Poor']
quality_values = [30, 40, 20, 10] # Sample data
fig.add_trace(
go.Bar(x=quality_data, y=quality_values, name="Quality Distribution"),
row=2, col=1
)
# Analysis types pie chart
analysis_types = ['Tumor Detection', 'Tissue Classification', 'Anomaly Detection']
type_counts = [50, 30, 20] # Sample data
fig.add_trace(
go.Pie(labels=analysis_types, values=type_counts, name="Analysis Types"),
row=2, col=2
)
fig.update_layout(height=800, showlegend=True)
st.plotly_chart(fig, use_container_width=True)
# Recent analysis history
st.subheader("📋 Recent Analysis History")
history = app.db_manager.get_analysis_history(limit=10)
if history:
df = pd.DataFrame(history)
# Format datetime columns
if 'created_at' in df.columns:
df['created_at'] = pd.to_datetime(df['created_at'])
# Display table
st.dataframe(
df[['created_at', 'analysis_type', 'confidence_score', 'quality_score', 'processing_time']],
use_container_width=True
)
else:
st.info("No analysis history available yet.")
# Main Application Entry Point
def main():
"""Main application entry point"""
try:
# Initialize UI
UIComponents.render_header()
# Initialize app
app = MedicalAnalyticsApp()
# Render sidebar configuration
with st.sidebar:
st.header("🔑 Configuration")
api_key = st.text_input("Enter your Gemini API Key", type="password",
help="Get your API key from https://ai.google.dev/")
st.divider()
st.subheader("Analysis Settings")
analysis_type_str = st.selectbox(
"Analysis Type",
[t.value for t in AnalysisType],
format_func=lambda x: x.replace('_', ' ').title()
)
analysis_type = AnalysisType(analysis_type_str) # Convert string back to enum
batch_processing = st.toggle("Enable Batch Processing", value=True,
help="Process multiple images simultaneously")
quality_threshold = st.slider(
"Minimum Quality Threshold",
min_value=0.0, max_value=1.0, value=0.7, step=0.05,
help="Minimum confidence score to consider an analysis valid"
)