forked from Brijeshthummar02/NeuroVision
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1533 lines (1295 loc) · 58.4 KB
/
Copy pathapp.py
File metadata and controls
1533 lines (1295 loc) · 58.4 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
"""
NeuroScan AI - Brain Tumor Detection Web Application
Flask Backend API with Enhanced Multi-Model Ensemble and TTA
Features:
- Multiple classification models ensemble for higher accuracy
- Multiple segmentation models for better tumor localization
- Test Time Augmentation (TTA) for robust predictions
- Advanced preprocessing and post-processing
- User authentication and scan history (MongoDB)
- Cloud image storage with Cloudinary
- Detailed diagnostic reports with share functionality
"""
from dotenv import load_dotenv
import os
load_dotenv()
REQUIRED_ENV_VARS = [
'FLASK_SECRET_KEY',
'CLOUDINARY_CLOUD_NAME',
'CLOUDINARY_API_KEY',
'CLOUDINARY_API_SECRET',
]
def validate_required_env():
"""Fail fast if required environment variables are missing."""
missing = [var for var in REQUIRED_ENV_VARS if not os.getenv(var)]
if missing:
raise EnvironmentError(
'Missing required environment variables: '
+ ', '.join(missing)
+ '. Copy .env.example to .env and set your values.'
)
validate_required_env()
from flask import Flask, render_template, request, jsonify, send_from_directory, session, redirect, url_for
from flask_cors import CORS
import tensorflow as tf
import numpy as np
import cv2
import base64
from io import BytesIO
from PIL import Image
import json
import uuid
import hashlib
from datetime import datetime
from functools import wraps
from werkzeug.utils import secure_filename
from pymongo import MongoClient
from bson import ObjectId
import cloudinary
import cloudinary.uploader
import cloudinary.api
from utilities import (
focal_tversky, tversky_loss, tversky,
dice_coefficient, dice_loss, bce_dice_loss,
iou_score, sensitivity, specificity, precision_metric,
predict_with_tta_classification, predict_with_tta_segmentation
)
# Initialize Flask app
app = Flask(__name__)
# Restrict CORS to explicit origins — set CORS_ORIGINS in .env (comma-separated)
_cors_origins = os.getenv('CORS_ORIGINS', 'http://localhost:5000').split(',')
CORS(app, supports_credentials=True, origins=[o.strip() for o in _cors_origins])
app.secret_key = os.getenv('FLASK_SECRET_KEY')
# Configuration
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['SCAN_HISTORY_FOLDER'] = 'scan_history'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'tif', 'tiff'}
app.config['USE_TTA'] = True # Enable Test Time Augmentation for higher accuracy
app.config['USE_ENSEMBLE'] = True # Enable ensemble predictions
app.config['CONFIDENCE_THRESHOLD'] = 0.5 # Minimum confidence for tumor detection
# MongoDB Configuration (optional — falls back to local JSON storage)
MONGO_URI = os.getenv('MONGO_URI')
MONGO_DB_NAME = os.getenv('MONGO_DB_NAME', 'neuroscan_db')
# Flag to track if MongoDB is available
mongodb_available = False
# Cloudinary Configuration
cloudinary.config(
cloud_name=os.getenv('CLOUDINARY_CLOUD_NAME'),
api_key=os.getenv('CLOUDINARY_API_KEY'),
api_secret=os.getenv('CLOUDINARY_API_SECRET'),
secure=True,
)
# Create required directories
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['SCAN_HISTORY_FOLDER'], exist_ok=True)
# ==================== Cloudinary Helper Functions ====================
def upload_image_to_cloudinary(image_data, folder="neuroscan", public_id=None):
"""Upload base64 image to Cloudinary and return the URL"""
try:
# Handle data URL format
if ',' in image_data:
image_data = image_data.split(',')[1]
result = cloudinary.uploader.upload(
f"data:image/png;base64,{image_data}",
folder=folder,
public_id=public_id,
resource_type="image"
)
return {
'url': result['secure_url'],
'public_id': result['public_id']
}
except Exception as e:
print(f"Cloudinary upload error: {str(e)}")
return None
def delete_image_from_cloudinary(public_id):
"""Delete image from Cloudinary"""
try:
cloudinary.uploader.destroy(public_id)
return True
except Exception as e:
print(f"Cloudinary delete error: {str(e)}")
return False
# ==================== MongoDB Setup ====================
mongo_client = None
db = None
mongodb_init_attempted = False
# File-based JSON storage fallback when MongoDB is not available
STORAGE_FILE = 'neuroscan_data.json'
def load_storage():
"""Load data from JSON file"""
try:
if os.path.exists(STORAGE_FILE):
with open(STORAGE_FILE, 'r') as f:
return json.load(f)
except Exception as e:
print(f"Error loading storage: {e}")
return {'users': {}, 'scan_history': {}}
def save_storage(data):
"""Save data to JSON file"""
try:
with open(STORAGE_FILE, 'w') as f:
json.dump(data, f, default=str)
except Exception as e:
print(f"Error saving storage: {e}")
# Load existing data on startup
memory_storage = load_storage()
def init_mongodb():
"""Initialize MongoDB connection"""
global mongo_client, db, mongodb_available, mongodb_init_attempted
# Only try once
if mongodb_init_attempted:
return mongodb_available
mongodb_init_attempted = True
if not MONGO_URI:
mongodb_available = False
print("⚠ MONGO_URI not set — using JSON file storage fallback")
return False
try:
# Try to connect to MongoDB with a short timeout
mongo_client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)
db = mongo_client[MONGO_DB_NAME]
# Test connection
mongo_client.admin.command('ping')
# Create indexes for better performance
db.users.create_index('email', unique=True)
db.scan_history.create_index('user_id')
db.scan_history.create_index('share_token', unique=True, sparse=True)
db.scan_history.create_index('scan_date')
mongodb_available = True
print("✓ Connected to MongoDB successfully")
return True
except Exception as e:
mongodb_available = False
print(f"⚠ MongoDB connection failed: {str(e)}")
print(" Using in-memory storage as fallback")
print(" Note: Data will not persist after server restart")
return False
def get_db():
"""Get MongoDB database instance"""
global db, mongodb_available, mongodb_init_attempted
# Try to initialize if not done yet
if not mongodb_init_attempted:
init_mongodb()
if not mongodb_available:
return None
return db
def hash_password(password):
"""Hash password with SHA256"""
return hashlib.sha256(password.encode()).hexdigest()
def login_required(f):
"""Decorator to require login for routes"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return jsonify({'error': 'Authentication required', 'authenticated': False}), 401
return f(*args, **kwargs)
return decorated_function
# Global variables for models (ensemble support)
classification_models = [] # List of classification models for ensemble
segmentation_models = [] # List of segmentation models for ensemble
classification_model = None # Primary classification model
segmentation_model = None # Primary segmentation model
secondary_classifier = None # Secondary classifier (classifier-resnet-weights.keras)
secondary_segmentation = None # Secondary segmentation model
models_loaded = False
def allowed_file(filename):
"""Check if file extension is allowed"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def get_custom_objects():
"""Get all custom objects for model loading"""
return {
'Functional': tf.keras.Model,
'tversky': tversky,
'tversky_loss': tversky_loss,
'focal_tversky': focal_tversky,
'dice_coefficient': dice_coefficient,
'dice_loss': dice_loss,
'bce_dice_loss': bce_dice_loss,
'iou_score': iou_score,
'sensitivity': sensitivity,
'specificity': specificity,
'precision_metric': precision_metric
}
def load_models():
"""Load all pre-trained classification and segmentation models for ensemble"""
global classification_model, segmentation_model, secondary_classifier, secondary_segmentation
global classification_models, segmentation_models, models_loaded
custom_objects = get_custom_objects()
try:
# ============================================================
# LOAD PRIMARY CLASSIFICATION MODEL (ResNet-50)
# Matches notebook: model.compile with label_smoothing and comprehensive metrics
# ============================================================
print("Loading primary classification model (ResNet-50)...")
with open('resnet-50-MRI.json', 'r') as json_file:
json_savedModel = json_file.read()
json_savedModel = json_savedModel.replace('"class_name": "Model"', '"class_name": "Functional"')
classification_model = tf.keras.models.model_from_json(json_savedModel, custom_objects=custom_objects)
classification_model.load_weights('weights.hdf5')
# Compile EXACTLY like notebook for consistent inference
classification_model.compile(
loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1),
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5), # Fine-tuned LR from notebook
metrics=[
'accuracy',
tf.keras.metrics.Precision(name='precision'),
tf.keras.metrics.Recall(name='recall'),
tf.keras.metrics.AUC(name='auc')
]
)
classification_models.append(('ResNet-50', classification_model))
print("✓ Primary classification model loaded successfully")
# ============================================================
# LOAD SECONDARY CLASSIFICATION MODEL (classifier-resnet-weights.keras)
# ============================================================
if os.path.exists('classifier-resnet-weights.keras'):
print("Loading secondary classification model...")
try:
# Try loading the full model directly
secondary_classifier = tf.keras.models.load_model(
'classifier-resnet-weights.keras',
custom_objects=custom_objects
)
classification_models.append(('Classifier-ResNet', secondary_classifier))
print("✓ Secondary classification model loaded successfully")
except Exception as e:
print(f"⚠ Could not load secondary classifier: {str(e)}")
# Try loading with JSON architecture if available
if os.path.exists('classifier-resnet-model.json'):
try:
with open('classifier-resnet-model.json', 'r') as json_file:
json_content = json_file.read()
if json_content.strip(): # Check if file is not empty
json_content = json_content.replace('"class_name": "Model"', '"class_name": "Functional"')
secondary_classifier = tf.keras.models.model_from_json(json_content, custom_objects=custom_objects)
secondary_classifier.load_weights('classifier-resnet-weights.keras')
secondary_classifier.compile(
loss='categorical_crossentropy',
optimizer='adam',
metrics=["accuracy"]
)
classification_models.append(('Classifier-ResNet', secondary_classifier))
print("✓ Secondary classification model loaded with JSON architecture")
except Exception as e2:
print(f"⚠ Secondary classifier not available: {str(e2)}")
# ============================================================
# LOAD PRIMARY SEGMENTATION MODEL (ResUNet-MRI)
# Matches notebook: model_seg.compile with focal_tversky and comprehensive metrics
# ============================================================
print("Loading primary segmentation model (ResUNet-MRI)...")
with open('ResUNet-MRI.json', 'r') as json_file:
json_savedModel = json_file.read()
json_savedModel = json_savedModel.replace('"class_name": "Model"', '"class_name": "Functional"')
segmentation_model = tf.keras.models.model_from_json(json_savedModel, custom_objects=custom_objects)
segmentation_model.load_weights('weights_seg.hdf5')
# Compile EXACTLY like notebook for consistent inference
segmentation_model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), # Same as notebook
loss=focal_tversky,
metrics=[
tversky,
dice_coefficient,
iou_score,
sensitivity,
specificity
]
)
segmentation_models.append(('ResUNet-MRI', segmentation_model))
print("✓ Primary segmentation model loaded successfully")
# ============================================================
# LOAD SECONDARY SEGMENTATION MODEL (ResUNet-model)
# ============================================================
if os.path.exists('ResUNet-model.json'):
print("Loading secondary segmentation model...")
try:
with open('ResUNet-model.json', 'r') as json_file:
json_savedModel = json_file.read()
json_savedModel = json_savedModel.replace('"class_name": "Model"', '"class_name": "Functional"')
secondary_segmentation = tf.keras.models.model_from_json(json_savedModel, custom_objects=custom_objects)
# Use same weights if no separate weights file exists
if os.path.exists('weights_seg.hdf5'):
secondary_segmentation.load_weights('weights_seg.hdf5')
# Compile EXACTLY like notebook
secondary_segmentation.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
loss=focal_tversky,
metrics=[tversky, dice_coefficient, iou_score, sensitivity, specificity]
)
segmentation_models.append(('ResUNet-Alt', secondary_segmentation))
print("✓ Secondary segmentation model loaded successfully")
except Exception as e:
print(f"⚠ Could not load secondary segmentation: {str(e)}")
models_loaded = True
print(f"\n📊 Model Summary:")
print(f" - Classification models loaded: {len(classification_models)}")
print(f" - Segmentation models loaded: {len(segmentation_models)}")
print(f" - TTA enabled: {app.config['USE_TTA']}")
print(f" - Ensemble enabled: {app.config['USE_ENSEMBLE']}")
return True
except Exception as e:
print(f"Error loading models: {str(e)}")
import traceback
traceback.print_exc()
models_loaded = False
return False
def preprocess_image_classification(img):
"""
Preprocessing for classification model - EXACTLY matches notebook's ImageDataGenerator.
Uses rescale=1./255. as in training (flow_from_dataframe with rescale=1./255.).
"""
# Resize to 256x256 (same as target_size=IMG_SIZE in notebook)
img = cv2.resize(img, (256, 256))
# Convert to RGB if grayscale (ImageDataGenerator loads as RGB)
if len(img.shape) == 2:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
elif len(img.shape) == 3 and img.shape[2] == 4: # RGBA
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
elif len(img.shape) == 3 and img.shape[2] == 3:
# OpenCV loads as BGR, convert to RGB to match ImageDataGenerator
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Normalize to [0, 1] - EXACT same as train_datagen = ImageDataGenerator(rescale=1./255.)
img_norm = img.astype(np.float32) / 255.0
# Reshape for model input (batch_size=1, height=256, width=256, channels=3)
img_norm = np.reshape(img_norm, (1, 256, 256, 3))
return img_norm
def preprocess_image_segmentation(img):
"""
Preprocessing for segmentation model - EXACTLY matches notebook's DataGenerator.
Uses standardization: img -= img.mean(); img /= img.std() as in utilities.py DataGenerator.
"""
# Resize to 256x256 (same as img_h, img_w in DataGenerator)
img = cv2.resize(img, (256, 256))
# Convert to RGB if grayscale (DataGenerator reads with PIL which loads as RGB)
if len(img.shape) == 2:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
elif len(img.shape) == 3 and img.shape[2] == 4: # RGBA
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
elif len(img.shape) == 3 and img.shape[2] == 3:
# OpenCV loads as BGR, convert to RGB to match PIL in DataGenerator
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Convert to float64 - EXACT same as DataGenerator
img = np.array(img, dtype=np.float64)
# Standardize (mean centering and std scaling) - EXACT same as DataGenerator:
# img -= img.mean()
# img /= (img.std() + 1e-8)
img -= img.mean()
img /= (img.std() + 1e-8)
# Reshape for model input - EXACT same as DataGenerator: X = np.empty((1, 256, 256, 3))
X = np.empty((1, 256, 256, 3), dtype=np.float64)
X[0,] = img
return X
def ensemble_classification_predict(img, use_tta=True):
"""
Ensemble prediction combining multiple classification models.
Uses weighted averaging based on model reliability.
Primary ResNet-50 model gets higher weight as it matches notebook training.
"""
predictions = []
weights = []
for name, model in classification_models:
if use_tta and app.config['USE_TTA']:
# Use Test Time Augmentation for more robust predictions
pred = predict_with_tta_classification(model, img)
else:
pred = model.predict(img, verbose=0)
predictions.append(pred)
# Assign weights (primary model trained in notebook gets highest weight)
if name == 'ResNet-50':
weights.append(1.0) # Primary model from notebook - full weight
elif name == 'Classifier-ResNet':
weights.append(0.8) # Secondary trained model - high weight
else:
weights.append(0.5) # Other models - lower weight
# Normalize weights
weights = np.array(weights)
weights = weights / weights.sum()
# Weighted ensemble prediction for better accuracy
if len(predictions) > 1 and app.config['USE_ENSEMBLE']:
ensemble_pred = np.zeros_like(predictions[0])
for pred, weight in zip(predictions, weights):
ensemble_pred += pred * weight
return ensemble_pred
else:
return predictions[0]
def ensemble_segmentation_predict(img, use_tta=True):
"""
Ensemble prediction combining multiple segmentation models.
Uses averaging for more robust tumor boundary detection.
"""
predictions = []
for name, model in segmentation_models:
if use_tta and app.config['USE_TTA']:
# Use Test Time Augmentation
pred = predict_with_tta_segmentation(model, img)
else:
pred = model.predict(img, verbose=0)
predictions.append(pred)
# Average ensemble prediction
if len(predictions) > 1 and app.config['USE_ENSEMBLE']:
ensemble_pred = np.mean(predictions, axis=0)
return ensemble_pred
else:
return predictions[0]
def post_process_segmentation(mask, min_area=100):
"""
Post-process segmentation mask to remove noise and small artifacts.
"""
# Convert to binary
mask_binary = (mask > 0.5).astype(np.uint8)
# Find connected components
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(mask_binary, connectivity=8)
# Remove small components (noise)
cleaned_mask = np.zeros_like(mask_binary)
for i in range(1, num_labels): # Skip background (label 0)
area = stats[i, cv2.CC_STAT_AREA]
if area >= min_area:
cleaned_mask[labels == i] = 1
# Apply morphological operations for smoother boundaries
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
cleaned_mask = cv2.morphologyEx(cleaned_mask, cv2.MORPH_CLOSE, kernel)
cleaned_mask = cv2.morphologyEx(cleaned_mask, cv2.MORPH_OPEN, kernel)
return cleaned_mask
def predict_tumor(image_path, img_original=None, use_tta=None):
"""
Enhanced two-stage prediction with ensemble models and TTA:
1. Classification: Does the image have a tumor? (Ensemble + TTA)
2. Segmentation: If yes, where is the tumor located? (Ensemble + TTA)
Args:
image_path: Path to the uploaded image file.
img_original: Pre-loaded BGR numpy array. When provided, skips the
disk read for a small I/O win. Falls back to imread.
use_tta: Override TTA for this call. None defers to USE_TTA config.
Returns detailed results including confidence scores and metrics.
"""
_use_tta = app.config['USE_TTA'] if use_tta is None else bool(use_tta)
# Read image — reuse already-loaded array when caller provides it
if img_original is None:
img_original = cv2.imread(image_path)
if img_original is None:
try:
img_pil = Image.open(image_path)
img_original = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)
except:
return None
# ============================================================
# STAGE 1: ENHANCED CLASSIFICATION (Ensemble + TTA)
# ============================================================
# Preprocess EXACTLY like notebook's ImageDataGenerator (rescale=1./255.)
img_class = preprocess_image_classification(img_original.copy())
# Use ensemble prediction with TTA for robust tumor detection
classification_pred = ensemble_classification_predict(img_class, use_tta=_use_tta)
# Determine tumor presence with confidence
tumor_probability = float(classification_pred[0][1])
no_tumor_probability = float(classification_pred[0][0])
# Use configurable threshold for more accurate detection
has_tumor = tumor_probability >= app.config['CONFIDENCE_THRESHOLD']
confidence = max(tumor_probability, no_tumor_probability)
result = {
'has_tumor': has_tumor,
'confidence': confidence,
'classification_scores': {
'no_tumor': no_tumor_probability,
'tumor': tumor_probability
},
'analysis_method': {
'tta_enabled': _use_tta,
'ensemble_enabled': app.config['USE_ENSEMBLE'],
'classification_models_used': len(classification_models),
'segmentation_models_used': len(segmentation_models)
}
}
# ============================================================
# STAGE 2: ENHANCED SEGMENTATION (Ensemble + TTA + Post-processing)
# ============================================================
if has_tumor:
img_seg = preprocess_image_segmentation(img_original.copy())
# Use ensemble prediction with TTA
segmentation_pred = ensemble_segmentation_predict(img_seg, use_tta=_use_tta)
# Get raw mask
mask_raw = segmentation_pred[0].squeeze()
# Post-process mask for cleaner results
mask_binary = post_process_segmentation(mask_raw)
# Calculate comprehensive tumor metrics
tumor_pixels = int(np.sum(mask_binary))
total_pixels = mask_binary.shape[0] * mask_binary.shape[1]
tumor_percentage = (tumor_pixels / total_pixels) * 100
# Calculate tumor bounding box and centroid
if tumor_pixels > 0:
y_indices, x_indices = np.where(mask_binary == 1)
bbox = {
'x_min': int(np.min(x_indices)),
'y_min': int(np.min(y_indices)),
'x_max': int(np.max(x_indices)),
'y_max': int(np.max(y_indices)),
'width': int(np.max(x_indices) - np.min(x_indices)),
'height': int(np.max(y_indices) - np.min(y_indices))
}
centroid = {
'x': int(np.mean(x_indices)),
'y': int(np.mean(y_indices))
}
else:
bbox = None
centroid = None
# Create visualization images
# Heatmap visualization
mask_heatmap = (mask_raw * 255).astype(np.uint8)
mask_colored = cv2.applyColorMap(mask_heatmap, cv2.COLORMAP_JET)
# Green overlay on tumor region
overlay = img_original.copy()
overlay = cv2.resize(overlay, (256, 256))
# Create a semi-transparent overlay
green_overlay = overlay.copy()
green_overlay[mask_binary == 1] = [0, 255, 0] # Green
overlay = cv2.addWeighted(overlay, 0.7, green_overlay, 0.3, 0)
# Add contours for better visualization
contours, _ = cv2.findContours(mask_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(overlay, contours, -1, (0, 255, 255), 2) # Yellow contours
# Convert images to base64
_, mask_buffer = cv2.imencode('.png', mask_colored)
_, overlay_buffer = cv2.imencode('.png', overlay)
mask_base64 = base64.b64encode(mask_buffer).decode('utf-8')
overlay_base64 = base64.b64encode(overlay_buffer).decode('utf-8')
_mask_conf = float(np.mean(mask_raw[mask_binary == 1])) if tumor_pixels > 0 else 0.0
result['segmentation'] = {
'mask': f"data:image/png;base64,{mask_base64}",
'overlay': f"data:image/png;base64,{overlay_base64}",
'tumor_area_percentage': float(tumor_percentage),
'tumor_pixels': tumor_pixels,
'total_pixels': total_pixels,
'bounding_box': bbox,
'centroid': centroid,
'mask_confidence': _mask_conf
}
# Calculate severity assessment
if tumor_percentage > 10:
severity = 'High'
severity_color = '#dc2626'
urgency = 'Immediate'
elif tumor_percentage > 5:
severity = 'Moderate'
severity_color = '#f59e0b'
urgency = 'Priority'
elif tumor_percentage > 1:
severity = 'Low'
severity_color = '#10b981'
urgency = 'Routine'
else:
severity = 'Minimal'
severity_color = '#3b82f6'
urgency = 'Monitor'
# Determine tumor location based on centroid
img_center_x, img_center_y = 128, 128 # Center of 256x256 image
if centroid:
cx, cy = centroid['x'], centroid['y']
# Determine quadrant/region
if cy < img_center_y * 0.6:
vertical_pos = 'Superior (Upper)'
elif cy > img_center_y * 1.4:
vertical_pos = 'Inferior (Lower)'
else:
vertical_pos = 'Central'
if cx < img_center_x * 0.6:
horizontal_pos = 'Left Hemisphere'
elif cx > img_center_x * 1.4:
horizontal_pos = 'Right Hemisphere'
else:
horizontal_pos = 'Midline'
location = f"{vertical_pos} - {horizontal_pos}"
# Calculate distance from center (normalized)
dist_from_center = np.sqrt((cx - img_center_x)**2 + (cy - img_center_y)**2) / img_center_x
if dist_from_center < 0.3:
location_risk = 'Central location - may affect critical structures'
elif dist_from_center < 0.6:
location_risk = 'Intermediate location - moderate accessibility'
else:
location_risk = 'Peripheral location - better surgical accessibility'
else:
location = 'Unable to determine'
location_risk = 'N/A'
# Estimate tumor characteristics
if bbox:
aspect_ratio = bbox['width'] / max(bbox['height'], 1)
if 0.7 <= aspect_ratio <= 1.3:
shape = 'Roughly spherical/circular'
elif aspect_ratio < 0.7:
shape = 'Vertically elongated'
else:
shape = 'Horizontally elongated'
# Estimated size in mm (assuming 256px = ~200mm brain width)
pixel_to_mm = 200 / 256
estimated_width_mm = bbox['width'] * pixel_to_mm
estimated_height_mm = bbox['height'] * pixel_to_mm
estimated_area_mm2 = tumor_pixels * (pixel_to_mm ** 2)
else:
shape = 'Unable to determine'
estimated_width_mm = 0
estimated_height_mm = 0
estimated_area_mm2 = 0
# Generate detailed recommendations based on severity
if severity == 'High':
recommendations = [
'Immediate consultation with a neuro-oncologist recommended',
'Additional imaging (contrast-enhanced MRI, PET scan) advised',
'Tumor board review for treatment planning',
'Consider surgical evaluation for biopsy or resection',
'Regular monitoring every 2-4 weeks during treatment'
]
elif severity == 'Moderate':
recommendations = [
'Schedule consultation with neurologist within 1-2 weeks',
'Consider additional contrast-enhanced MRI',
'Baseline cognitive assessment recommended',
'Follow-up scan in 4-6 weeks',
'Discuss treatment options with specialist'
]
elif severity == 'Low':
recommendations = [
'Follow-up with primary care physician',
'Repeat MRI in 3-6 months for monitoring',
'Document any new neurological symptoms',
'Maintain regular health check-ups',
'Consider specialist referral if symptoms develop'
]
else:
recommendations = [
'Continue routine health monitoring',
'Report any new symptoms to healthcare provider',
'Follow-up scan in 6-12 months if needed',
'Maintain healthy lifestyle',
'No immediate intervention required'
]
result['severity_assessment'] = {
'level': severity,
'severity_color': severity_color,
'urgency': urgency,
'tumor_coverage': f"{tumor_percentage:.2f}%",
'recommendation': recommendations[0]
}
# Add detailed report data
result['detailed_report'] = {
'scan_id': str(uuid.uuid4())[:8].upper(),
'scan_date': datetime.now().isoformat(),
'patient_type': 'Anonymous',
'scan_type': 'Brain MRI (T1-weighted)',
'image_resolution': '256 × 256 pixels',
'tumor_characteristics': {
'detected': True,
'confidence_score': f"{confidence * 100:.1f}%",
'coverage_percentage': f"{tumor_percentage:.2f}%",
'affected_pixels': f"{tumor_pixels:,}",
'total_pixels': f"{total_pixels:,}",
'estimated_size': {
'width_mm': f"{estimated_width_mm:.1f}",
'height_mm': f"{estimated_height_mm:.1f}",
'area_mm2': f"{estimated_area_mm2:.1f}"
},
'shape_assessment': shape,
'location': location,
'location_risk': location_risk
},
'severity_details': {
'level': severity,
'color': severity_color,
'urgency': urgency,
'description': f"Based on AI analysis, the detected abnormality covers {tumor_percentage:.2f}% of the scan area, classified as {severity.lower()} severity requiring {urgency.lower()} attention."
},
'bounding_box': bbox,
'centroid': centroid,
'mask_confidence': f"{_mask_conf * 100:.1f}%" if tumor_pixels > 0 else "N/A",
'recommendations': recommendations,
'analysis_metadata': {
'models_used': [name for name, _ in classification_models] + [name for name, _ in segmentation_models],
'tta_enabled': _use_tta,
'ensemble_enabled': app.config['USE_ENSEMBLE'],
'processing_time': 'Real-time',
'ai_version': '2.0.0'
},
'disclaimer': 'This AI-generated report is intended for informational purposes only and should not replace professional medical diagnosis. Please consult with qualified healthcare professionals for proper diagnosis and treatment planning.'
}
else:
# No tumor detected - add basic report
result['detailed_report'] = {
'scan_id': str(uuid.uuid4())[:8].upper(),
'scan_date': datetime.now().isoformat(),
'patient_type': 'Anonymous',
'scan_type': 'Brain MRI (T1-weighted)',
'image_resolution': '256 × 256 pixels',
'tumor_characteristics': {
'detected': False,
'confidence_score': f"{confidence * 100:.1f}%",
'coverage_percentage': '0.00%',
'description': 'No abnormal tissue masses detected in this scan.'
},
'recommendations': [
'No immediate concerns identified',
'Continue regular health check-ups',
'Report any new neurological symptoms',
'Maintain healthy lifestyle habits',
'Follow-up as advised by your physician'
],
'analysis_metadata': {
'models_used': [name for name, _ in classification_models],
'tta_enabled': _use_tta,
'ensemble_enabled': app.config['USE_ENSEMBLE'],
'processing_time': 'Real-time',
'ai_version': '2.0.0'
},
'disclaimer': 'This AI-generated report is intended for informational purposes only. A negative result does not guarantee absence of pathology. Please consult with qualified healthcare professionals for comprehensive evaluation.'
}
return result
# Routes
@app.route('/')
def index():
"""Render main page"""
return render_template('index.html')
@app.route('/api/health', methods=['GET'])
def health_check():
"""API health check endpoint"""
return jsonify({
'status': 'healthy',
'models_loaded': models_loaded,
'version': '1.0.0'
})
@app.route('/api/predict', methods=['POST'])
def predict():
"""Handle image upload and prediction"""
if not models_loaded:
return jsonify({
'error': 'Models not loaded. Please restart the server.'
}), 500
# Check if file is present
if 'file' not in request.files:
return jsonify({'error': 'No file uploaded'}), 400
file = request.files['file']
# Check if file is selected
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
# Check if file is allowed
if not allowed_file(file.filename):
return jsonify({
'error': 'Invalid file type. Allowed types: PNG, JPG, JPEG, TIF, TIFF'
}), 400
# Resolve TTA preference: ?tta=false / ?tta=0 / ?tta=no disables TTA for this request
tta_param = request.args.get('tta', '').lower()
_use_tta = False if tta_param in ('false', '0', 'no') else app.config['USE_TTA']
try:
# Save uploaded file
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
# Read and convert original image to PNG for browser compatibility
img_original = cv2.imread(filepath)
if img_original is None:
# Try with PIL for TIFF support
img_pil = Image.open(filepath)
img_original = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)
# Convert to PNG and encode as base64
_, img_buffer = cv2.imencode('.png', img_original)
img_base64 = base64.b64encode(img_buffer).decode('utf-8')
# Make prediction — pass already-loaded image to avoid a second disk read
prediction_result = predict_tumor(filepath, img_original=img_original, use_tta=_use_tta)
if prediction_result is None:
return jsonify({'error': 'Failed to process image'}), 500
# Add original image to result
prediction_result['original_image'] = f"data:image/png;base64,{img_base64}"
# Clean up uploaded file (optional)
# os.remove(filepath)
return jsonify(prediction_result)
except Exception as e:
return jsonify({'error': f'Prediction failed: {str(e)}'}), 500
@app.route('/api/stats', methods=['GET'])
def get_stats():
"""Return enhanced project statistics including model information"""
stats = {
'total_patients': 110,
'total_scans': 3929,
'model_accuracy': 97.92,
'segmentation_score': 0.92,
'average_inference_time': 2.3,
'model_type': 'ResNet-50 + ResUNet Ensemble',
'features': {
'tta_enabled': app.config['USE_TTA'],
'ensemble_enabled': app.config['USE_ENSEMBLE'],
'classification_models': len(classification_models),
'segmentation_models': len(segmentation_models),
'confidence_threshold': app.config['CONFIDENCE_THRESHOLD']
},
'models_info': {
'classification': [name for name, _ in classification_models],
'segmentation': [name for name, _ in segmentation_models]
}
}
return jsonify(stats)
@app.route('/api/config', methods=['GET', 'POST'])
def config():
"""Get or update model configuration"""
if request.method == 'GET':
return jsonify({
'use_tta': app.config['USE_TTA'],
'use_ensemble': app.config['USE_ENSEMBLE'],
'confidence_threshold': app.config['CONFIDENCE_THRESHOLD']
})
else:
data = request.get_json()
if 'use_tta' in data:
app.config['USE_TTA'] = bool(data['use_tta'])
if 'use_ensemble' in data:
app.config['USE_ENSEMBLE'] = bool(data['use_ensemble'])
if 'confidence_threshold' in data:
app.config['CONFIDENCE_THRESHOLD'] = float(data['confidence_threshold'])
return jsonify({
'status': 'updated',
'use_tta': app.config['USE_TTA'],
'use_ensemble': app.config['USE_ENSEMBLE'],
'confidence_threshold': app.config['CONFIDENCE_THRESHOLD']
})
@app.errorhandler(413)