Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- app.py +139 -0
- glaucoma-4b682-firebase-adminsdk-fbsvc-cd31fbe99d.json +13 -0
- mobilenet_glaucoma_model.h5 +3 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,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('/predict', methods=['POST'])
|
| 77 |
+
def predict():
|
| 78 |
+
"""Perform prediction and save results to Firebase."""
|
| 79 |
+
if 'file' not in request.files:
|
| 80 |
+
return jsonify({'error': 'No file uploaded'}), 400
|
| 81 |
+
|
| 82 |
+
file = request.files['file']
|
| 83 |
+
if file.filename == '':
|
| 84 |
+
return jsonify({'error': 'No file selected'}), 400
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
img = Image.open(file.stream).convert('RGB')
|
| 88 |
+
img_array = preprocess_image(img)
|
| 89 |
+
|
| 90 |
+
prediction = model.predict(img_array)[0]
|
| 91 |
+
glaucoma_prob = 1 - prediction[0]
|
| 92 |
+
normal_prob = prediction[0]
|
| 93 |
+
result = 'Glaucoma' if glaucoma_prob > normal_prob else 'Normal'
|
| 94 |
+
confidence = float(glaucoma_prob) if result == 'Glaucoma' else float(normal_prob)
|
| 95 |
+
|
| 96 |
+
# Grad-CAM
|
| 97 |
+
heatmap = make_gradcam(img_array, model, last_conv_layer_name='Conv2D_1')
|
| 98 |
+
gradcam_filename = f"gradcam_{int(datetime.now().timestamp())}.png"
|
| 99 |
+
save_gradcam_image(img, heatmap, filename=gradcam_filename)
|
| 100 |
+
|
| 101 |
+
# Save to Firebase
|
| 102 |
+
results_ref.push({
|
| 103 |
+
'image_filename': file.filename,
|
| 104 |
+
'prediction': result,
|
| 105 |
+
'confidence': confidence,
|
| 106 |
+
'gradcam_filename': gradcam_filename,
|
| 107 |
+
'timestamp': datetime.now().isoformat()
|
| 108 |
+
})
|
| 109 |
+
|
| 110 |
+
return jsonify({
|
| 111 |
+
'prediction': result,
|
| 112 |
+
'confidence': confidence,
|
| 113 |
+
'normal_probability': float(normal_prob),
|
| 114 |
+
'glaucoma_probability': float(glaucoma_prob),
|
| 115 |
+
'gradcam_image': gradcam_filename
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
except Exception as e:
|
| 119 |
+
return jsonify({'error': str(e)}), 500
|
| 120 |
+
|
| 121 |
+
@app.route('/results', methods=['GET'])
|
| 122 |
+
def results():
|
| 123 |
+
"""List all results from the Firebase database."""
|
| 124 |
+
results_data = results_ref.get()
|
| 125 |
+
if not results_data:
|
| 126 |
+
results_data = []
|
| 127 |
+
return jsonify(results_data)
|
| 128 |
+
|
| 129 |
+
@app.route('/gradcam/<filename>')
|
| 130 |
+
def get_gradcam(filename):
|
| 131 |
+
"""Serve the Grad-CAM overlay image."""
|
| 132 |
+
filepath = os.path.join('results', filename)
|
| 133 |
+
if os.path.exists(filepath):
|
| 134 |
+
return send_file(filepath, mimetype='image/png')
|
| 135 |
+
else:
|
| 136 |
+
return jsonify({'error': 'File not found'}), 404
|
| 137 |
+
|
| 138 |
+
if __name__ == '__main__':
|
| 139 |
+
app.run(host='0.0.0.0', port=7860)
|
glaucoma-4b682-firebase-adminsdk-fbsvc-cd31fbe99d.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"type": "service_account",
|
| 3 |
+
"project_id": "glaucoma-4b682",
|
| 4 |
+
"private_key_id": "cd31fbe99d9bfcd83a0f9435df4b10351a2d02d1",
|
| 5 |
+
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDPm5oqN+BOcDWm\nW4/bG77rXioI3OmKUm54vHtad8eGD/2id2zmWs6UVvvWpPH/NetKdDLaFH8hlLmT\nir/F6/zWKXtiL4hwFW/BKzW9PO4MeVvUgV/Wf0DuY+hskA9xKUYUkfi2asKd3Jrx\neMK4fHbqb4qrHRNZ3yl9P4n861ykxCuMg/5KG1etKqJeQuOSrknSAid+aC1Pg5px\nyelyXMC0moGpkdmXRSBsQV5euAOm7sU1vdpYowsw8LjcqsV7L3s8F64gxFo0usqx\no1RK4l3//CIsFP9X4hIyPBkbwgjLKGTRy/omxAWYLk0gEIoLunnBPGPaSQUGqtv6\nICz6taFvAgMBAAECggEABeAkf19iITYscE8xhaFpgUlX9FFe6HWZcTynBfWowgvG\n6/loLbU84CTEvWnZ3+pn9nCx470J4A40RI98JxDV8LBg9+Voto7qFnB2vMccyLcm\nHIOmKmJ4Q2p7xdCRC8JG8gbByuNqZC52tXfrW8O65ddragrJZRUwxtpXY/fYZJnE\n88UV+KGiIciV1O/LP4Fi2C7CgY68KS5Mj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": "[email protected]",
|
| 7 |
+
"client_id": "107453183192663273755",
|
| 8 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 9 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 10 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
| 11 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40glaucoma-4b682.iam.gserviceaccount.com",
|
| 12 |
+
"universe_domain": "googleapis.com"
|
| 13 |
+
}
|
mobilenet_glaucoma_model.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:678846bf6ca5c8d457c7ab2fb173c250394896bdf0d19214cb2e58ef485de9f7
|
| 3 |
+
size 9587048
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Flask
|
| 2 |
+
tensorflow
|
| 3 |
+
pillow
|
| 4 |
+
numpy
|