deploy: 957ce94 Merge pull request #38 from pathology-data-mining/fix/fetch-progress-flood
Browse filesFiles changed (5)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""My Results details and ZIP through the real Gradio app (local user mode)."""
import uuid
import pandas as pdimport pytestfrom gradio_client import Clientfrom PIL import Image
from mosaic.ui.user_tabs import LOCAL_DEBUG_USERNAMEfrom mosaic.user_results import delete_analysis_results, save_analysis_results
@pytest.fixturedef saved_result(): analysis_id = f"{uuid.uuid4()}_0" save_analysis_results( username=LOCAL_DEBUG_USERNAME, analysis_id=analysis_id, slide_id="", slide_name="TCGA-XX-0000-01Z-00-DX1.svs", settings={ "seg_config": "TCGA", "site_type": "Primary", "sex": "Female", "tissue_site": "Lung", "cancer_subtype": "LUAD", # provided -> Aeon not run "paladin_weights": "ats", }, # what the pipeline saves when Aeon is skipped: the given subtype at 1.0 aeon_results=pd.DataFrame({"Confidence": [1.0]}, index=pd.Index(["LUAD"])), paladin_results=pd.DataFrame( { "Cancer Subtype": ["LUAD"], "Biomarker": ["EGFR"], "Prob. Present": [0.0083971275016665], "Weights": ["Pan-cancer (ATS)"], } ), slide_mask=Image.new("RGB", (32, 32)), ) yield analysis_id delete_analysis_results(LOCAL_DEBUG_USERNAME, analysis_id)
def test_details_and_zip(gradio_server, saved_result): client = Client(gradio_server["url"], verbose=False) out = client.predict(saved_result, "", api_name="/view_result_details") # the Accordion is a layout block, not an API output metadata_md, _mask, aeon, paladin, _status = out[-5:] text = metadata_md if isinstance(metadata_md, str) else str(metadata_md) assert "provided; Aeon not run" in text assert "Pan-cancer (ATS)" in text and "paladin_weights**: ats" not in text # the made-up "prediction" at confidence 1 is not shown assert not (isinstance(aeon, dict) and aeon.get("visible") and aeon.get("value")) value = paladin.get("value", paladin) if isinstance(paladin, dict) else paladin probs = [row[2] for row in value["data"]] assert probs == [0.008]
zip_file, status = client.predict(saved_result, "", api_name="/download_result_zip") status_text = status.get("value", status) if isinstance(status, dict) else status assert "click the file below" in str(status_text) assert zip_file51 unmodified lines52535455565758591372 unmodified lines14321433143414331435143614371438143914401 unmodified line144214431444144214431444144514461447144814491445144614471448144914501451145214531454145514561457145814591460146151 unmodified lines# Set via MOSAIC_GDC_DOWNLOAD_TIMEOUT env var for very large filesAPI_TIMEOUT = 30DOWNLOAD_TIMEOUT = int(os.environ.get("MOSAIC_GDC_DOWNLOAD_TIMEOUT", "300"))DOWNLOAD_CHUNK_BYTES = 1024 * 1024PROGRESS_INTERVAL_SEC = 0.5
# Cache for OncoTree ancestor lookups to avoid repeated API calls_oncotree_ancestors_cache: dict[str, list[str]] = {}1372 unmodified lines file_size = int(response.headers.get("content-length", 0))
bytes_downloaded = 0 chunk_size = 8192 # 8KB chunks chunk_size = DOWNLOAD_CHUNK_BYTES part_path = slide_dir / f".{filename}.part" last_report = 0.0
try: with open(part_path, "wb") as f:1 unmodified line if chunk: f.write(chunk) bytes_downloaded += len(chunk) if progress_callback: if file_size: # Report progress with percentage progress_callback(bytes_downloaded, file_size) else: # Report bytes downloaded without total (file_size unknown) # Some progress callbacks can handle this gracefully progress_callback(bytes_downloaded, bytes_downloaded) # Report at most a few times a second: one update per # chunk (tens of thousands per slide) flooded the web UI's # event stream, so through the HF proxy the page never # received the fetch result. now = time.monotonic() done = bool(file_size) and bytes_downloaded >= file_size if progress_callback and ( done or now - last_report >= PROGRESS_INTERVAL_SEC ): last_report = now # Without a known total, report bytes as both values. progress_callback( bytes_downloaded, file_size or bytes_downloaded )
if file_size and bytes_downloaded != file_size: raise GDCNetworkError(195 unmodified lines1961971981991992002012026 unmodified lines20921021121221221321421511 unmodified lines22722822923023023123223323323423523613 unmodified lines25025125225325325425525617 unmodified lines274275276277278279280281282283284285286131 unmodified lines418419420414415416421422423424425426427385 unmodified lines813814815816817818819820810821822823824825826195 unmodified lines**Single Slide Analysis:**1. Upload an H&E whole slide image (.svs, .tiff, or .tif)2. Configure settings: - **Sex**: Required - Patient biological sex (affects analysis) - **Sex**: Patient biological sex; required when Cancer Subtype is "Unknown" (Aeon uses it) - **Site Type**: Primary tumor or metastatic site - **Tissue Site**: Anatomical location (if known) - **Cancer Subtype**: Leave as "Unknown" for automatic inference6 unmodified lines**Fetch from TCGA:**1. Select "Fetch from TCGA" input mode2. Enter a TCGA slide ID (UUID or barcode like TCGA-A1-A0SB-01Z-00-DX1)3. Click "Fetch Slide" - metadata will auto-fill the dropdowns3. Click "Fetch Slide" (clicking an example fetches it directly) - metadata will auto-fill the dropdowns4. Review/adjust settings, then click "Analyze"
**Batch Processing:**11 unmodified lines**File Requirements:**- H&E stained whole slide images- Standard microscopy scanning resolution- Compatible with OpenSlide library- Pyramidal SVS/TIFF readable by the slide reader (unreadable files are rejected on upload)
**Configuration Fields:**- **Sex** (Required): Male/Female - Used for sex-specific cancer analysis- **Sex**: Male/Female - required when Cancer Subtype is "Unknown" (used by Aeon)- **Site Type**: Primary vs Metastatic - Affects biomarker interpretation- **Tissue Site**: 60+ anatomical sites supported (see dropdown)- **Cancer Subtype**: Use "Unknown" for automatic inference via Aeon model13 unmodified lines**Biomarker Predictions:**- Uses **Paladin model** for biomarker inference- Each cancer subtype has its own panel of biomarkers- Scores indicate predicted expression/mutation status- **Prob. Present** (0-1) is the predicted probability that the alteration is present- **Paladin Biomarker Weights** chooses which models predict that panel: - **Pan-cancer (ATS)** (default): one model per biomarker, trained jointly across 41 cancer types - **Subtype-specific**: the original models, one per cancer subtype and biomarker17 unmodified lines- Models: CTransPath, Optimus, Aeon (subtype), Paladin (biomarker)- Background model loading may occur on first use
**Sharing the GPU (public Space):**- Analyses run one at a time on the GPU; if others are ahead you'll see your place in the queue and an estimated wait- Cached results (e.g. the example TCGA slides) return immediately without waiting- **Cancel** stops your analysis; closing the tab does too- Limits: up to 10 slides per run, 90 min of GPU time per run, 45 min per sample, one GPU analysis per user at a time- Larger batches: use the Mosaic command line or Docker image
---
## CSV Batch Upload Format131 unmodified lines## Troubleshooting
**Common Issues:**- **"Sex is required"**: Select Male or Female before analyzing- **Slow processing**: Large slides take longer; be patient- **Upload failed**: Check file format (.svs, .tiff, .tif only)- **"Sex is required"**: Select Male or Female, or set the Cancer Subtype if known- **Slow processing**: Large slides take longer; if others are ahead of you, the progress bar shows your place in the queue- **Upload failed**: Check file format (.svs, .tiff, .tif only) and that the file is a readable whole-slide image- **"The settings don't match the uploaded slides"**: the Slide column of a settings CSV must name each uploaded file- **No results**: Ensure slide contains sufficient tissue """ )385 unmodified lines )
# Create dropdown choices: display name → slide_id # Newest first, with the upload time: the same file name is # often uploaded more than once. slides = sorted(slides, key=lambda sl: sl.upload_time, reverse=True) choices = [ ( f"{slide.original_filename} ({slide.size_bytes / (1024**2):.1f} MB)", f"{slide.original_filename} · " f"{slide.upload_time[:16].replace('T', ' ')} · " f"{slide.size_bytes / (1024**2):.1f} MB", slide.slide_id, ) for slide in slides380 unmodified lines3813823833843853863873883893903913923933873943953963973983991 unmodified line40140240339539639739839940040440540699 unmodified lines5065075085095105065075085095105115125135145155165175185195205215225235245255265275285295305319 unmodified lines54154254353053154454554654754854955055155255351 unmodified lines605606607589608609610611612380 unmodified lines download_zip_btn = gr.Button("Download ZIP", variant="primary") delete_result_btn = gr.Button("Delete Result", variant="stop")
# Status and download link right under the buttons (they used to sit # below the details, past a full-size mask image). result_action_status = gr.Textbox( label="Status", interactive=False, visible=False ) result_download_file = gr.File(label="Download", visible=False)
# Result detail section (hidden by default) with gr.Accordion("Result Details", open=False) as result_details: result_metadata_md = gr.Markdown("No result selected") result_mask_img = gr.Image(label="Tissue Segmentation Mask", visible=False) result_mask_img = gr.Image( label="Tissue Segmentation Mask", visible=False, height=360 ) result_aeon_df = gr.Dataframe( label="Cancer Subtype Predictions", visible=False )1 unmodified line label="Biomarker Predictions", visible=False )
# Status and download result_action_status = gr.Textbox( label="Status", interactive=False, visible=False ) result_download_file = gr.File(label="Download", visible=False)
def load_results( session_id: str = "", request: gr.Request = None,99 unmodified lines aeon_df[col], errors="coerce" ).round(3)
# Round biomarker probabilities as in the main results table # ("Score" in results saved before the column was renamed). # Round paladin scores if paladin_df is not None and "Score" in paladin_df.columns: paladin_df["Score"] = pd.to_numeric( paladin_df["Score"], errors="coerce" ).round(3) for col in ("Prob. Present", "Score"): if paladin_df is not None and col in paladin_df.columns: paladin_df[col] = pd.to_numeric( paladin_df[col], errors="coerce" ).round(3)
# Aeon is skipped when the cancer subtype was provided; its # saved table then only repeats the given subtype at 1.0. provided = metadata.settings.get("cancer_subtype") aeon_ran = provided in (None, "", "Unknown") if not aeon_ran: aeon_df = None
# Format metadata settings_md = "### Analysis Settings\n\n" for key, value in metadata.settings.items(): if key == "paladin_weights": value = PALADIN_WEIGHTS_LABELS.get(value, value) settings_md += f"- **{key}**: {value}\n"
# Format cancer subtype with readable name9 unmodified lines f"### {metadata.slide_name}\n\n" f"**Analysis ID:** {metadata.analysis_id}\n\n" f"**Date:** {metadata.timestamp[:19]}\n\n" f"**Predicted Subtype:** {subtype_display}\n\n" f"{settings_md}" + ( f"**Predicted Subtype:** {subtype_display}\n\n" if aeon_ran else f"**Cancer Subtype:** {subtype_display} " "(provided; Aeon not run)\n\n" ) + settings_md )
return (51 unmodified lines )
return gr.File(value=str(zip_path), visible=True), gr.Textbox( value="ZIP ready for download", visible=True value="ZIP ready: click the file below to download it", visible=True, )
except Exception as e:1760 unmodified lines176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861760 unmodified lines assert _pick_slide("TCGA-HU-A4GJ-01A-01-TS1", hits)["file_id"] == "ts" # no diagnostic slide: fall back to any slide assert _pick_slide("TCGA-HU-A4GJ", hits[:1])["file_id"] == "ts"
def test_download_progress_is_throttled(tmp_path, monkeypatch): """Progress per chunk flooded the UI's event stream; report at most a few times a second, plus the final update.""" from mosaic import tcga
chunks = [b"x" * 10] * 1000 response = MagicMock() response.headers = {} response.iter_content.side_effect = lambda chunk_size: iter(chunks) calls = [] meta = {"file_name": "slide.svs", "file_size": 10_000} with ( patch("mosaic.tcga.get_slide_metadata", return_value=meta), patch("mosaic.tcga._make_request_with_retry", return_value=response), ): tcga.fetch_slide_by_uuid( "u-progress", tmp_path, progress_callback=lambda d, t: calls.append((d, t)) ) assert len(calls) <= 5 # not 1000 assert calls[-1] == (10_000, 10_000) # final update always sent assert response.iter_content.call_args.kwargs["chunk_size"] >= 1024 * 1024integration/test_results_tab.pyAdded+63
src/mosaic/tcga.py+18-9
src/mosaic/ui/app.py+22-9
src/mosaic/ui/user_tabs.py+35-15
tests/test_tcga.py+23