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"