Spaces:
Runtime error

File size: 8,657 Bytes
219c63d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import gradio as gr
import torch
import torchvision.transforms as transforms
import timm
import numpy as np
import cv2
from PIL import Image
from datetime import datetime
import calendar

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)

from gradcam_multi import (
    GradCAM_V1, GradCAM_V2, GradCAM_V3,
    GradCAM_V4, GradCAM_V5
)

# -----------------------------
# MODEL LOADING
# -----------------------------
def load_model(ckpt_path):
    model = timm.create_model("resnet18", pretrained=False)
    in_features = model.get_classifier().in_features
    model.fc = torch.nn.Sequential(
        torch.nn.Dropout(0.3),
        torch.nn.Linear(in_features, 2)
    )
    ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
    model.load_state_dict(ckpt["model_state"])
    model.to(device)
    model.eval()
    return model

model = load_model("checkpoints/resnet18/resnet18_best.pth")

variants = {
    "GradCAM v1": GradCAM_V1(model, model.layer4[-1]),
    "GradCAM v2": GradCAM_V2(model, model.layer4[-1]),
    "GradCAM_V3": GradCAM_V3(model, model.layer3[-1]),
    "GradCAM v4": GradCAM_V4(model, model.layer4[-1]),
    "GradCAM v5": GradCAM_V5(model, model.layer4[-1]),
}

preprocess = transforms.Compose([
    transforms.Resize((1024, 1024)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406],
                         [0.229, 0.224, 0.225]),
])

# -----------------------------
# GRADCAM OVERLAY
# -----------------------------
def overlay_cam(img, cam):
    img = np.array(img)
    cam_resized = cv2.resize(cam, (img.shape[1], img.shape[0]))
    cam_uint8 = (cam_resized * 255).astype("uint8")
    heatmap = cv2.applyColorMap(cam_uint8, cv2.COLORMAP_JET)
    heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
    overlay = 0.45 * heatmap + 0.55 * img
    return overlay.astype("uint8")

# -----------------------------
# PROCESS SINGLE IMAGE
# -----------------------------
def process_single(pil_img, sample_id, barcode, patient_name, mrn, dob):
    tensor = preprocess(pil_img).unsqueeze(0).to(device)

    with torch.no_grad():
        logits = model(tensor)
        probs = torch.softmax(logits, dim=1)[0]
        pred_class = torch.argmax(probs).item()
        confidence = float(probs[pred_class])
        pred_label = "Gram Positive" if pred_class == 1 else "Gram Negative"

    qc_status = (
        "QC PASS" if confidence > 0.60
        else "QC WARN" if confidence > 0.40
        else "QC FAIL"
    )

    cams = []
    for name, cam_gen in variants.items():
        cam = cam_gen.generate(tensor)
        overlay = overlay_cam(pil_img, cam)
        cams.append(overlay)

    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    report = (
        f"Timestamp: {timestamp}\n"
        f"Patient Name: {patient_name}\n"
        f"MRN: {mrn}\n"
        f"Date of Birth: {dob}\n"
        f"Sample ID: {sample_id}\n"
        f"Barcode: {barcode}\n"
        f"Result: {pred_label}\n"
        f"Confidence: {confidence:.2f}\n"
        f"QC Status: {qc_status}"
    )

    return pred_label, pil_img, cams, qc_status, confidence, report

# -----------------------------
# ANALYZE FUNCTION
# -----------------------------
def analyze(sample_id, barcode, patient_name, mrn, year, month, day, images):
    if year and month and day:
        dob = f"{int(year)}-{int(month):02d}-{int(day):02d}"
    else:
        dob = "N/A"

    if images is None:
        return ("ERROR: No images", None, None, "ERROR", 0, "No report")

    if not isinstance(images, list):
        images = [images]

    if len(images) == 1:
        pil_img = Image.open(images[0].name).convert("RGB")
        pred, orig, cams, qc, conf, rep = process_single(
            pil_img, sample_id, barcode, patient_name, mrn, dob
        )
        return (pred, [orig], cams, qc, conf, rep)

    originals = []
    all_cams = []
    reports = []

    for img_file in images:
        pil_img = Image.open(img_file.name).convert("RGB")
        pred, orig, cams, qc, conf, rep = process_single(
            pil_img, sample_id, barcode, patient_name, mrn, dob
        )
        originals.append(orig)
        all_cams.extend(cams)
        reports.append(rep)

    batch_report = "\n\n".join(reports)

    return ("Batch Complete", originals, all_cams, "READY", 1, batch_report)

