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