Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,12 +10,12 @@ import sqlite3
|
|
| 10 |
|
| 11 |
app = Flask(__name__)
|
| 12 |
|
| 13 |
-
# β
|
| 14 |
-
|
| 15 |
-
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
DB_PATH = 'results/results.db'
|
| 19 |
|
| 20 |
def init_db():
|
| 21 |
conn = sqlite3.connect(DB_PATH)
|
|
@@ -47,6 +47,7 @@ def preprocess_image(img):
|
|
| 47 |
|
| 48 |
# β
Grad-CAM Generation
|
| 49 |
def make_gradcam(img_array, model, last_conv_layer_name='Conv_1_bn'):
|
|
|
|
| 50 |
last_conv_layer = model.get_layer(last_conv_layer_name)
|
| 51 |
grad_model = Model(inputs=model.inputs, outputs=[last_conv_layer.output, model.output])
|
| 52 |
|
|
@@ -65,13 +66,12 @@ def make_gradcam(img_array, model, last_conv_layer_name='Conv_1_bn'):
|
|
| 65 |
heatmap = tf.reduce_mean(conv_outputs, axis=-1).numpy()
|
| 66 |
heatmap = np.maximum(heatmap, 0)
|
| 67 |
heatmap /= np.max(heatmap)
|
|
|
|
| 68 |
return heatmap
|
| 69 |
|
| 70 |
# β
Save Grad-CAM Overlay
|
| 71 |
-
def save_gradcam_image(original_img, heatmap, filename='gradcam.png', output_dir=
|
| 72 |
-
|
| 73 |
-
os.makedirs(output_dir)
|
| 74 |
-
|
| 75 |
img = np.array(original_img.resize((224, 224)))
|
| 76 |
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 77 |
heatmap = np.uint8(255 * heatmap)
|
|
@@ -90,8 +90,89 @@ def home():
|
|
| 90 |
|
| 91 |
@app.route("/test_file")
|
| 92 |
def test_file():
|
|
|
|
| 93 |
filepath = "mobilenet_glaucoma_model.h5"
|
| 94 |
if os.path.exists(filepath):
|
| 95 |
return f"β
Model file found at: {filepath}"
|
| 96 |
else:
|
| 97 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
app = Flask(__name__)
|
| 12 |
|
| 13 |
+
# β
Directory and database path
|
| 14 |
+
OUTPUT_DIR = '/tmp/results'
|
| 15 |
+
if not os.path.exists(OUTPUT_DIR):
|
| 16 |
+
os.makedirs(OUTPUT_DIR)
|
| 17 |
|
| 18 |
+
DB_PATH = os.path.join(OUTPUT_DIR, 'results.db')
|
|
|
|
| 19 |
|
| 20 |
def init_db():
|
| 21 |
conn = sqlite3.connect(DB_PATH)
|
|
|
|
| 47 |
|
| 48 |
# β
Grad-CAM Generation
|
| 49 |
def make_gradcam(img_array, model, last_conv_layer_name='Conv_1_bn'):
|
| 50 |
+
"""Generate Grad-CAM for the given image and model."""
|
| 51 |
last_conv_layer = model.get_layer(last_conv_layer_name)
|
| 52 |
grad_model = Model(inputs=model.inputs, outputs=[last_conv_layer.output, model.output])
|
| 53 |
|
|
|
|
| 66 |
heatmap = tf.reduce_mean(conv_outputs, axis=-1).numpy()
|
| 67 |
heatmap = np.maximum(heatmap, 0)
|
| 68 |
heatmap /= np.max(heatmap)
|
| 69 |
+
|
| 70 |
return heatmap
|
| 71 |
|
| 72 |
# β
Save Grad-CAM Overlay
|
| 73 |
+
def save_gradcam_image(original_img, heatmap, filename='gradcam.png', output_dir=OUTPUT_DIR):
|
| 74 |
+
"""Save the Grad-CAM overlay image and return its path."""
|
|
|
|
|
|
|
| 75 |
img = np.array(original_img.resize((224, 224)))
|
| 76 |
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 77 |
heatmap = np.uint8(255 * heatmap)
|
|
|
|
| 90 |
|
| 91 |
@app.route("/test_file")
|
| 92 |
def test_file():
|
| 93 |
+
"""Check if the model file is present and readable."""
|
| 94 |
filepath = "mobilenet_glaucoma_model.h5"
|
| 95 |
if os.path.exists(filepath):
|
| 96 |
return f"β
Model file found at: {filepath}"
|
| 97 |
else:
|
| 98 |
+
return "β Model file NOT found."
|
| 99 |
+
|
| 100 |
+
@app.route('/predict', methods=['POST'])
|
| 101 |
+
def predict():
|
| 102 |
+
"""Perform prediction and save results to SQLite database."""
|
| 103 |
+
if 'file' not in request.files:
|
| 104 |
+
return jsonify({'error': 'No file uploaded'}), 400
|
| 105 |
+
|
| 106 |
+
file = request.files['file']
|
| 107 |
+
if file.filename == '':
|
| 108 |
+
return jsonify({'error': 'No file selected'}), 400
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
img = Image.open(file.stream).convert('RGB')
|
| 112 |
+
img_array = preprocess_image(img)
|
| 113 |
+
|
| 114 |
+
prediction = model.predict(img_array)[0]
|
| 115 |
+
glaucoma_prob = 1 - prediction[0]
|
| 116 |
+
normal_prob = prediction[0]
|
| 117 |
+
result = 'Glaucoma' if glaucoma_prob > normal_prob else 'Normal'
|
| 118 |
+
confidence = float(glaucoma_prob) if result == 'Glaucoma' else float(normal_prob)
|
| 119 |
+
|
| 120 |
+
# Grad-CAM
|
| 121 |
+
heatmap = make_gradcam(img_array, model, last_conv_layer_name='Conv_1_bn')
|
| 122 |
+
gradcam_filename = f"gradcam_{int(datetime.now().timestamp())}.png"
|
| 123 |
+
save_gradcam_image(img, heatmap, filename=gradcam_filename)
|
| 124 |
+
|
| 125 |
+
# Save results to SQLite
|
| 126 |
+
conn = sqlite3.connect(DB_PATH)
|
| 127 |
+
cursor = conn.cursor()
|
| 128 |
+
cursor.execute("""
|
| 129 |
+
INSERT INTO results (image_filename, prediction, confidence, gradcam_filename, timestamp)
|
| 130 |
+
VALUES (?, ?, ?, ?, ?)
|
| 131 |
+
""", (file.filename, result, confidence, gradcam_filename, datetime.now().isoformat()))
|
| 132 |
+
conn.commit()
|
| 133 |
+
conn.close()
|
| 134 |
+
|
| 135 |
+
return jsonify({
|
| 136 |
+
'prediction': result,
|
| 137 |
+
'confidence': confidence,
|
| 138 |
+
'normal_probability': float(normal_prob),
|
| 139 |
+
'glaucoma_probability': float(glaucoma_prob),
|
| 140 |
+
'gradcam_image': gradcam_filename
|
| 141 |
+
})
|
| 142 |
+
|
| 143 |
+
except Exception as e:
|
| 144 |
+
return jsonify({'error': str(e)}), 500
|
| 145 |
+
|
| 146 |
+
@app.route('/results', methods=['GET'])
|
| 147 |
+
def results():
|
| 148 |
+
"""List all results from the SQLite database."""
|
| 149 |
+
conn = sqlite3.connect(DB_PATH)
|
| 150 |
+
cursor = conn.cursor()
|
| 151 |
+
cursor.execute("SELECT * FROM results ORDER BY timestamp DESC")
|
| 152 |
+
results_data = cursor.fetchall()
|
| 153 |
+
conn.close()
|
| 154 |
+
|
| 155 |
+
results_list = []
|
| 156 |
+
for record in results_data:
|
| 157 |
+
results_list.append({
|
| 158 |
+
'id': record[0],
|
| 159 |
+
'image_filename': record[1],
|
| 160 |
+
'prediction': record[2],
|
| 161 |
+
'confidence': record[3],
|
| 162 |
+
'gradcam_filename': record[4],
|
| 163 |
+
'timestamp': record[5]
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
return jsonify(results_list)
|
| 167 |
+
|
| 168 |
+
@app.route('/gradcam/<filename>')
|
| 169 |
+
def get_gradcam(filename):
|
| 170 |
+
"""Serve the Grad-CAM overlay image."""
|
| 171 |
+
filepath = os.path.join(OUTPUT_DIR, filename)
|
| 172 |
+
if os.path.exists(filepath):
|
| 173 |
+
return send_file(filepath, mimetype='image/png')
|
| 174 |
+
else:
|
| 175 |
+
return jsonify({'error': 'File not found'}), 404
|
| 176 |
+
|
| 177 |
+
if __name__ == '__main__':
|
| 178 |
+
app.run(host='0.0.0.0', port=7860)
|