Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,139 +1,148 @@
|
|
1 |
-
from flask import Flask, request, jsonify, send_file
|
2 |
-
from tensorflow.keras.models import load_model, Model
|
3 |
-
from PIL import Image
|
4 |
-
import numpy as np
|
5 |
-
import os
|
6 |
-
import cv2
|
7 |
-
import tensorflow as tf
|
8 |
-
import firebase_admin
|
9 |
-
from firebase_admin import credentials, db
|
10 |
-
from datetime import datetime
|
11 |
-
|
12 |
-
app = Flask(__name__)
|
13 |
-
|
14 |
-
# β
1. Initialize Firebase
|
15 |
-
cred = credentials.Certificate("glaucoma-4b682-firebase-adminsdk-fbsvc-cd31fbe99d.json") # Path to your service account JSON
|
16 |
-
firebase_admin.initialize_app(cred, {
|
17 |
-
'databaseURL': 'https://glaucoma-4b682-default-rtdb.firebaseio.com/'
|
18 |
-
})
|
19 |
-
results_ref = db.reference('results') # Will save results here
|
20 |
-
|
21 |
-
# β
2. Load the Model
|
22 |
-
model = load_model('mobilenet_glaucoma_model.h5', compile=False)
|
23 |
-
|
24 |
-
# β
3. Preprocess Image
|
25 |
-
def preprocess_image(img):
|
26 |
-
img = img.resize((224, 224))
|
27 |
-
img = np.array(img) / 255.0
|
28 |
-
img = np.expand_dims(img, axis=0)
|
29 |
-
return img
|
30 |
-
|
31 |
-
# β
4. Grad-CAM Generation
|
32 |
-
def make_gradcam(img_array, model, last_conv_layer_name='Conv2D_1'):
|
33 |
-
"""Generate Grad-CAM for the given image and model."""
|
34 |
-
last_conv_layer = model.get_layer(last_conv_layer_name)
|
35 |
-
grad_model = Model(inputs=model.inputs, outputs=[last_conv_layer.output, model.output])
|
36 |
-
|
37 |
-
with tf.GradientTape() as tape:
|
38 |
-
conv_outputs, predictions = grad_model(img_array)
|
39 |
-
loss = predictions[:, 0]
|
40 |
-
grads = tape.gradient(loss, conv_outputs)
|
41 |
-
|
42 |
-
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
43 |
-
conv_outputs = conv_outputs[0]
|
44 |
-
|
45 |
-
for i in range(conv_outputs.shape[-1]):
|
46 |
-
conv_outputs[..., i] *= pooled_grads[i]
|
47 |
-
|
48 |
-
heatmap = tf.reduce_mean(conv_outputs, axis=-1).numpy()
|
49 |
-
heatmap = np.maximum(heatmap, 0)
|
50 |
-
heatmap /= np.max(heatmap)
|
51 |
-
|
52 |
-
return heatmap
|
53 |
-
|
54 |
-
# β
5. Save Grad-CAM Overlay
|
55 |
-
def save_gradcam_image(original_img, heatmap, filename='gradcam.png', output_dir='results'):
|
56 |
-
"""Save the Grad-CAM overlay image and return its path."""
|
57 |
-
if not os.path.exists(output_dir):
|
58 |
-
os.makedirs(output_dir)
|
59 |
-
|
60 |
-
img = np.array(original_img.resize((224, 224)))
|
61 |
-
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
62 |
-
heatmap = np.uint8(255 * heatmap)
|
63 |
-
|
64 |
-
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
|
65 |
-
overlay = cv2.addWeighted(img, 0.6, heatmap, 0.4, 0)
|
66 |
-
|
67 |
-
filepath = os.path.join(output_dir, filename)
|
68 |
-
cv2.imwrite(filepath, overlay)
|
69 |
-
|
70 |
-
return filepath
|
71 |
-
|
72 |
-
@app.route('/')
|
73 |
-
def home():
|
74 |
-
return "Glaucoma Detection Flask API is running!"
|
75 |
-
|
76 |
-
@app.route(
|
77 |
-
def
|
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 |
-
return jsonify({
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify, send_file
|
2 |
+
from tensorflow.keras.models import load_model, Model
|
3 |
+
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
import os
|
6 |
+
import cv2
|
7 |
+
import tensorflow as tf
|
8 |
+
import firebase_admin
|
9 |
+
from firebase_admin import credentials, db
|
10 |
+
from datetime import datetime
|
11 |
+
|
12 |
+
app = Flask(__name__)
|
13 |
+
|
14 |
+
# β
1. Initialize Firebase
|
15 |
+
cred = credentials.Certificate("glaucoma-4b682-firebase-adminsdk-fbsvc-cd31fbe99d.json") # Path to your service account JSON
|
16 |
+
firebase_admin.initialize_app(cred, {
|
17 |
+
'databaseURL': 'https://glaucoma-4b682-default-rtdb.firebaseio.com/'
|
18 |
+
})
|
19 |
+
results_ref = db.reference('results') # Will save results here
|
20 |
+
|
21 |
+
# β
2. Load the Model
|
22 |
+
model = load_model('mobilenet_glaucoma_model.h5', compile=False)
|
23 |
+
|
24 |
+
# β
3. Preprocess Image
|
25 |
+
def preprocess_image(img):
|
26 |
+
img = img.resize((224, 224))
|
27 |
+
img = np.array(img) / 255.0
|
28 |
+
img = np.expand_dims(img, axis=0)
|
29 |
+
return img
|
30 |
+
|
31 |
+
# β
4. Grad-CAM Generation
|
32 |
+
def make_gradcam(img_array, model, last_conv_layer_name='Conv2D_1'):
|
33 |
+
"""Generate Grad-CAM for the given image and model."""
|
34 |
+
last_conv_layer = model.get_layer(last_conv_layer_name)
|
35 |
+
grad_model = Model(inputs=model.inputs, outputs=[last_conv_layer.output, model.output])
|
36 |
+
|
37 |
+
with tf.GradientTape() as tape:
|
38 |
+
conv_outputs, predictions = grad_model(img_array)
|
39 |
+
loss = predictions[:, 0]
|
40 |
+
grads = tape.gradient(loss, conv_outputs)
|
41 |
+
|
42 |
+
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
43 |
+
conv_outputs = conv_outputs[0]
|
44 |
+
|
45 |
+
for i in range(conv_outputs.shape[-1]):
|
46 |
+
conv_outputs[..., i] *= pooled_grads[i]
|
47 |
+
|
48 |
+
heatmap = tf.reduce_mean(conv_outputs, axis=-1).numpy()
|
49 |
+
heatmap = np.maximum(heatmap, 0)
|
50 |
+
heatmap /= np.max(heatmap)
|
51 |
+
|
52 |
+
return heatmap
|
53 |
+
|
54 |
+
# β
5. Save Grad-CAM Overlay
|
55 |
+
def save_gradcam_image(original_img, heatmap, filename='gradcam.png', output_dir='results'):
|
56 |
+
"""Save the Grad-CAM overlay image and return its path."""
|
57 |
+
if not os.path.exists(output_dir):
|
58 |
+
os.makedirs(output_dir)
|
59 |
+
|
60 |
+
img = np.array(original_img.resize((224, 224)))
|
61 |
+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
62 |
+
heatmap = np.uint8(255 * heatmap)
|
63 |
+
|
64 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
|
65 |
+
overlay = cv2.addWeighted(img, 0.6, heatmap, 0.4, 0)
|
66 |
+
|
67 |
+
filepath = os.path.join(output_dir, filename)
|
68 |
+
cv2.imwrite(filepath, overlay)
|
69 |
+
|
70 |
+
return filepath
|
71 |
+
|
72 |
+
@app.route('/')
|
73 |
+
def home():
|
74 |
+
return "Glaucoma Detection Flask API is running!"
|
75 |
+
|
76 |
+
@app.route("/test_file")
|
77 |
+
def test_file():
|
78 |
+
"""Check if the Firebase service account JSON is present and readable."""
|
79 |
+
filepath = "glaucoma-4b682-firebase-adminsdk-fbsvc-cd31fbe99d.json"
|
80 |
+
if os.path.exists(filepath):
|
81 |
+
return f"β
Service account file found at: {filepath}"
|
82 |
+
else:
|
83 |
+
return "β Service account JSON NOT found."
|
84 |
+
|
85 |
+
@app.route('/predict', methods=['POST'])
|
86 |
+
def predict():
|
87 |
+
"""Perform prediction and save results to Firebase."""
|
88 |
+
if 'file' not in request.files:
|
89 |
+
return jsonify({'error': 'No file uploaded'}), 400
|
90 |
+
|
91 |
+
file = request.files['file']
|
92 |
+
if file.filename == '':
|
93 |
+
return jsonify({'error': 'No file selected'}), 400
|
94 |
+
|
95 |
+
try:
|
96 |
+
img = Image.open(file.stream).convert('RGB')
|
97 |
+
img_array = preprocess_image(img)
|
98 |
+
|
99 |
+
prediction = model.predict(img_array)[0]
|
100 |
+
glaucoma_prob = 1 - prediction[0]
|
101 |
+
normal_prob = prediction[0]
|
102 |
+
result = 'Glaucoma' if glaucoma_prob > normal_prob else 'Normal'
|
103 |
+
confidence = float(glaucoma_prob) if result == 'Glaucoma' else float(normal_prob)
|
104 |
+
|
105 |
+
# Grad-CAM
|
106 |
+
heatmap = make_gradcam(img_array, model, last_conv_layer_name='Conv2D_1')
|
107 |
+
gradcam_filename = f"gradcam_{int(datetime.now().timestamp())}.png"
|
108 |
+
save_gradcam_image(img, heatmap, filename=gradcam_filename)
|
109 |
+
|
110 |
+
# Save to Firebase
|
111 |
+
results_ref.push({
|
112 |
+
'image_filename': file.filename,
|
113 |
+
'prediction': result,
|
114 |
+
'confidence': confidence,
|
115 |
+
'gradcam_filename': gradcam_filename,
|
116 |
+
'timestamp': datetime.now().isoformat()
|
117 |
+
})
|
118 |
+
|
119 |
+
return jsonify({
|
120 |
+
'prediction': result,
|
121 |
+
'confidence': confidence,
|
122 |
+
'normal_probability': float(normal_prob),
|
123 |
+
'glaucoma_probability': float(glaucoma_prob),
|
124 |
+
'gradcam_image': gradcam_filename
|
125 |
+
})
|
126 |
+
|
127 |
+
except Exception as e:
|
128 |
+
return jsonify({'error': str(e)}), 500
|
129 |
+
|
130 |
+
@app.route('/results', methods=['GET'])
|
131 |
+
def results():
|
132 |
+
"""List all results from the Firebase database."""
|
133 |
+
results_data = results_ref.get()
|
134 |
+
if not results_data:
|
135 |
+
results_data = []
|
136 |
+
return jsonify(results_data)
|
137 |
+
|
138 |
+
@app.route('/gradcam/<filename>')
|
139 |
+
def get_gradcam(filename):
|
140 |
+
"""Serve the Grad-CAM overlay image."""
|
141 |
+
filepath = os.path.join('results', filename)
|
142 |
+
if os.path.exists(filepath):
|
143 |
+
return send_file(filepath, mimetype='image/png')
|
144 |
+
else:
|
145 |
+
return jsonify({'error': 'File not found'}), 404
|
146 |
+
|
147 |
+
if __name__ == '__main__':
|
148 |
+
app.run(host='0.0.0.0', port=7860)
|