Spaces:
Runtime error

gradiocam / app.py
HAHAHAonezeroone's picture
Upload folder using huggingface_hub
219c63d verified
Raw History Blame Contribute Delete
8.66 kB
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)