Update app.py
Browse files
app.py
CHANGED
@@ -1,212 +1,213 @@
|
|
1 |
-
from flask import Flask, request, jsonify, send_file
|
2 |
-
from PIL import Image
|
3 |
-
import torch
|
4 |
-
import torch.nn.functional as F
|
5 |
-
from torchvision import transforms
|
6 |
-
import os
|
7 |
-
import numpy as np
|
8 |
-
from datetime import datetime
|
9 |
-
import sqlite3
|
10 |
-
import torch.nn as nn
|
11 |
-
import cv2
|
12 |
-
|
13 |
-
# β
New Grad-CAM++ imports
|
14 |
-
from pytorch_grad_cam import GradCAMPlusPlus
|
15 |
-
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
16 |
-
from pytorch_grad_cam.utils.image import show_cam_on_image
|
17 |
-
|
18 |
-
# β
Import Hugging Face-style GLAM EfficientNet model
|
19 |
-
from glam_efficientnet_model import GLAMEfficientNetForClassification, GLAMEfficientNetConfig
|
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 |
-
model
|
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 |
-
if
|
82 |
-
|
83 |
-
|
84 |
-
return "
|
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 |
-
cursor.
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
conn.
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
'
|
155 |
-
'
|
156 |
-
'
|
157 |
-
'
|
158 |
-
'
|
159 |
-
'
|
160 |
-
'
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
cursor.
|
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 |
-
|
|
|
|
1 |
+
from flask import Flask, request, jsonify, send_file
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from torchvision import transforms
|
6 |
+
import os
|
7 |
+
import numpy as np
|
8 |
+
from datetime import datetime
|
9 |
+
import sqlite3
|
10 |
+
import torch.nn as nn
|
11 |
+
import cv2
|
12 |
+
|
13 |
+
# β
New Grad-CAM++ imports
|
14 |
+
from pytorch_grad_cam import GradCAMPlusPlus
|
15 |
+
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
|
16 |
+
from pytorch_grad_cam.utils.image import show_cam_on_image
|
17 |
+
|
18 |
+
# β
Import Hugging Face-style GLAM EfficientNet model
|
19 |
+
from glam_efficientnet_model import GLAMEfficientNetForClassification, GLAMEfficientNetConfig
|
20 |
+
from glam_module import GLAM
|
21 |
+
from swin_module import SwinWindowAttention
|
22 |
+
|
23 |
+
app = Flask(__name__)
|
24 |
+
|
25 |
+
# β
Directory and database path
|
26 |
+
OUTPUT_DIR = '/tmp/results'
|
27 |
+
if not os.path.exists(OUTPUT_DIR):
|
28 |
+
os.makedirs(OUTPUT_DIR)
|
29 |
+
|
30 |
+
DB_PATH = os.path.join(OUTPUT_DIR, 'results.db')
|
31 |
+
|
32 |
+
|
33 |
+
def init_db():
|
34 |
+
"""Initialize SQLite database for storing results."""
|
35 |
+
conn = sqlite3.connect(DB_PATH)
|
36 |
+
cursor = conn.cursor()
|
37 |
+
cursor.execute("""
|
38 |
+
CREATE TABLE IF NOT EXISTS results (
|
39 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
40 |
+
image_filename TEXT,
|
41 |
+
prediction TEXT,
|
42 |
+
confidence REAL,
|
43 |
+
gradcam_filename TEXT,
|
44 |
+
gradcam_gray_filename TEXT,
|
45 |
+
timestamp TEXT
|
46 |
+
)
|
47 |
+
""")
|
48 |
+
conn.commit()
|
49 |
+
conn.close()
|
50 |
+
|
51 |
+
|
52 |
+
init_db()
|
53 |
+
|
54 |
+
# β
Load GLAM EfficientNet Model
|
55 |
+
config = GLAMEfficientNetConfig()
|
56 |
+
model = GLAMEfficientNetForClassification(
|
57 |
+
config, glam_module_cls=GLAM, swin_module_cls=SwinWindowAttention
|
58 |
+
)
|
59 |
+
model.load_state_dict(torch.load('efficientnet_glam_best.pt', map_location='cpu'))
|
60 |
+
model.eval()
|
61 |
+
|
62 |
+
# β
Class Names
|
63 |
+
CLASS_NAMES = ["Advanced", "Early", "Normal"]
|
64 |
+
|
65 |
+
# β
Transformation for input images
|
66 |
+
transform = transforms.Compose([
|
67 |
+
transforms.Resize(256),
|
68 |
+
transforms.CenterCrop(224),
|
69 |
+
transforms.ToTensor(),
|
70 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
71 |
+
std=[0.229, 0.224, 0.225]),
|
72 |
+
])
|
73 |
+
|
74 |
+
@app.route('/')
|
75 |
+
def home():
|
76 |
+
"""Check that the API is working."""
|
77 |
+
return "Glaucoma Detection Flask API (GLAM EfficientNet) is running!"
|
78 |
+
|
79 |
+
@app.route("/test_file")
|
80 |
+
def test_file():
|
81 |
+
"""Check if the .pt model file is present and readable."""
|
82 |
+
filepath = "efficientnet_glam_best.pt"
|
83 |
+
if os.path.exists(filepath):
|
84 |
+
return f"β
Model file found at: {filepath}"
|
85 |
+
else:
|
86 |
+
return "β Model file NOT found."
|
87 |
+
|
88 |
+
|
89 |
+
@app.route('/predict', methods=['POST'])
|
90 |
+
def predict():
|
91 |
+
"""Perform prediction and save results (including Grad-CAM++) to the database."""
|
92 |
+
if 'file' not in request.files:
|
93 |
+
return jsonify({'error': 'No file uploaded'}), 400
|
94 |
+
|
95 |
+
uploaded_file = request.files['file']
|
96 |
+
if uploaded_file.filename == '':
|
97 |
+
return jsonify({'error': 'No file selected'}), 400
|
98 |
+
|
99 |
+
try:
|
100 |
+
# β
Save the uploaded image
|
101 |
+
timestamp = int(datetime.now().timestamp())
|
102 |
+
uploaded_filename = f"uploaded_{timestamp}.png"
|
103 |
+
uploaded_file_path = os.path.join(OUTPUT_DIR, uploaded_filename)
|
104 |
+
uploaded_file.save(uploaded_file_path)
|
105 |
+
|
106 |
+
# β
Perform prediction
|
107 |
+
img = Image.open(uploaded_file_path).convert('RGB')
|
108 |
+
input_tensor = transform(img).unsqueeze(0)
|
109 |
+
|
110 |
+
# β
Get prediction
|
111 |
+
output = model(input_tensor) # Dict with "logits"
|
112 |
+
probabilities = F.softmax(output["logits"], dim=1).cpu().detach().numpy()[0]
|
113 |
+
class_index = np.argmax(probabilities)
|
114 |
+
result = CLASS_NAMES[class_index]
|
115 |
+
confidence = float(probabilities[class_index])
|
116 |
+
|
117 |
+
# β
Grad-CAM++ setup
|
118 |
+
# Target the final convolutional output. In GLAM EfficientNet, this is `model.features`
|
119 |
+
target_layer = dict(model.features.named_modules())["features.7"] # β
Adjust as needed
|
120 |
+
cam_model = GradCAMPlusPlus(model=model, target_layers=[target_layer])
|
121 |
+
|
122 |
+
# β
Get Grad-CAM++ map
|
123 |
+
cam_output = cam_model(input_tensor=input_tensor, targets=[ClassifierOutputTarget(class_index)])[0]
|
124 |
+
|
125 |
+
# β
Create RGB overlay
|
126 |
+
original_img = np.asarray(img.resize((224, 224)), dtype=np.float32) / 255.0
|
127 |
+
overlay = show_cam_on_image(original_img, cam_output, use_rgb=True)
|
128 |
+
|
129 |
+
# β
Create grayscale version
|
130 |
+
cam_normalized = np.uint8(255 * cam_output)
|
131 |
+
|
132 |
+
# β
Save overlay
|
133 |
+
gradcam_filename = f"gradcam_{timestamp}.png"
|
134 |
+
gradcam_file_path = os.path.join(OUTPUT_DIR, gradcam_filename)
|
135 |
+
cv2.imwrite(gradcam_file_path, cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))
|
136 |
+
|
137 |
+
# β
Save grayscale
|
138 |
+
gray_filename = f"gradcam_gray_{timestamp}.png"
|
139 |
+
gray_file_path = os.path.join(OUTPUT_DIR, gray_filename)
|
140 |
+
cv2.imwrite(gray_file_path, cam_normalized)
|
141 |
+
|
142 |
+
# β
Save results to database
|
143 |
+
conn = sqlite3.connect(DB_PATH)
|
144 |
+
cursor = conn.cursor()
|
145 |
+
cursor.execute("""
|
146 |
+
INSERT INTO results (image_filename, prediction, confidence, gradcam_filename, gradcam_gray_filename, timestamp)
|
147 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
148 |
+
""", (uploaded_filename, result, confidence, gradcam_filename, gray_filename, datetime.now().isoformat()))
|
149 |
+
conn.commit()
|
150 |
+
conn.close()
|
151 |
+
|
152 |
+
# β
Return results
|
153 |
+
return jsonify({
|
154 |
+
'prediction': result,
|
155 |
+
'confidence': confidence,
|
156 |
+
'normal_probability': float(probabilities[0]),
|
157 |
+
'early_glaucoma_probability': float(probabilities[1]),
|
158 |
+
'advanced_glaucoma_probability': float(probabilities[2]),
|
159 |
+
'gradcam_image': gradcam_filename,
|
160 |
+
'gradcam_gray_image': gray_filename,
|
161 |
+
'image_filename': uploaded_filename
|
162 |
+
})
|
163 |
+
|
164 |
+
except Exception as e:
|
165 |
+
return jsonify({'error': str(e)}), 500
|
166 |
+
|
167 |
+
|
168 |
+
@app.route('/results', methods=['GET'])
|
169 |
+
def results():
|
170 |
+
"""List all results from the SQLite database."""
|
171 |
+
conn = sqlite3.connect(DB_PATH)
|
172 |
+
cursor = conn.cursor()
|
173 |
+
cursor.execute("SELECT * FROM results ORDER BY timestamp DESC")
|
174 |
+
results_data = cursor.fetchall()
|
175 |
+
conn.close()
|
176 |
+
|
177 |
+
results_list = []
|
178 |
+
for record in results_data:
|
179 |
+
results_list.append({
|
180 |
+
'id': record[0],
|
181 |
+
'image_filename': record[1],
|
182 |
+
'prediction': record[2],
|
183 |
+
'confidence': record[3],
|
184 |
+
'gradcam_filename': record[4],
|
185 |
+
'gradcam_gray_filename': record[5],
|
186 |
+
'timestamp': record[6]
|
187 |
+
})
|
188 |
+
|
189 |
+
return jsonify(results_list)
|
190 |
+
|
191 |
+
|
192 |
+
@app.route('/gradcam/<filename>')
|
193 |
+
def get_gradcam(filename):
|
194 |
+
"""Serve the Grad-CAM overlay image."""
|
195 |
+
filepath = os.path.join(OUTPUT_DIR, filename)
|
196 |
+
if os.path.exists(filepath):
|
197 |
+
return send_file(filepath, mimetype='image/png')
|
198 |
+
else:
|
199 |
+
return jsonify({'error': 'File not found'}), 404
|
200 |
+
|
201 |
+
|
202 |
+
@app.route('/image/<filename>')
|
203 |
+
def get_image(filename):
|
204 |
+
"""Serve the original uploaded image."""
|
205 |
+
filepath = os.path.join(OUTPUT_DIR, filename)
|
206 |
+
if os.path.exists(filepath):
|
207 |
+
return send_file(filepath, mimetype='image/png')
|
208 |
+
else:
|
209 |
+
return jsonify({'error': 'File not found'}), 404
|
210 |
+
|
211 |
+
|
212 |
+
if __name__ == '__main__':
|
213 |
+
app.run(host='0.0.0.0', port=7860)
|