# -----------------------------
# CALENDAR HELPERS
# -----------------------------
def month_name(m):
    return calendar.month_name[int(m)]

def days_for(year, month):
    year = int(year)
    month = int(month)
    return list(range(1, calendar.monthrange(year, month)[1] + 1))

def update_labels_and_days(year, month):
    m_label = f"<div style='font-size:18px; text-align:center;'>{month_name(month)}</div>"
    y_label = f"<div style='font-size:18px; text-align:center;'>{int(year)}</div>"
    return m_label, y_label, gr.Dropdown.update(choices=days_for(year, month))

def prev_year(y, m):
    y = int(y)
    m = int(m)
    y = max(1920, y - 1)
    m_label, y_label, day_update = update_labels_and_days(y, m)
    return y, m, m_label, y_label, day_update

def next_year(y, m):
    y = int(y)
    m = int(m)
    y = min(datetime.now().year, y + 1)
    m_label, y_label, day_update = update_labels_and_days(y, m)
    return y, m, m_label, y_label, day_update

def prev_month(y, m):
    y = int(y)
    m = int(m)
    if m == 1:
        m = 12
        y = max(1920, y - 1)
    else:
        m -= 1
    m_label, y_label, day_update = update_labels_and_days(y, m)
    return y, m, m_label, y_label, day_update

def next_month(y, m):
    y = int(y)
    m = int(m)
    if m == 12:
        m = 1
        y = min(datetime.now().year, y + 1)
    else:
        m += 1
    m_label, y_label, day_update = update_labels_and_days(y, m)
    return y, m, m_label, y_label, day_update

# -----------------------------
# UI
# -----------------------------
css = """
body, .gradio-container {
    background-color: #1A1C20 !important;
    color: #E4E4E6 !important;
}
"""

with gr.Blocks(css=css) as demo:

    gr.Markdown("## Gram Stain Diagnostic System — MRN + DOB with Arrow Calendar")

    with gr.Row():
        with gr.Column(scale=1):
            sample_id = gr.Textbox(label="Sample ID")
            barcode = gr.Textbox(label="Barcode")
            patient_name = gr.Textbox(label="Patient Name")
            mrn = gr.Textbox(label="MRN (Medical Record Number)")

            # Calendar state
            start_year = 2005
            year_state = gr.State(start_year)
            month_state = gr.State(1)

            with gr.Row():
                prev_year_btn = gr.Button("<<")
                year_label = gr.HTML(
                    f"<div style='font-size:18px; text-align:center;'>{start_year}</div>"
                )
                next_year_btn = gr.Button(">>")

            with gr.Row():
                prev_month_btn = gr.Button("<")
                month_label = gr.HTML(
                    f"<div style='font-size:18px; text-align:center;'>{month_name(1)}</div>"
                )
                next_month_btn = gr.Button(">")

            day = gr.Dropdown(
                choices=days_for(start_year, 1),
                label="Day"
            )

            input_imgs = gr.File(label="Upload Image(s)", file_count="multiple")
            analyze_btn = gr.Button("Run Analysis")

            pred = gr.Label(label="Status")
            qc_status = gr.Label(label="QC")
            confidence_bar = gr.Slider(0, 1, label="Confidence")
            report_box = gr.Textbox(lines=10, label="Report")

        with gr.Column(scale=2):
            original_display = gr.Gallery(label="Original(s)", columns=3)
            cam_grid = gr.Gallery(label="Grad‑CAM Outputs", columns=3)

    # Wire year/month arrows
    prev_year_btn.click(
        prev_year,
        [year_state, month_state],
        [year_state, month_state, month_label, year_label, day],
    )
    next_year_btn.click(
        next_year,
        [year_state, month_state],
        [year_state, month_state, month_label, year_label, day],
    )
    prev_month_btn.click(
        prev_month,
        [year_state, month_state],
        [year_state, month_state, month_label, year_label, day],
    )
    next_month_btn.click(
        next_month,
        [year_state, month_state],
        [year_state, month_state, month_label, year_label, day],
    )

    # Run analysis
    analyze_btn.click(
        analyze,
        [sample_id, barcode, patient_name, mrn, year_state, month_state, day, input_imgs],
        [pred, original_display, cam_grid, qc_status, confidence_bar, report_box],
    )

demo.launch(share=True)