PCOS_Detection / app.py
DheivaCodes's picture
Update app.py
6f44c3b verified
Raw History Blame Contribute Delete
26.5 kB
import os
import io
import warnings
import numpy as np
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import gradio as gr
warnings.filterwarnings("ignore")
# ═══════════════════════════════════════════════════════════════
# CONFIG
# ═══════════════════════════════════════════════════════════════
MODELS_DIR = "models"
IMG_SIZE = 224
DEVICE = torch.device("cpu")
CLASS_NAMES = ["Not PCOS", "PCOS"] # alphabetical: not_pcos=0, pcos=1
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]),
])
# ═══════════════════════════════════════════════════════════════
# MODEL LOADING
# ═══════════════════════════════════════════════════════════════
def load_model():
candidates = [
os.path.join(MODELS_DIR, "best_model.pth"),
os.path.join(MODELS_DIR, "efficientnetb0.pth"),
os.path.join(MODELS_DIR, "EfficientNetB0.pth"),
]
pth = next((p for p in candidates if os.path.exists(p)), None)
if pth is None:
print(f"❌ No model found. models/ = {os.listdir(MODELS_DIR) if os.path.exists(MODELS_DIR) else 'missing'}")
return None
net = models.efficientnet_b0(weights=None)
net.classifier[1] = nn.Linear(net.classifier[1].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"βœ… Model loaded: {pth}")
return net
MODEL = load_model()
# ═══════════════════════════════════════════════════════════════
# CORE INFERENCE
# ═══════════════════════════════════════════════════════════════
def run_inference(img_rgb: Image.Image):
"""Returns (pcos_prob, notpcos_prob, pred_idx)."""
tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
with torch.no_grad():
probs = torch.softmax(MODEL(tensor), dim=1)[0]
pcos_p = float(probs[PCOS_IDX])
notp = float(probs[1 - PCOS_IDX])
pred = int(probs.argmax())
return pcos_p, notp, pred, tensor
# ═══════════════════════════════════════════════════════════════
# GRAD-CAM
# ═══════════════════════════════════════════════════════════════
def compute_gradcam(img_rgb: Image.Image, target_class: int) -> plt.Figure:
grads, acts = [], []
def fwd_hook(m, inp, out):
acts.append(out.detach())
out.register_hook(lambda g: grads.append(g.detach()))
handle = MODEL.features[-1].register_forward_hook(fwd_hook)
tensor = VAL_TRANSFORM(img_rgb).unsqueeze(0).to(DEVICE)
MODEL.zero_grad()
MODEL(tensor)[0, target_class].backward()
handle.remove()
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.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})
panels = [
(orig_r, None, "Original Image"),
(cam_up, "jet", "Grad-CAM Heatmap"),
(overlay, None, "Activation Overlay"),
]
for ax, (img, cmap, title) in zip(axes, panels):
ax.set_facecolor("#0f172a")
ax.imshow(img, cmap=cmap)
ax.set_title(title, color="white", fontsize=11,
fontweight="bold", pad=6)
ax.axis("off")
for sp in ax.spines.values():
sp.set_linewidth(0)
fig.text(0.5, -0.02,
f"Grad-CAM Β· EfficientNetB0 Β· Predicted: {CLASS_NAMES[target_class]}",
ha="center", color="#94a3b8", fontsize=10)
plt.tight_layout(pad=0.4)
return fig
# ═══════════════════════════════════════════════════════════════
# PROBABILITY GAUGE CHART
# ═══════════════════════════════════════════════════════════════
def make_gauge(pcos_prob: float) -> plt.Figure:
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")
# Background bar
ax.barh([0.5], [1.0], height=0.32, color="#1e293b",
left=0, align="center", zorder=1)
# Colored fill
color = "#22c55e" if pcos_prob < 0.33 else "#f59e0b" if pcos_prob < 0.66 else "#ef4444"
ax.barh([0.5], [pcos_prob], height=0.32, color=color,
left=0, align="center", zorder=2)
# Threshold line
ax.axvline(0.5, color="white", lw=1.5, ls="--", alpha=0.7, zorder=3)
# Percentage label
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")
# Zone labels
ax.text(0.16, 0.12, "Low", color="#22c55e", fontsize=8, ha="center", alpha=0.8)
ax.text(0.50, 0.12, "Moderate", color="#f59e0b", fontsize=8, ha="center", alpha=0.8)
ax.text(0.83, 0.12, "High", color="#ef4444", 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
# ═══════════════════════════════════════════════════════════════
# SINGLE IMAGE PREDICTION
# ═══════════════════════════════════════════════════════════════
def predict_single(image):
if MODEL is None:
return "❌ Model not loaded β€” upload `best_model.pth` to `models/`.", 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}** |
*EfficientNetB0 Β· 224Γ—224 Β· ImageNet normalisation*
> ⚠️ Research use only β€” not a clinical tool."""
gauge = make_gauge(pcos_p)
gradcam_fig = compute_gradcam(img_rgb, pred)
return result, gauge, gradcam_fig
except Exception as e:
import traceback
return f"❌ Error: {e}\n```\n{traceback.format_exc()}\n```", None, None
# ═══════════════════════════════════════════════════════════════
# BATCH PREDICTION
# ═══════════════════════════════════════════════════════════════
def predict_batch(files):
if MODEL is None:
return "❌ Model not loaded.", None
if not files:
return "⚠️ Please 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)
label = CLASS_NAMES[pred]
risk = "Low" if pcos_p < 0.33 else "Moderate" if pcos_p < 0.66 else "High"
icon = "πŸ”΄" if pred == PCOS_IDX else "🟒"
fname = os.path.basename(f.name)
rows.append({
"File" : fname,
"Prediction" : f"{icon} {label}",
"PCOS Prob (%)" : f"{pcos_p*100:.1f}",
"Not PCOS Prob (%)": f"{notp*100:.1f}",
"Risk" : risk,
})
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"❌ Error: {e}",
"PCOS Prob (%)" : "β€”",
"Not PCOS Prob (%)": "β€”",
"Risk" : "β€”",
})
total = len(rows)
# ── Summary markdown ─────────────────────────────────────────
summary = f"""### πŸ“Š Batch Summary β€” {total} image{'s' if total > 1 else ''}
| | Count | Percentage |
|---|---|---|
| πŸ”΄ PCOS Detected | **{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 |
|---|---|---|---|---|
""" + "\n".join(
f"| `{r['File']}` | {r['Prediction']} | {r['PCOS Prob (%)']}% | {r['Not PCOS Prob (%)']}% | {r['Risk']} |"
for r in rows
) + "\n\n> ⚠️ Research use only β€” not a clinical tool."
# ── Summary pie chart ─────────────────────────────────────────
summary_fig = make_batch_chart(pcos_c, notp_c, total)
return summary, summary_fig
def make_batch_chart(pcos_c: int, notp_c: int, total: int) -> plt.Figure:
fig = plt.figure(figsize=(10, 4), facecolor="#0f172a")
# ── Pie ──────────────────────────────────────────────────────
ax1 = fig.add_subplot(1, 2, 1)
ax1.set_facecolor("#0f172a")
if total > 0:
sizes = [pcos_c, notp_c]
labels = [f"PCOS\n{pcos_c}", f"Not PCOS\n{notp_c}"]
colors = ["#ef4444", "#22c55e"]
wedges, texts, autotexts = ax1.pie(
sizes, labels=labels, colors=colors,
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)
# ── Bar β€” counts ──────────────────────────────────────────────
ax2 = fig.add_subplot(1, 2, 2)
ax2.set_facecolor("#0f172a")
cats = ["Not PCOS", "PCOS"]
counts = [notp_c, pcos_c]
colors = ["#22c55e", "#ef4444"]
bars = ax2.bar(cats, counts, color=colors, width=0.45,
edgecolor="#0f172a", linewidth=2)
ax2.set_ylim(0, max(counts) * 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, counts):
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 ''} Β· EfficientNetB0",
ha="center", color="#64748b", fontsize=9)
plt.tight_layout(pad=1.5)
return fig
# ═══════════════════════════════════════════════════════════════
# CSS
# ═══════════════════════════════════════════════════════════════
CSS = """
/* ── Global ── */
body, .gradio-container {
background: #0f172a !important;
font-family: 'Inter', 'Segoe UI', sans-serif !important;
}
/* ── Header banner ── */
.app-header {
background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #1e1b4b 100%);
border: 1px solid #4338ca;
border-radius: 16px;
padding: 28px 36px;
margin-bottom: 20px;
text-align: center;
}
.app-header h1 {
color: #e0e7ff !important;
font-size: 2rem !important;
font-weight: 700 !important;
margin: 0 0 6px 0 !important;
letter-spacing: -0.5px;
}
.app-header p {
color: #a5b4fc !important;
font-size: 0.95rem !important;
margin: 0 !important;
}
/* ── Disclaimer ── */
.disclaimer {
background: #1c1917;
border-left: 4px solid #f59e0b;
border-radius: 8px;
padding: 10px 16px;
color: #fbbf24 !important;
font-size: 0.85rem;
margin-bottom: 16px;
}
/* ── Cards ── */
.card {
background: #1e293b;
border: 1px solid #334155;
border-radius: 14px;
padding: 20px;
}
/* ── Section headings ── */
.section-title {
color: #c7d2fe !important;
font-size: 0.8rem !important;
font-weight: 600 !important;
letter-spacing: 1.2px !important;
text-transform: uppercase !important;
margin: 0 0 12px 0 !important;
padding-bottom: 8px !important;
border-bottom: 1px solid #334155 !important;
}
/* ── Stat pills ── */
.stat-row {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin: 10px 0;
}
.stat-pill {
background: #0f172a;
border: 1px solid #475569;
border-radius: 8px;
padding: 8px 14px;
font-size: 0.85rem;
color: #e2e8f0;
min-width: 120px;
}
.stat-pill strong { color: #818cf8; display: block; font-size: 1.1rem; }
/* ── Tab nav ── */
.tab-nav button {
color: #94a3b8 !important;
font-size: 0.9rem !important;
font-weight: 600 !important;
border-radius: 8px 8px 0 0 !important;
padding: 10px 20px !important;
}
.tab-nav button.selected {
color: #818cf8 !important;
border-bottom: 2px solid #818cf8 !important;
background: #1e293b !important;
}
/* ── Buttons ── */
button.primary {
background: linear-gradient(135deg, #4f46e5, #7c3aed) !important;
border: none !important;
border-radius: 10px !important;
font-weight: 700 !important;
font-size: 1rem !important;
color: white !important;
letter-spacing: 0.3px;
padding: 12px 0 !important;
transition: opacity 0.2s;
}
button.primary:hover { opacity: 0.88 !important; }
/* ── Input panels ── */
.input-panel {
background: #1e293b;
border: 1px solid #334155;
border-radius: 14px;
padding: 16px;
}
/* ── Result panel ── */
.result-panel {
background: #1e293b;
border: 1px solid #334155;
border-radius: 14px;
padding: 16px;
min-height: 200px;
}
/* ── Markdown tables ── */
table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
th {
background: #1e3a5f;
color: #93c5fd;
padding: 8px 12px;
text-align: left;
font-weight: 600;
}
td { padding: 8px 12px; border-bottom: 1px solid #1e293b; color: #e2e8f0; }
tr:nth-child(even) td { background: #1a2540; }
/* ── Plots ── */
.gradio-plot { border-radius: 12px !important; overflow: hidden; }
/* ── File upload ── */
.upload-zone {
border: 2px dashed #4338ca !important;
border-radius: 14px !important;
background: #1e293b !important;
}
/* ── Info box ── */
.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; }
"""
# ═══════════════════════════════════════════════════════════════
# GRADIO UI
# ═══════════════════════════════════════════════════════════════
with gr.Blocks(css=CSS, title="PCOS Ultrasound Detection") as demo:
# ── Header ──────────────────────────────────────────────────
gr.HTML("""
<div class="app-header">
<h1>🩺 PCOS Ultrasound Detection</h1>
<p>EfficientNetB0 &nbsp;Β·&nbsp; Fine-tuned on ovarian ultrasound dataset &nbsp;Β·&nbsp; Grad-CAM XAI</p>
</div>
<div class="disclaimer">
⚠️ <strong>Medical Disclaimer:</strong> This tool is intended for
<strong>research and educational purposes only</strong>. It is not a certified
medical device and must not be used as a substitute for professional clinical diagnosis.
</div>
""")
with gr.Tabs(elem_classes="tab-nav"):
# ══════════════════════════════════════════════════════════
# TAB 1 β€” SINGLE IMAGE
# ══════════════════════════════════════════════════════════
with gr.TabItem("πŸ”¬ Single Image Analysis"):
with gr.Row(equal_height=False):
# ── Upload column ──────────────────────────────────
with gr.Column(scale=4):
gr.HTML('<p class="section-title">πŸ“ Upload Image</p>')
img_input = gr.Image(
label="",
type="pil",
height=290,
elem_classes="upload-zone",
)
analyze_btn = gr.Button(
"πŸ” Analyze Image",
variant="primary",
size="lg",
elem_classes="primary",
)
gr.HTML("""
<div class="info-box" style="margin-top:14px">
<strong>How to use</strong><br>
1. Upload a clear ovarian ultrasound (PNG / JPG)<br>
2. Click <strong>Analyze Image</strong><br>
3. Review the diagnosis, probability gauge, and Grad-CAM heatmap<br><br>
<strong>Model info</strong><br>
Architecture: EfficientNetB0 &nbsp;|&nbsp; Input: 224Γ—224 RGB<br>
Classes: <code>not_pcos</code> (0) &nbsp;Β·&nbsp; <code>pcos</code> (1)
</div>
""")
# ── Result column ──────────────────────────────────
with gr.Column(scale=6):
gr.HTML('<p class="section-title">πŸ“‹ Diagnosis Result</p>')
result_md = gr.Markdown(
value="*Upload an image and click **Analyze Image** to see the result.*",
)
gr.HTML('<p class="section-title" style="margin-top:16px">πŸ“Š PCOS Probability Gauge</p>')
gauge_plot = gr.Plot(label="", show_label=False)
# ── Grad-CAM ─────────────────────────────────────────────
gr.HTML('<p class="section-title" style="margin-top:8px">πŸ”₯ Grad-CAM Explainability</p>')
gradcam_plot = gr.Plot(label="", show_label=False)
analyze_btn.click(
fn=predict_single,
inputs=[img_input],
outputs=[result_md, gauge_plot, gradcam_plot],
)
# ══════════════════════════════════════════════════════════
# TAB 2 β€” BATCH
# ══════════════════════════════════════════════════════════
with gr.TabItem("πŸ“‚ Batch Analysis"):
with gr.Row():
with gr.Column(scale=4):
gr.HTML('<p class="section-title">πŸ“ Upload Multiple Images</p>')
batch_input = gr.File(
label="",
file_count="multiple",
file_types=["image"],
elem_classes="upload-zone",
)
batch_btn = gr.Button(
"⚑ Run Batch Analysis",
variant="primary",
size="lg",
elem_classes="primary",
)
gr.HTML("""
<div class="info-box" style="margin-top:14px">
<strong>Batch mode</strong><br>
Upload multiple ultrasound images at once.<br>
Each image is analysed independently and results
are shown in a summary table with per-image
PCOS probability and risk tier.<br><br>
<strong>Supported formats:</strong> PNG, JPG, JPEG, BMP, TIFF
</div>
""")
with gr.Column(scale=6):
gr.HTML('<p class="section-title">πŸ“Š Batch Summary &amp; Per-Image Results</p>')
batch_result_md = gr.Markdown(
value="*Upload images and click **Run Batch Analysis**.*"
)
gr.HTML('<p class="section-title" style="margin-top:8px">πŸ“ˆ Distribution Chart</p>')
batch_chart = gr.Plot(label="", show_label=False)
batch_btn.click(
fn=predict_batch,
inputs=[batch_input],
outputs=[batch_result_md, batch_chart],
)
# ══════════════════════════════════════════════════════════
# TAB 3 β€” ABOUT
# ══════════════════════════════════════════════════════════
with gr.TabItem("ℹ️ About"):
gr.Markdown("""
## About This Application
### 🧠 Model Architecture
| Parameter | Detail |
|---|---|
| Architecture | EfficientNetB0 (ImageNet pretrained, fine-tuned) |
| Input size | 224 Γ— 224 RGB |
| Normalisation | Mean [0.485, 0.456, 0.406] Β· Std [0.229, 0.224, 0.225] |
| Output classes | `not_pcos` (0), `pcos` (1) β€” alphabetical order |
| Decision threshold | 0.50 (softmax argmax) |
| Checkpoint key | `model_state` |
| Saved criterion | Best validation AUC |
### πŸ‹οΈ Training Details
| Setting | Value |
|---|---|
| Optimiser | Adam (lr=1e-4, weight_decay=1e-5) |
| Loss | CrossEntropyLoss with class weights (balanced) |
| Sampler | WeightedRandomSampler for batch balance |
| Scheduler | ReduceLROnPlateau (factor=0.3, patience=3) |
| Early stopping | Patience = 7 epochs |
| Max epochs | 30 |
| Batch size | 32 |
| Augmentation | RandomHorizontalFlip, RandomRotation(15Β°), ColorJitter |
### πŸ”₯ Grad-CAM Explainability
Gradient-weighted Class Activation Mapping (Grad-CAM) highlights image
regions that most influenced the model's decision.
- **Target layer:** `features[-1]` (last convolutional block)
- **Target class:** Predicted class
- Heatmap is upsampled to 224Γ—224 and overlaid on the original image
### ⚠️ Disclaimer
This application is for **research and educational purposes only**.
It is not certified for clinical use and must not replace the judgement
of a qualified medical professional.
""")
demo.launch(server_name="0.0.0.0", server_port=7860)