# 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("""