Download app.py from DheivaCodes/PCOS_Ultrasound_Image_Detection: direct link, hf CLI and curl.
- Browser
- Download file 20.5 kB
-
https://huggingface.co/spaces/DheivaCodes/PCOS_Ultrasound_Image_Detection/resolve/main/app.py
- Command line
-
hf download hf://spaces/DheivaCodes/PCOS_Ultrasound_Image_Detection/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DheivaCodes/PCOS_Ultrasound_Image_Detection/resolve/main/app.py
20.5 kB
| """ | |
| PCOS Image Detection β DenseNet121 | |
| - Tab 1: Single Image Analysis + Grad-CAM | |
| - Tab 2: Batch Upload | |
| - Tab 3: About | |
| """ | |
| import os, warnings | |
| warnings.filterwarnings("ignore") | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import matplotlib.cm as cm_mod | |
| import gradio as gr | |
| import torch | |
| import torch.nn as nn | |
| from torchvision import models as tv_models, transforms | |
| from PIL import Image | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CONFIG | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| MODELS_DIR = "models" | |
| IMG_SIZE = 224 | |
| DEVICE = torch.device("cpu") | |
| CLASS_NAMES = ["Not PCOS", "PCOS"] | |
| PCOS_IDX = 1 | |
| VAL_TRANSFORM = 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]), | |
| ]) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # LOAD MODEL | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def load_image_model(): | |
| candidates = [ | |
| os.path.join(MODELS_DIR, "best_model.pth"), | |
| os.path.join(MODELS_DIR, "densenet121.pth"), | |
| os.path.join(MODELS_DIR, "DenseNet121.pth"), | |
| ] | |
| pth = next((p for p in candidates if os.path.exists(p)), None) | |
| if pth is None: | |
| existing = os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else [] | |
| print(f"β οΈ Model not found. models/ contains: {existing}") | |
| return None | |
| try: | |
| net = tv_models.densenet121(weights=None) | |
| in_features = net.classifier.in_features | |
| net.classifier = nn.Linear(in_features, 2) | |
| ckpt = torch.load(pth, map_location=DEVICE, weights_only=False) | |
| if isinstance(ckpt, dict): | |
| state = (ckpt.get("model_state") or ckpt.get("model_state_dict") | |
| or ckpt.get("state_dict") or ckpt) | |
| else: | |
| state = ckpt | |
| net.load_state_dict(state, strict=True) | |
| net.to(DEVICE).eval() | |
| print(f"β DenseNet121 loaded: {pth}") | |
| return net | |
| except Exception as e: | |
| print(f"β οΈ Model failed to load: {e}") | |
| return None | |
| IMAGE_MODEL = load_image_model() | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # INFERENCE | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_inference(img_rgb: Image.Image): | |
| tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE) | |
| with torch.no_grad(): | |
| probs = torch.softmax(IMAGE_MODEL(tensor), dim=1)[0] | |
| return float(probs[PCOS_IDX]), float(probs[1 - PCOS_IDX]), int(probs.argmax()) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GRAD-CAM | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def compute_gradcam(img_rgb: Image.Image, target_class: int): | |
| grads, acts = [], [] | |
| def fwd_hook(m, inp, out): | |
| acts.append(out.detach()) | |
| out.register_hook(lambda g: grads.append(g.detach())) | |
| handle = IMAGE_MODEL.features.denseblock4.register_forward_hook(fwd_hook) | |
| tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE) | |
| IMAGE_MODEL.zero_grad() | |
| for param in IMAGE_MODEL.parameters(): | |
| param.requires_grad_(True) | |
| output = IMAGE_MODEL(tensor) | |
| output[0, target_class].backward() | |
| handle.remove() | |
| if not grads or not acts: | |
| return None | |
| w = grads[0].squeeze(0).mean(dim=(1, 2)).cpu().numpy() | |
| act = acts[0].squeeze(0).cpu().numpy() | |
| cam = np.maximum(sum(w[i] * act[i] for i in range(len(w))), 0) | |
| if cam.max() > 1e-8: | |
| cam /= cam.max() | |
| cam_up = np.array( | |
| Image.fromarray((cam * 255).astype(np.uint8)).resize( | |
| (IMG_SIZE, IMG_SIZE), Image.BILINEAR) | |
| ) / 255.0 | |
| orig_r = np.array(img_rgb.resize((IMG_SIZE, IMG_SIZE))) | |
| heat = cm_mod.jet(cam_up)[:, :, :3] | |
| overlay = np.clip(0.55 * orig_r / 255.0 + 0.45 * heat, 0, 1) | |
| fig, axes = plt.subplots(1, 3, figsize=(14, 4), facecolor="#0f172a", | |
| gridspec_kw={"wspace": 0.05}) | |
| for ax, (img, cmap, title) in zip(axes, [ | |
| (orig_r, None, "Original Image"), | |
| (cam_up, "jet", "Grad-CAM Heatmap"), | |
| (overlay, None, "Activation Overlay"), | |
| ]): | |
| ax.set_facecolor("#0f172a") | |
| ax.imshow(img, cmap=cmap) | |
| ax.set_title(title, color="white", fontsize=11, fontweight="bold", pad=6) | |
| ax.axis("off") | |
| fig.text(0.5, -0.01, | |
| f"Grad-CAM Β· DenseNet121 Β· features.denseblock4 Β· Predicted: {CLASS_NAMES[target_class]}", | |
| ha="center", color="#94a3b8", fontsize=9) | |
| plt.tight_layout(pad=0.3) | |
| return fig | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GAUGE CHART | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def make_gauge(pcos_prob: float): | |
| fig, ax = plt.subplots(figsize=(5, 2.6), facecolor="#0f172a") | |
| ax.set_facecolor("#0f172a") | |
| ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.axis("off") | |
| ax.barh([0.5], [1.0], height=0.30, color="#1e293b", left=0, align="center", zorder=1) | |
| color = "#22c55e" if pcos_prob < 0.33 else "#f59e0b" if pcos_prob < 0.66 else "#ef4444" | |
| ax.barh([0.5], [pcos_prob], height=0.30, color=color, left=0, align="center", zorder=2) | |
| ax.axvline(0.5, color="white", lw=1.5, ls="--", alpha=0.7, zorder=3) | |
| ax.text(pcos_prob, 0.5, f" {pcos_prob*100:.1f}%", va="center", color="white", | |
| fontsize=16, fontweight="bold", zorder=4, | |
| ha="left" if pcos_prob < 0.85 else "right") | |
| for x, lbl, c in [(0.16, "Low", "#22c55e"), (0.50, "Moderate", "#f59e0b"), (0.83, "High", "#ef4444")]: | |
| ax.text(x, 0.12, lbl, color=c, fontsize=8, ha="center", alpha=0.8) | |
| ax.text(0.5, 0.92, "PCOS Probability", color="#94a3b8", fontsize=9, ha="center", va="top") | |
| plt.tight_layout(pad=0.2) | |
| return fig | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # BATCH CHART | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def make_batch_chart(pcos_c: int, notp_c: int, total: int): | |
| fig = plt.figure(figsize=(10, 4), facecolor="#0f172a") | |
| ax1 = fig.add_subplot(1, 2, 1); ax1.set_facecolor("#0f172a") | |
| if total > 0: | |
| _, _, autotexts = ax1.pie( | |
| [pcos_c, notp_c], | |
| labels=[f"PCOS\n{pcos_c}", f"Not PCOS\n{notp_c}"], | |
| colors=["#ef4444", "#22c55e"], autopct="%1.1f%%", startangle=90, | |
| textprops={"color": "white", "fontsize": 10}, | |
| wedgeprops={"linewidth": 2, "edgecolor": "#0f172a"}, pctdistance=0.75) | |
| for at in autotexts: | |
| at.set_color("white"); at.set_fontsize(10); at.set_fontweight("bold") | |
| ax1.set_title("Class Distribution", color="white", fontsize=12, fontweight="bold", pad=12) | |
| ax2 = fig.add_subplot(1, 2, 2); ax2.set_facecolor("#0f172a") | |
| bars = ax2.bar(["Not PCOS", "PCOS"], [notp_c, pcos_c], | |
| color=["#22c55e", "#ef4444"], width=0.45, edgecolor="#0f172a", linewidth=2) | |
| ax2.set_ylim(0, max(pcos_c, notp_c) * 1.35 + 0.5) | |
| ax2.set_title("Count per Class", color="white", fontsize=12, fontweight="bold", pad=12) | |
| ax2.tick_params(colors="white", labelsize=11) | |
| for sp in ax2.spines.values(): sp.set_visible(False) | |
| ax2.yaxis.set_visible(False) | |
| for bar, cnt in zip(bars, [notp_c, pcos_c]): | |
| ax2.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.15, | |
| str(cnt), ha="center", color="white", fontsize=14, fontweight="bold") | |
| fig.text(0.5, 0.01, f"Total: {total} image{'s' if total > 1 else ''} Β· DenseNet121", | |
| ha="center", color="#64748b", fontsize=9) | |
| plt.tight_layout(pad=1.5) | |
| return fig | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # HANDLERS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def predict_single(image): | |
| if IMAGE_MODEL is None: | |
| return ("## β Model not loaded\n\nUpload `best_model.pth` to the `models/` folder."), None, None | |
| if image is None: | |
| return "β οΈ Please upload an ultrasound image.", None, None | |
| try: | |
| img_rgb = (image if isinstance(image, Image.Image) else Image.fromarray(image)).convert("RGB") | |
| pcos_p, notp, pred = run_inference(img_rgb) | |
| icon = "π΄" if pred == PCOS_IDX else "π’" | |
| label = CLASS_NAMES[pred] | |
| conf = pcos_p if pred == PCOS_IDX else notp | |
| risk = "π’ Low" if pcos_p < 0.33 else "π‘ Moderate" if pcos_p < 0.66 else "π΄ High" | |
| result = f"""### {icon} {label} | |
| | Metric | Value | | |
| |---|---| | |
| | PCOS Probability | **{pcos_p*100:.1f}%** | | |
| | Not PCOS Probability | **{notp*100:.1f}%** | | |
| | Confidence | **{conf*100:.1f}%** | | |
| | Risk Level | **{risk}** | | |
| *DenseNet121 Β· 224Γ224 Β· ImageNet normalisation Β· Val AUC: 0.9998 Β· MCC: 0.9648* | |
| > β οΈ Research use only β not a clinical tool.""" | |
| return result, make_gauge(pcos_p), compute_gradcam(img_rgb, pred) | |
| except Exception as e: | |
| import traceback | |
| return f"β Error: {e}\n```\n{traceback.format_exc()}\n```", None, None | |
| def predict_batch(files): | |
| if IMAGE_MODEL is None: | |
| return ("## β Model not loaded\n\nUpload `best_model.pth` to `models/`."), None | |
| if not files: | |
| return "β οΈ Upload at least one image.", None | |
| rows = []; pcos_c = 0; notp_c = 0 | |
| for f in files: | |
| try: | |
| img = Image.open(f.name).convert("RGB") | |
| pcos_p, notp, pred = run_inference(img) | |
| icon = "π΄" if pred == PCOS_IDX else "π’" | |
| rows.append({ | |
| "File" : os.path.basename(f.name), | |
| "Prediction": f"{icon} {CLASS_NAMES[pred]}", | |
| "PCOS%" : f"{pcos_p*100:.1f}", | |
| "Not PCOS%" : f"{notp*100:.1f}", | |
| "Risk" : "Low" if pcos_p < 0.33 else "Moderate" if pcos_p < 0.66 else "High" | |
| }) | |
| if pred == PCOS_IDX: pcos_c += 1 | |
| else: notp_c += 1 | |
| except Exception as e: | |
| rows.append({"File": os.path.basename(f.name), "Prediction": f"β {e}", | |
| "PCOS%": "β", "Not PCOS%": "β", "Risk": "β"}) | |
| total = len(rows) | |
| table = "\n".join( | |
| f"| `{r['File']}` | {r['Prediction']} | {r['PCOS%']}% | {r['Not PCOS%']}% | {r['Risk']} |" | |
| for r in rows) | |
| summary = f"""### π Batch Summary β {total} image{'s' if total > 1 else ''} | |
| | | Count | % | | |
| |---|---|---| | |
| | π΄ PCOS | **{pcos_c}** | **{pcos_c/total*100:.1f}%** | | |
| | π’ Not PCOS | **{notp_c}** | **{notp_c/total*100:.1f}%** | | |
| | Total | **{total}** | 100% | | |
| --- | |
| ### Per-Image Results | |
| | File | Prediction | PCOS% | Not PCOS% | Risk | | |
| |---|---|---|---|---| | |
| {table} | |
| > β οΈ Research use only.""" | |
| return summary, make_batch_chart(pcos_c, notp_c, total) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CSS + UI | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| CSS = """ | |
| body,.gradio-container{background:#0D0D1A !important;font-family:'Inter','Segoe UI',sans-serif !important;} | |
| .app-header{background:linear-gradient(135deg,#1e1b4b 0%,#312e81 50%,#1e1b4b 100%); | |
| border:1px solid #4338ca;border-radius:16px;padding:28px 36px;margin-bottom:16px;text-align:center;} | |
| .app-header h1{color:#e0e7ff !important;font-size:2rem !important;font-weight:700 !important;margin:0 0 4px 0 !important;} | |
| .app-header p{color:#a5b4fc !important;font-size:0.95rem !important;margin:0 !important;} | |
| .disclaimer{background:#1c1917;border-left:4px solid #f59e0b;border-radius:8px; | |
| padding:10px 16px;color:#fbbf24 !important;font-size:0.85rem;margin-bottom:16px;} | |
| .sec{color:#c7d2fe !important;font-size:0.75rem !important;font-weight:700 !important; | |
| letter-spacing:1.4px !important;text-transform:uppercase !important; | |
| margin:0 0 8px 0 !important;padding-bottom:6px !important;border-bottom:1px solid #334155 !important;} | |
| .info-box{background:#1e293b;border:1px solid #334155;border-radius:10px; | |
| padding:14px 18px;font-size:0.85rem;color:#94a3b8;line-height:1.7;} | |
| .info-box strong{color:#c7d2fe;} | |
| .tab-nav button{color:#94a3b8 !important;font-size:0.9rem !important;font-weight:600 !important;} | |
| .tab-nav button.selected{color:#818cf8 !important;border-bottom:2px solid #818cf8 !important;background:#1e293b !important;} | |
| button.primary{background:linear-gradient(135deg,#4f46e5,#7c3aed) !important; | |
| border:none !important;border-radius:10px !important;font-weight:700 !important; | |
| color:white !important;padding:12px 0 !important;} | |
| table{width:100%;border-collapse:collapse;font-size:0.88rem;} | |
| th{background:#1e3a5f;color:#93c5fd;padding:8px 12px;text-align:left;font-weight:600;} | |
| td{padding:7px 12px;border-bottom:1px solid #1e293b;color:#e2e8f0;} | |
| tr:nth-child(even) td{background:#1a2540;} | |
| footer{display:none !important;} | |
| """ | |
| with gr.Blocks( | |
| theme=gr.themes.Base(primary_hue="purple", secondary_hue="violet", neutral_hue="slate", | |
| font=[gr.themes.GoogleFont("Inter"), "sans-serif"]), | |
| css=CSS, title="PCOS Ultrasound Detection β DenseNet121" | |
| ) as demo: | |
| gr.HTML(""" | |
| <div class="app-header"> | |
| <h1>π¬ PCOS Ultrasound Detection</h1> | |
| <p>DenseNet121 Β· Grad-CAM XAI Β· Single & Batch Analysis Β· Val AUC 0.9998 Β· MCC 0.9648</p> | |
| </div> | |
| <div class="disclaimer"> | |
| β οΈ <strong>Medical Disclaimer:</strong> For <strong>research & educational purposes only</strong>. | |
| Not a certified medical device. Consult a qualified clinician for any health decisions. | |
| </div>""") | |
| with gr.Tabs(elem_classes="tab-nav"): | |
| # ββ TAB 1: SINGLE IMAGE βββββββββββββββββββββββββββββββββββ | |
| with gr.TabItem("πΌοΈ Single Image Analysis"): | |
| with gr.Row(equal_height=False): | |
| with gr.Column(scale=4): | |
| gr.HTML('<p class="sec">π Upload Ultrasound Image</p>') | |
| img_input = gr.Image(label="", type="pil", height=280) | |
| img_btn = gr.Button("π Analyze Image", variant="primary", size="lg") | |
| gr.HTML("""<div class="info-box" style="margin-top:12px"> | |
| <strong>Model:</strong> DenseNet121 (fine-tuned)<br> | |
| <strong>Why best:</strong> Highest MCC (0.9648) Β· Val AUC (0.9998) Β· Lowest Log Loss (0.0357)<br> | |
| <strong>Specificity:</strong> 0.9918 β lowest false positive rate<br> | |
| <strong>Input:</strong> 224Γ224 RGB Β· ImageNet normalisation<br> | |
| <strong>XAI:</strong> Grad-CAM on <code>features.denseblock4</code> | |
| </div>""") | |
| with gr.Column(scale=6): | |
| gr.HTML('<p class="sec">π Diagnosis Result</p>') | |
| img_result = gr.Markdown(value="*Upload an image and click Analyze.*") | |
| gr.HTML('<p class="sec" style="margin-top:14px">π Risk Probability Gauge</p>') | |
| img_gauge = gr.Plot(label="", show_label=False) | |
| gr.HTML('<p class="sec" style="margin-top:6px">π₯ Grad-CAM Explainability β Where the model looks</p>') | |
| img_gradcam = gr.Plot(label="", show_label=False) | |
| img_btn.click(fn=predict_single, inputs=[img_input], | |
| outputs=[img_result, img_gauge, img_gradcam]) | |
| # ββ TAB 2: BATCH ββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.TabItem("π Batch Analysis"): | |
| with gr.Row(equal_height=False): | |
| with gr.Column(scale=4): | |
| gr.HTML('<p class="sec">π Upload Multiple Images</p>') | |
| batch_input = gr.File(label="", file_count="multiple", file_types=["image"]) | |
| batch_btn = gr.Button("β‘ Run Batch Analysis", variant="primary", size="lg") | |
| gr.HTML("""<div class="info-box" style="margin-top:12px"> | |
| Upload any number of ultrasound images.<br> | |
| Each image is analysed independently.<br> | |
| Results shown as summary table + distribution chart.<br><br> | |
| <strong>Supported:</strong> PNG, JPG, JPEG, BMP, TIFF | |
| </div>""") | |
| with gr.Column(scale=6): | |
| gr.HTML('<p class="sec">π Batch Summary</p>') | |
| batch_result = gr.Markdown(value="*Upload images and click Run Batch Analysis.*") | |
| gr.HTML('<p class="sec" style="margin-top:6px">π Distribution Chart</p>') | |
| batch_chart = gr.Plot(label="", show_label=False) | |
| batch_btn.click(fn=predict_batch, inputs=[batch_input], | |
| outputs=[batch_result, batch_chart]) | |
| # ββ TAB 3: ABOUT ββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.TabItem("βΉοΈ About"): | |
| gr.Markdown(""" | |
| ## PCOS Ultrasound Detection β DenseNet121 | |
| ### π Why DenseNet121? | |
| 5 models were trained and compared. DenseNet121 was selected as best: | |
| | Model | Accuracy | F1 | ROC-AUC | MCC | Val AUC | Log Loss | | |
| |---|---|---|---|---|---|---| | |
| | ResNet50 | 0.9800 | 0.9873 | 0.9999 | 0.9421 | 0.9997 | 0.0623 | | |
| | EfficientNetB0 | 0.9883 | 0.9927 | 0.9993 | 0.9644 | 0.9997 | 0.0410 | | |
| | **DenseNet121** β | **0.9883** | **0.9926** | **0.9994** | **0.9648** | **0.9998** | **0.0357** | | |
| | MobileNetV2 | 0.9833 | 0.9894 | 0.9998 | 0.9513 | 0.9996 | 0.0522 | | |
| **DenseNet121 wins on MCC, Val AUC, Log Loss, and Specificity β the most clinically important metrics.** | |
| ### πΌοΈ Model Details | |
| | Component | Detail | | |
| |---|---| | |
| | Architecture | DenseNet121 (ImageNet pretrained, fine-tuned) | | |
| | Input | 224Γ224 RGB Β· ImageNet normalisation | | |
| | Classes | `not_pcos` (0) Β· `pcos` (1) | | |
| | Optimizer | Adam lr=1e-4 Β· CrossEntropyLoss | | |
| | Training | Early stopping patience=7 Β· WeightedRandomSampler | | |
| | XAI | Grad-CAM on `features.denseblock4` | | |
| ### π₯ Grad-CAM Explanation | |
| Grad-CAM highlights the ovarian regions that drive the prediction β specifically follicle patterns and ovarian texture. Red regions = highest model attention. | |
| ### β οΈ Disclaimer | |
| For **research and educational purposes only**. Not a certified medical device. | |
| Always consult a qualified healthcare professional for clinical decisions. | |
| """) | |
| demo.launch(server_name="0.0.0.0", server_port=7860) |