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") 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]), ]) RECOMMENDATIONS = { "Low" : "Low PCOS probability. Routine monitoring recommended.", "Moderate": "Moderate PCOS probability. Clinical evaluation and hormonal panel recommended.", "High" : "High PCOS probability. Urgent clinical review and comprehensive workup advised.", } def load_image_model(model_path): model = models.efficientnet_b0(weights=None) in_features = model.classifier[1].in_features model.classifier[1] = nn.Linear(in_features, 2) checkpoint = torch.load(model_path, map_location=DEVICE, weights_only=False) 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): 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_pcos = round(probs[1].item(), 4) prob_not = round(probs[0].item(), 4) if prob_pcos < 0.33: cat = "Low" elif prob_pcos < 0.66: cat = "Moderate" else: cat = "High" return { "prob_pcos" : prob_pcos, "prob_not_pcos" : prob_not, "risk_score" : round(prob_pcos * 100, 1), "risk_category" : cat, "recommendation": RECOMMENDATIONS[cat], "pred_label" : "PCOS" if prob_pcos >= 0.5 else "Not PCOS", } class GradCAM: def __init__(self, model, target_layer): self.model = model self.gradients = None self.activations = None self._fh = target_layer.register_forward_hook(self._save_act) self._bh = target_layer.register_full_backward_hook(self._save_grad) def _save_act(self, m, i, o): self.activations = o.detach() def _save_grad(self, m, gi, go): self.gradients = go[0].detach() def generate(self, tensor, class_idx=1): self.model.zero_grad() out = self.model(tensor) out[0, class_idx].backward() grads = self.gradients[0] acts = self.activations[0] weights = grads.mean(dim=(1, 2)) 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 generate_gradcam_overlay(model, pil_image, class_idx=1): 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) gcam = GradCAM(model, model.features[-1]) cam = gcam.generate(tensor, class_idx=class_idx) gcam.remove() cam_r = cv2.resize(cam, (IMG_SIZE, IMG_SIZE)) heatmap = cv2.applyColorMap(np.uint8(255 * cam_r), cv2.COLORMAP_JET) heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) overlay = (0.5 * img_rgb + 0.5 * heatmap).astype(np.uint8) return overlay, heatmap