Download scripts/warm_tcga_examples.py from raylim/mosaic: direct link, hf CLI and curl.
- Browser
- Download file 5.32 kB
-
https://huggingface.co/spaces/raylim/mosaic/resolve/main/scripts/warm_tcga_examples.py
- Command line
-
hf download hf://spaces/raylim/mosaic/scripts/warm_tcga_examples.py
-
curl -L -o warm_tcga_examples.py https://huggingface.co/spaces/raylim/mosaic/resolve/main/scripts/warm_tcga_examples.py
5.32 kB
| #!/usr/bin/env python3 | |
| """Run the UI's example TCGA slides with their default (pre-filled) settings. | |
| Analyzing a TCGA slide stores its results in the Space's TCGA results cache | |
| (MOSAIC_TCGA_CACHE_HF_REPO), keyed by the settings and model versions. Running | |
| the examples through the real UI therefore warms the cache for exactly the | |
| keys visitors will hit when they click an example. | |
| # Warm the private staging Space (computes uncached examples, ~5-20 min each) | |
| python scripts/warm_tcga_examples.py --url https://raylim-mosaic-staging.hf.space --private | |
| # After a deploy: check every example is served from the cache | |
| python scripts/warm_tcga_examples.py --url https://raylim-mosaic.hf.space --expect-cached | |
| Runs the slides one after another (the Space analyzes one at a time anyway). | |
| Needs only Playwright; reuses the browser helpers of hf_space_e2e.py. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import hf_space_e2e as e # noqa: E402 | |
| # Must match the gr.Examples list in src/mosaic/ui/app.py (checked by a test). | |
| EXAMPLE_SLIDES = [ | |
| "TCGA-86-8074-01Z-00-DX1", # LUAD | |
| "TCGA-AZ-4313-01Z-00-DX1", # COAD | |
| "TCGA-EJ-7123-01Z-00-DX1", # PRAD | |
| "TCGA-G2-A2ES-01Z-00-DX1", # BLCA | |
| "TCGA-HU-A4GJ-01Z-00-DX1", # STAD | |
| "TCGA-EY-A1GK-01Z-00-DX1", # UCEC | |
| ] | |
| CACHED_MAX_SEC = 90 # a cache hit returns in seconds; leave room for a cold page | |
| def run_example(browser, url: str, slide_id: str, timeout_ms: int) -> dict: | |
| page = browser.new_page( | |
| viewport={"width": 1600, "height": 1400}, extra_http_headers=e._AUTH_HEADERS | |
| ) | |
| try: | |
| e._open_app(page, url) | |
| page.get_by_role("radio", name="Fetch from TCGA").check() | |
| page.get_by_label("TCGA Slide ID").fill(slide_id) | |
| page.get_by_role("button", name="Fetch Slide").click() | |
| status = page.get_by_label("Fetch Status") | |
| status.wait_for(state="visible", timeout=timeout_ms) | |
| page.wait_for_function( | |
| "el => el.value && el.value.includes('Slide fetched')", | |
| arg=status.element_handle(), | |
| timeout=timeout_ms, | |
| ) | |
| page.wait_for_timeout(2000) | |
| prefill = status.input_value() | |
| start = time.monotonic() | |
| page.get_by_role("button", name="Analyze").click() | |
| download = page.get_by_role("button", name="Download Paladin Results") | |
| while not download.is_visible(): | |
| errors = [ | |
| t for t in page.locator(".toast-body").all_inner_texts() if "rror" in t | |
| ] | |
| if errors: | |
| raise RuntimeError(errors[0][:300]) | |
| if (time.monotonic() - start) * 1000 > timeout_ms: | |
| shot = Path(f"warm_timeout_{slide_id}.png").resolve() | |
| page.screenshot(path=str(shot), full_page=True) | |
| analyze = page.get_by_role("button", name="Analyze") | |
| raise TimeoutError( | |
| f"no results after {timeout_ms // 1000}s " | |
| f"(Analyze enabled={analyze.is_enabled()}, screenshot {shot})" | |
| ) | |
| time.sleep(2) | |
| return { | |
| "ok": True, | |
| "seconds": round(time.monotonic() - start, 1), | |
| "prefill": prefill, | |
| } | |
| finally: | |
| page.close() | |
| def main(argv=None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| parser.add_argument("--url", required=True, help="Space URL") | |
| parser.add_argument( | |
| "--private", action="store_true", help="send HF_TOKEN (private Space)" | |
| ) | |
| parser.add_argument( | |
| "--expect-cached", | |
| action="store_true", | |
| help=f"fail if any example takes longer than {CACHED_MAX_SEC}s", | |
| ) | |
| parser.add_argument("--slides", nargs="*", default=EXAMPLE_SLIDES) | |
| parser.add_argument("--timeout-min", type=float, default=45) | |
| parser.add_argument("--out", help="write a JSON summary here") | |
| args = parser.parse_args(argv) | |
| if args.private: | |
| e._AUTH_HEADERS["Authorization"] = f"Bearer {os.environ['HF_TOKEN']}" | |
| from playwright.sync_api import sync_playwright | |
| results = {} | |
| with sync_playwright() as pw: | |
| browser = pw.chromium.launch() | |
| for slide_id in args.slides: | |
| print(f"--- {slide_id}", flush=True) | |
| try: | |
| results[slide_id] = run_example( | |
| browser, args.url, slide_id, int(args.timeout_min * 60_000) | |
| ) | |
| except Exception as exc: # pylint: disable=broad-except | |
| results[slide_id] = {"ok": False, "error": str(exc).splitlines()[0]} | |
| print(json.dumps(results[slide_id]), flush=True) | |
| browser.close() | |
| failed = [s for s, r in results.items() if not r["ok"]] | |
| slow = [ | |
| s | |
| for s, r in results.items() | |
| if args.expect_cached and r["ok"] and r["seconds"] > CACHED_MAX_SEC | |
| ] | |
| if args.out: | |
| Path(args.out).write_text(json.dumps(results, indent=2)) | |
| print( | |
| "RESULT", | |
| "PASS" if not failed and not slow else "FAIL", | |
| json.dumps({"failed": failed, "not_cached": slow}), | |
| ) | |
| return 1 if failed or slow else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |