File size: 6,803 Bytes
ac9f500
 
751c399
 
 
ac9f500
751c399
ac9f500
d318540
c539386
cf2ad62
0cdf25a
cf2ad62
5e8dac1
 
 
 
 
ac9f500
 
cc71d5c
 
 
 
c544fc1
cc71d5c
c544fc1
751c399
d318540
b050424
d318540
 
 
 
 
 
 
 
 
8b4e7ae
d318540
 
 
 
 
de50b3c
751c399
d318540
b050424
 
5e8dac1
b050424
 
0ac5b89
456a39c
0e25922
0ac5b89
c539386
5a322a1
93d636a
b050424
 
4ca7330
 
b050424
5e8dac1
4ca7330
b050424
0cdf25a
ac9f500
 
b050424
c539386
ac9f500
 
 
751c399
b050424
ac9f500
69c8cf6
ac9f500
cc71d5c
 
 
 
5e8dac1
cc71d5c
 
 
3c9ef9c
 
cc71d5c
 
 
3c9ef9c
 
 
 
 
 
 
 
751c399
cc71d5c
5e8dac1
0cdf25a
73e939c
c539386
 
 
cc71d5c
5e8dac1
edcb5de
5e8dac1
8b4e7ae
5e8dac1
 
8b4e7ae
5e8dac1
 
 
8b4e7ae
5e8dac1
 
8b4e7ae
5e8dac1
0cdf25a
 
5e8dac1
8b4e7ae
5e8dac1
b7b8021
 
5e8dac1
8b4e7ae
b7b8021
cc71d5c
 
 
8b4e7ae
 
 
cc71d5c
 
8b4e7ae
b7b8021
cc71d5c
 
 
c539386
 
 
0cdf25a
b7b8021
3c9ef9c
cc71d5c
5e8dac1
cc71d5c
 
 
0cdf25a
cc71d5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b4e7ae
 
cc71d5c
 
 
 
0cdf25a
cc71d5c
 
0cdf25a
cc71d5c
 
 
 
 
 
0cdf25a
3c9ef9c
 
 
 
 
 
 
 
 
0cdf25a
cc71d5c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
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
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
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
from flask import Flask, request, jsonify, send_file
from PIL import Image
import torch
import torch.nn.functional as F
from torchvision import transforms
import os
import numpy as np
from datetime import datetime
import sqlite3
import torch.nn as nn
import torchvision.models as models
import cv2

# βœ… New Grad-CAM++ imports
from pytorch_grad_cam import GradCAMPlusPlus
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from pytorch_grad_cam.utils.image import show_cam_on_image

app = Flask(__name__)

# βœ… Directory and database path
OUTPUT_DIR = '/tmp/results'
if not os.path.exists(OUTPUT_DIR):
    os.makedirs(OUTPUT_DIR)

DB_PATH = os.path.join(OUTPUT_DIR, 'results.db')


def init_db():
    """Initialize SQLite database for storing results."""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS results (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            image_filename TEXT,
            prediction TEXT,
            confidence REAL,
            gradcam_filename TEXT,
            gradcam_gray_filename TEXT,
            timestamp TEXT
        )
    """)
    conn.commit()
    conn.close()


init_db()

# βœ… Import your custom GLAM model
from densenet_withglam import get_model_with_attention

# βœ… Instantiate the model
model = get_model_with_attention('densenet169', num_classes=3)  # Will have GLAM
model.load_state_dict(torch.load('densenet169_seed40_best.pt', map_location='cpu'))
model.eval()

# βœ… Class Names
CLASS_NAMES = ["Advanced", "Early", "Normal"]

# βœ… Transformation for input images
transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

@app.route('/')
def home():
    """Check that the API is working."""
    return "Glaucoma Detection Flask API (3-Class Model) is running!"

@app.route("/test_file")
def test_file():
    """Check if the .pt model file is present and readable."""
    filepath = "densenet169_seed40_best2.pt"
    if os.path.exists(filepath):
        return f"βœ… Model file found at: {filepath}"
    else:
        return "❌ Model file NOT found."

@app.route('/predict', methods=['POST'])
def predict():
    """Perform prediction and save results (including Grad-CAM++) to the database."""
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400

    uploaded_file = request.files['file']
    if uploaded_file.filename == '':
        return jsonify({'error': 'No file selected'}), 400

    try:
        # βœ… Save the uploaded image
        timestamp = int(datetime.now().timestamp())
        uploaded_filename = f"uploaded_{timestamp}.png"
        uploaded_file_path = os.path.join(OUTPUT_DIR, uploaded_filename)
        uploaded_file.save(uploaded_file_path)

        # βœ… Perform prediction
        img = Image.open(uploaded_file_path).convert('RGB')
        input_tensor = transform(img).unsqueeze(0)

        # βœ… Get prediction
        output = model(input_tensor)
        probabilities = F.softmax(output, dim=1).cpu().detach().numpy()[0]
        class_index = np.argmax(probabilities)
        result = CLASS_NAMES[class_index]
        confidence = float(probabilities[class_index])

        # βœ… Grad-CAM++ setup
        target_layer = model.features[2].global_spatial_conv
        cam_model = GradCAMPlusPlus(model=model, target_layers=[target_layer])

        # βœ… Get Grad-CAM++ map
        cam_output = cam_model(input_tensor=input_tensor, targets=[ClassifierOutputTarget(class_index)])[0]

        # βœ… Create RGB overlay
        original_img = np.asarray(img.resize((224, 224)), dtype=np.float32) / 255.0
        overlay = show_cam_on_image(original_img, cam_output, use_rgb=True)

        # βœ… Create grayscale version
        cam_normalized = np.uint8(255 * cam_output)

        # βœ… Save overlay
        gradcam_filename = f"gradcam_{timestamp}.png"
        gradcam_file_path = os.path.join(OUTPUT_DIR, gradcam_filename)
        cv2.imwrite(gradcam_file_path, cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))

        # βœ… Save grayscale
        gray_filename = f"gradcam_gray_{timestamp}.png"
        gray_file_path = os.path.join(OUTPUT_DIR, gray_filename)
        cv2.imwrite(gray_file_path, cam_normalized)

        # βœ… Save results to database
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO results (image_filename, prediction, confidence, gradcam_filename, gradcam_gray_filename, timestamp) 
            VALUES (?, ?, ?, ?, ?, ?)
        """, (uploaded_filename, result, confidence, gradcam_filename, gray_filename, datetime.now().isoformat()))
        conn.commit()
        conn.close()

        # βœ… Return results
        return jsonify({
            'prediction': result,
            'confidence': confidence,
            'normal_probability': float(probabilities[0]),
            'early_glaucoma_probability': float(probabilities[1]),
            'advanced_glaucoma_probability': float(probabilities[2]),
            'gradcam_image': gradcam_filename,
            'gradcam_gray_image': gray_filename,
            'image_filename': uploaded_filename
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/results', methods=['GET'])
def results():
    """List all results from the SQLite database."""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM results ORDER BY timestamp DESC")
    results_data = cursor.fetchall()
    conn.close()

    results_list = []
    for record in results_data:
        results_list.append({
            'id': record[0],
            'image_filename': record[1],
            'prediction': record[2],
            'confidence': record[3],
            'gradcam_filename': record[4],
            'gradcam_gray_filename': record[5],
            'timestamp': record[6]
        })

    return jsonify(results_list)


@app.route('/gradcam/<filename>')
def get_gradcam(filename):
    """Serve the Grad-CAM overlay image."""
    filepath = os.path.join(OUTPUT_DIR, filename)
    if os.path.exists(filepath):
        return send_file(filepath, mimetype='image/png')
    else:
        return jsonify({'error': 'File not found'}), 404


@app.route('/image/<filename>')
def get_image(filename):
    """Serve the original uploaded image."""
    filepath = os.path.join(OUTPUT_DIR, filename)
    if os.path.exists(filepath):
        return send_file(filepath, mimetype='image/png')
    else:
        return jsonify({'error': 'File not found'}), 404


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)