BreastCancer / app.py
LOP3Zs's picture
Optimize ZeroGPU duration to 20s to conserve free tier quota
42e0ba8 verified
Raw History Blame Contribute Delete
17.1 kB
# On Hugging Face ZeroGPU Spaces, spaces MUST be imported prior to torch/CUDA initialization.
try:
import spaces
gpu_decorator = spaces.GPU
except (ImportError, Exception):
def gpu_decorator(*args, **kwargs):
def wrapper(f):
return f
if len(args) == 1 and callable(args[0]):
return args[0]
return wrapper
import os
import sys
from pathlib import Path
from typing import Optional, Dict, Any, Tuple
import gradio as gr
import numpy as np
import torch
from PIL import Image
from model_architectures import build_model
from wsi_loader import load_image_or_slide_from_path
from inference import PhikonFeatureExtractor, ModelManager
from heatmap import (
render_wide_overview_heatmap,
render_wide_hotspot_roi,
render_figure_5_publication
)
@gpu_decorator(duration=20)
def predict_risk_and_heatmap(
image_file: Optional[str],
svs_file: Optional[str],
cohort: str,
target: str,
model_name: str,
fold: str,
colormap: str,
alpha_max: float,
tile_size: int,
progress=gr.Progress(track_tqdm=True)
) -> Tuple[Dict[str, float], str, Optional[Image.Image], Optional[Image.Image], Optional[Image.Image], Optional[Image.Image], Dict[str, Any]]:
"""
End-to-End Histopathology Risk & Attention Pipeline:
1. Input resolution (PNG/JPG/TIFF or SVS)
2. Dense tissue tile extraction covering the specimen without gaps
3. Foundation feature extraction via owkin/phikon-v2 [N, 1024]
4. Weakly-supervised MIL inference (5-Fold ensemble or single fold)
5. High-resolution attention map overlay & wide-context hotspot ROI (for supported models)
6. For TransMIL: Computes risk stratification and outputs explicit notice regarding CLS readout.
"""
target_path = None
if svs_file is not None:
target_path = svs_file if isinstance(svs_file, str) else getattr(svs_file, "name", str(svs_file))
elif image_file is not None:
target_path = image_file if isinstance(image_file, str) else getattr(image_file, "name", str(image_file))
if not target_path or not os.path.exists(target_path):
raise gr.Error("Please upload a histopathology image (PNG, JPG, TIFF), an SVS whole slide, or select a reference example below.")
progress(0.10, desc="Extracting histopathological tiles and filtering acellular background...")
try:
canvas_img, tiles, coords, meta = load_image_or_slide_from_path(
file_path=target_path,
tile_size=int(tile_size),
)
except Exception as exc:
raise gr.Error(f"Error loading histology input: {str(exc)}")
if not tiles:
raise gr.Error("No valid tissue area detected. Please verify that the image contains stained tissue content.")
progress(0.35, desc=f"Extracting Phikon-v2 representations for {len(tiles)} tissue tiles...")
try:
extractor = PhikonFeatureExtractor.get_instance()
features = extractor.extract_features(tiles, batch_size=16)
except Exception as exc:
raise gr.Error(f"Phikon-v2 feature extraction error: {str(exc)}")
progress(0.70, desc=f"Executing {model_name} risk model inference ({fold})...")
try:
model_mgr = ModelManager.get_instance()
prob_high, attention_scores = model_mgr.run_inference(
features=features,
cohort=cohort,
target=target,
model_type=model_name,
fold_selection=fold
)
except Exception as exc:
raise gr.Error(f"MIL inference error: {str(exc)}")
prob_low = 1.0 - prob_high
pred_str = "High Risk" if prob_high >= 0.5 else "Low Risk"
prob_disp = f"{pred_str} ({(prob_high * 100):.1f}%)"
label_output = {
"High Risk": round(float(prob_high), 4),
"Low Risk": round(float(prob_low), 4)
}
# Handle models without tile-level attention map (e.g. TransMIL)
if attention_scores is None or model_name.upper() == "TRANSMIL":
status_notice = (
"### Attention Map Notice\n\n"
f"**Attention heatmap overlay is not supported for {model_name}.**\n\n"
"TransMIL utilizes Nyström self-attention with sequence-level `[CLS]` token readout "
"(adapted from Chen et al., NeurIPS 2021). The final classification is pooled through the global `[CLS]` token, "
"which does not produce direct 1D tile-wise spatial attention weights. "
"Slide-level risk classification and lineage signature scores are accurately reported above."
)
metrics = {
"Predicted Risk Category": pred_str,
"High Risk Probability": f"{(prob_high * 100):.2f}%",
"Low Risk Probability": f"{(prob_low * 100):.2f}%",
"Decision Threshold": 0.50,
"Molecular Subtype": cohort,
"Target Risk Signature": target,
"Model Architecture": f"{model_name} ({fold})",
"Attention Heatmap": "Not supported (Nyström [CLS] token readout)",
"Analyzed Tissue Tiles": meta["tiles_processed"],
"Canvas Dimensions": f"{canvas_img.width} x {canvas_img.height}",
"Input Type": meta["source_type"]
}
return label_output, status_notice, None, None, canvas_img, None, metrics
# For models with attention weights (ABMIL, CLAM-SB, DSMIL, MambaMIL)
progress(0.88, desc="Rendering wide attention heatmap overlay and predictive hotspot...")
status_notice = (
"### Attention Analysis Status\n\n"
f"**Attention heatmap active for {model_name} ({fold}).**\n\n"
"Tile importance scores are normalized using slide-level min-max scaling ($s \\in [0, 1]$) "
"matching the methodology in `figure.ipynb`. Full spatial attention is rendered continuously "
"across all specimen tissue without obstructing annotations. A wide contextual inset of the "
"peak predictive hotspot is available in the adjacent tab."
)
actual_tile_span = meta.get("tile_span", meta.get("tile_size", tile_size))
try:
overview_heatmap, roi_box, s_min, s_max = render_wide_overview_heatmap(
canvas_image=canvas_img,
coords=coords,
raw_scores=attention_scores,
colormap_name=colormap,
alpha=float(alpha_max),
tile_size=int(actual_tile_span)
)
hotspot_roi = render_wide_hotspot_roi(
canvas_image=canvas_img,
coords=coords,
raw_scores=attention_scores,
roi_box=roi_box,
colormap_name=colormap,
alpha=float(alpha_max),
tile_size=int(actual_tile_span)
)
fig_meta = {
"cohort": cohort,
"target": target,
"model": f"{model_name} ({fold})",
"prob_str": prob_disp
}
publication_fig5 = render_figure_5_publication(
canvas_image=canvas_img,
coords=coords,
raw_scores=attention_scores,
metadata=fig_meta,
colormap_name=colormap,
alpha=float(alpha_max),
tile_size=int(tile_size)
)
except Exception as exc:
raise gr.Error(f"Visualization rendering error: {str(exc)}")
metrics = {
"Predicted Risk Category": pred_str,
"High Risk Probability": f"{(prob_high * 100):.2f}%",
"Low Risk Probability": f"{(prob_low * 100):.2f}%",
"Decision Threshold": 0.50,
"Molecular Subtype": cohort,
"Target Risk Signature": target,
"Model Architecture": f"{model_name} ({fold})",
"Attention Heatmap": "Supported & Rendered (Slide-level min-max)",
"Raw Attention Range": f"[{s_min:.6e}, {s_max:.6e}]",
"Analyzed Tissue Tiles": meta["tiles_processed"],
"Canvas Dimensions": f"{canvas_img.width} x {canvas_img.height}",
"Input Type": meta["source_type"]
}
return label_output, status_notice, overview_heatmap, hotspot_roi, canvas_img, publication_fig5, metrics
# Publication-grade CSS styling (clean typography, no icons/emojis, academic theme)
custom_css = """
.gradio-container {
max-width: 1500px !important;
margin: auto !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
color: #1a1a1a;
}
.main-title {
font-size: 1.85rem;
font-weight: 700;
letter-spacing: -0.02em;
color: #0f172a;
margin-bottom: 0.25rem;
border-bottom: 2px solid #0f172a;
padding-bottom: 0.6rem;
}
.sub-title {
font-size: 0.95rem;
color: #475569;
margin-bottom: 1.25rem;
line-height: 1.5;
}
.section-header {
font-size: 1.05rem;
font-weight: 600;
color: #1e293b;
margin-top: 0.5rem;
margin-bottom: 0.5rem;
border-bottom: 1px solid #e2e8f0;
padding-bottom: 0.35rem;
}
"""
with gr.Blocks(title="Deep-MIL Histopathology Risk & Attention Assessment", css=custom_css) as demo:
gr.HTML("""
<div class="main-title">Weakly-Supervised Multiple Instance Learning for Breast Cancer Risk Stratification</div>
<div class="sub-title">
Clinical and translational research framework evaluating five specialized Multiple Instance Learning architectures
(ABMIL, CLAM-SB, DSMIL, TransMIL, MambaMIL) on foundation ViT embeddings (Phikon-v2) across molecular PAM50 subtypes and risk lineage targets.
</div>
""")
with gr.Row():
# Left Column: Configuration & Inputs
with gr.Column(scale=5):
gr.HTML('<div class="section-header">1. Histopathology Input</div>')
with gr.Tabs():
with gr.TabItem("Standard Histology Image"):
image_input = gr.Image(
type="filepath",
label="Upload Histopathology Image (PNG, JPG, TIFF)",
sources=["upload", "clipboard"]
)
with gr.TabItem("Whole Slide Image (.svs)"):
svs_input = gr.File(
label="Upload WSI Slide (.svs, max 200 MB)",
file_types=[".svs", ".ndpi", ".tiff"]
)
gr.HTML('<div class="section-header">2. Model & Molecular Configuration</div>')
with gr.Row():
cohort_input = gr.Dropdown(
choices=["LumA", "LumB", "HER2", "Basal"],
value="LumA",
label="PAM50 Molecular Subtype",
info="Target patient cohort"
)
target_input = gr.Dropdown(
choices=["Stromal", "Immune", "Epithelial", "Vascular"],
value="Stromal",
label="Lineage Risk Signature",
info="Gene expression prognostic target"
)
with gr.Row():
model_input = gr.Dropdown(
choices=["ABMIL", "CLAM-SB", "DSMIL", "TransMIL", "MambaMIL"],
value="ABMIL",
label="MIL Architecture",
info="All 5 architectures from study"
)
fold_input = gr.Dropdown(
choices=[
"5-Fold Ensemble (Recommended)",
"Fold 1", "Fold 2", "Fold 3", "Fold 4", "Fold 5"
],
value="5-Fold Ensemble (Recommended)",
label="Cross-Validation Selection",
info="Patient-disjoint cross validation"
)
with gr.Accordion("Visualization Settings (Optional)", open=False):
with gr.Row():
colormap_input = gr.Dropdown(
choices=["YlOrRd", "plasma", "magma", "viridis"],
value="YlOrRd",
label="Colormap",
info="YlOrRd: Publication benchmark"
)
alpha_input = gr.Slider(
minimum=0.2, maximum=0.9, value=0.65, step=0.05,
label="Heatmap Overlay Opacity"
)
tile_size_input = gr.Slider(
minimum=112, maximum=448, value=224, step=56,
label="Tile Dimension (pixels)",
info="Standard: 224 pixels"
)
submit_btn = gr.Button("Compute Risk Stratification & Attention Analysis", variant="primary", size="lg")
# Right Column: Analytical Results & Visualizations
with gr.Column(scale=7):
gr.HTML('<div class="section-header">3. Risk Classification Output</div>')
label_output = gr.Label(
num_top_classes=2,
label="Predicted Risk Category & Calibrated Probability"
)
status_notice = gr.Markdown(
value="*Submit an image or select a benchmark reference example below to initiate inference.*"
)
gr.HTML('<div class="section-header">4. Spatial Attention Heatmap & Hotspot Insets</div>')
with gr.Tabs():
with gr.TabItem("Slide Attention Heatmap Overlay"):
heatmap_output = gr.Image(
label="Slide Attention Heatmap Overlay (Continuous Publication Standard)",
type="pil",
height=680
)
gr.Markdown(
"*Continuous attention heatmap covering the specimen tissue (slide-level min-max normalization).*"
)
with gr.TabItem("Predictive Hotspot ROI (Wide Context)"):
roi_output = gr.Image(
label="Highest-Attention Region of Interest (Wide-Context High-Resolution Inset)",
type="pil",
height=680
)
gr.Markdown(
"*Wide contextual ROI surrounding the peak attention tile, showing histological morphology "
"and fine spatial attention gradient.*"
)
with gr.TabItem("Original H&E Reference"):
he_output = gr.Image(
label="Unaltered Stained Histology Reference",
type="pil",
height=600
)
with gr.TabItem("Publication Multi-Panel Layout (Figure 5)"):
figure_5_output = gr.Image(
label="Publication 4-Panel Layout (Figure 5 Benchmark Export)",
type="pil",
height=680
)
gr.Markdown(
"*Full 4-panel multi-scale figure reproducing Figure 5 from the study.*"
)
metrics_output = gr.JSON(label="Quantitative Summary & Execution Parameters")
# Benchmark Curated Reference Examples
sample_dir = Path(__file__).parent / "sample_images"
sample_1 = str(sample_dir / "sample_roi_luma.png") if (sample_dir / "sample_roi_luma.png").exists() else None
sample_2 = str(sample_dir / "sample_roi_luma_high.png") if (sample_dir / "sample_roi_luma_high.png").exists() else None
sample_3 = str(sample_dir / "sample_roi_lumab6.png") if (sample_dir / "sample_roi_lumab6.png").exists() else None
examples_list = []
if sample_1:
examples_list.append([sample_1, None, "LumA", "Stromal", "ABMIL", "5-Fold Ensemble (Recommended)", "YlOrRd", 0.65, 224])
if sample_2:
examples_list.append([sample_2, None, "LumA", "Stromal", "CLAM-SB", "5-Fold Ensemble (Recommended)", "YlOrRd", 0.65, 224])
if sample_3:
examples_list.append([sample_3, None, "LumA", "Stromal", "TransMIL", "5-Fold Ensemble (Recommended)", "YlOrRd", 0.65, 224])
if examples_list:
gr.HTML('<div class="section-header" style="margin-top: 1.5rem;">Curated Reference Benchmark Cases</div>')
gr.Examples(
examples=examples_list,
inputs=[
image_input, svs_input, cohort_input, target_input,
model_input, fold_input, colormap_input, alpha_input, tile_size_input
],
outputs=[label_output, status_notice, heatmap_output, roi_output, he_output, figure_5_output, metrics_output],
fn=predict_risk_and_heatmap,
cache_examples=False
)
submit_btn.click(
fn=predict_risk_and_heatmap,
inputs=[
image_input, svs_input, cohort_input, target_input,
model_input, fold_input, colormap_input, alpha_input, tile_size_input
],
outputs=[label_output, status_notice, heatmap_output, roi_output, he_output, figure_5_output, metrics_output]
)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=int(os.environ.get("PORT", 7860)),
theme=gr.themes.Soft(),
css=custom_css
)