""" EfficientNetB0 inference + Grad-CAM for PCOS ultrasound detection. Mirrors the exact model architecture and preprocessing from the original notebook. """ import torch import torch.nn as nn import numpy as np import cv2 from PIL import Image from torchvision import models, transforms IMG_SIZE = 224 DEVICE = torch.device("cpu") # HF Spaces free tier is CPU PREPROCESS = transforms.Compose([ transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std =[0.229, 0.224, 0.225]), ]) RISK_THRESHOLDS = { "Low" : (0.00, 0.33), "Moderate" : (0.33, 0.66), "High" : (0.66, 1.00), } RECOMMENDATIONS = { "Low" : "Low PCOS probability. Routine monitoring recommended. Repeat scan if symptoms develop.", "Moderate" : "Moderate PCOS probability. Clinical evaluation recommended. Consider hormonal panel (FSH, LH, AMH).", "High" : "High PCOS probability. Urgent clinical review recommended. Comprehensive hormonal workup advised.", } def build_model(): """Build EfficientNetB0 with same head as training.""" model = models.efficientnet_b0(weights=None) in_features = model.classifier[1].in_features model.classifier[1] = nn.Linear(in_features, 2) return model def load_image_model(model_path: str): """Load trained EfficientNetB0 weights.""" model = build_model() checkpoint = torch.load(model_path, map_location=DEVICE, weights_only=False) # Handle both raw state_dict and checkpoint dict if isinstance(checkpoint, dict) and "model_state" in checkpoint: model.load_state_dict(checkpoint["model_state"]) else: model.load_state_dict(checkpoint) model.eval() return model.to(DEVICE) def predict_image(model, pil_image: Image.Image) -> dict: """ Run inference on a PIL image. Returns prob_pcos, prob_not_pcos, risk_category, recommendation. """ tensor = PREPROCESS(pil_image.convert("RGB")).unsqueeze(0).to(DEVICE) with torch.no_grad(): out = model(tensor) probs = torch.softmax(out, dim=1)[0] prob_not_pcos = round(probs[0].item(), 4) prob_pcos = round(probs[1].item(), 4) risk_score = round(prob_pcos * 100, 1) category = "Low" for cat, (lo, hi) in RISK_THRESHOLDS.items(): if lo <= prob_pcos < hi: category = cat break if prob_pcos >= 0.66: category = "High" return { "prob_pcos" : prob_pcos, "prob_not_pcos" : prob_not_pcos, "risk_score" : risk_score, "risk_category" : category, "recommendation": RECOMMENDATIONS[category], "pred_label" : "PCOS" if prob_pcos >= 0.5 else "Not PCOS", } # ============================================================================= # GRAD-CAM # ============================================================================= class GradCAM: """Grad-CAM implementation identical to original notebook.""" def __init__(self, model, target_layer): self.model = model self.gradients = None self.activations = None self._fh = target_layer.register_forward_hook(self._save_activation) self._bh = target_layer.register_full_backward_hook(self._save_gradient) def _save_activation(self, module, inp, output): self.activations = output.detach() def _save_gradient(self, module, grad_input, grad_output): self.gradients = grad_output[0].detach() def generate(self, tensor, class_idx=None): """Generate Grad-CAM heatmap. class_idx=None → uses predicted class.""" self.model.zero_grad() out = self.model(tensor) if class_idx is None: class_idx = out.argmax(dim=1).item() out[0, class_idx].backward() grads = self.gradients[0] # (C, H, W) acts = self.activations[0] # (C, H, W) weights = grads.mean(dim=(1, 2)) # (C,) cam = torch.zeros(acts.shape[1:]) for i, w in enumerate(weights): cam += w * acts[i] cam = torch.relu(cam).numpy() cam -= cam.min() if cam.max() > 0: cam /= cam.max() return cam def remove(self): self._fh.remove() self._bh.remove() def get_target_layer(model): """Return the last conv block of EfficientNetB0 for Grad-CAM.""" return model.features[-1] def generate_gradcam_overlay(model, pil_image: Image.Image, class_idx: int = 1) -> np.ndarray: """ Returns an RGB numpy array of the Grad-CAM overlay (same size as input). class_idx=1 → PCOS class heatmap. """ img_rgb = np.array(pil_image.convert("RGB").resize((IMG_SIZE, IMG_SIZE))) tensor = PREPROCESS(pil_image.convert("RGB")).unsqueeze(0).to(DEVICE) tensor.requires_grad_(True) target_layer = get_target_layer(model) gcam = GradCAM(model, target_layer) cam = gcam.generate(tensor, class_idx=class_idx) gcam.remove() # Resize CAM to image size cam_resized = cv2.resize(cam, (IMG_SIZE, IMG_SIZE)) heatmap = cv2.applyColorMap( np.uint8(255 * cam_resized), cv2.COLORMAP_JET) heatmap_rgb = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) # Overlay: 50% original + 50% heatmap overlay = (0.5 * img_rgb + 0.5 * heatmap_rgb).astype(np.uint8) return overlay, heatmap_rgb