Download app.py from google/cellgemma: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/google/cellgemma/resolve/main/app.py
- Command line
-
hf download hf://spaces/google/cellgemma/app.py
-
curl -L -o app.py https://huggingface.co/spaces/google/cellgemma/resolve/main/app.py
16.4 kB
| """Hugging Face ZeroGPU + Gradio server for CellGemma Perturbation Studio.""" | |
| from __future__ import annotations | |
| # CRITICAL: `spaces` MUST be imported before `torch` or `transformers` on ZeroGPU | |
| try: | |
| import spaces | |
| except ImportError: | |
| class _SpacesFallback: | |
| def GPU(*args, **kwargs): | |
| def _decorator(fn): | |
| return fn | |
| if len(args) == 1 and callable(args[0]) and not kwargs: | |
| return args[0] | |
| return _decorator | |
| spaces = _SpacesFallback() # type: ignore[assignment] | |
| import collections | |
| import hashlib | |
| import json | |
| import logging | |
| import os | |
| import secrets | |
| import time | |
| import urllib.parse | |
| from pathlib import Path | |
| from typing import Iterator, Literal | |
| import gradio as gr | |
| from fastapi import FastAPI, HTTPException, Query, Request | |
| from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel, Field | |
| from starlette.middleware import Middleware | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from engine import ( | |
| CURATED_PRESETS, | |
| IS_ZEROGPU, | |
| CellGemmaEngine, | |
| parse_smiles_2d, | |
| ) | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | |
| logger = logging.getLogger("cellgemma.space") | |
| ROOT_DIR = Path(__file__).resolve().parent | |
| STATIC_DIR = ROOT_DIR / "static" | |
| ALLOWED_METHODS = {"GET", "POST", "HEAD"} | |
| def _compute_asset_version() -> str: | |
| h = hashlib.sha256() | |
| for name in ("index.html", "styles.css", "app.js"): | |
| p = STATIC_DIR / name | |
| if p.exists(): | |
| h.update(p.read_bytes()) | |
| return h.hexdigest()[:10] | |
| ASSET_VERSION = _compute_asset_version() | |
| # Ephemeral per-instance CSRF token for direct API fallback calls (never hardcoded or logged) | |
| # TODO(security): Public read-only demo Space relies on Hugging Face Spaces ZeroGPU X-IP-Token quotas; add OAuth if user accounts are added. | |
| def _init_csrf_secret() -> str: | |
| env_tok = os.getenv("CELLGEMMA_CSRF_SECRET") | |
| if env_tok and len(env_tok) >= 32: | |
| return env_tok | |
| return secrets.token_hex(32) | |
| SESSION_CSRF_TOKEN = _init_csrf_secret() | |
| _rate_buckets: dict[str, collections.deque[float]] = collections.defaultdict(collections.deque) | |
| # Instantiate global CellGemma engine on main thread (registers CUDA tensors before launch on ZeroGPU) | |
| engine = CellGemmaEngine() | |
| if not IS_ZEROGPU and engine.device in ("cuda", "mps"): | |
| logger.info("Pre-warming CellGemma E4B weights in background on %s ...", engine.device) | |
| engine.start_background_preload() | |
| class PredictRequest(BaseModel): | |
| dataset: Literal["tahoe", "k562"] | |
| cell_idx: int = Field(default=0, ge=0, le=99) | |
| kind: Literal["drug", "crispr"] | |
| drug_name: str = Field(default="Custom Compound", max_length=60) | |
| smiles: str = Field(default="", max_length=200) | |
| concentration_um: float = Field(default=0.5, ge=0.001, le=100.0) | |
| gene: str = Field(default="", max_length=20) | |
| max_new_tokens: int = Field(default=180, ge=32, le=1024) | |
| temperature: float = Field(default=0.0, ge=0.0, le=1.5) | |
| def predict_zero_gpu(req_json: str) -> Iterator[str]: | |
| """ZeroGPU worker generator streaming Stage 1 gene tokens and Stage 2 expression deltas.""" | |
| try: | |
| raw = json.loads(req_json or "{}") | |
| req = PredictRequest.model_validate(raw) | |
| except Exception: | |
| yield json.dumps({"seq": 1, "type": "error", "message": "Invalid perturbation input parameters."}) | |
| return | |
| seq = 0 | |
| try: | |
| for event in engine.stream_predict( | |
| dataset=req.dataset, | |
| cell_idx=req.cell_idx, | |
| kind=req.kind, | |
| drug_name=req.drug_name, | |
| smiles=req.smiles, | |
| concentration_um=req.concentration_um, | |
| gene=req.gene, | |
| max_new_tokens=req.max_new_tokens, | |
| temperature=req.temperature, | |
| ): | |
| seq += 1 | |
| payload = dict(event) | |
| payload["seq"] = seq | |
| yield json.dumps(payload) | |
| except ValueError as exc: | |
| seq += 1 | |
| yield json.dumps({"seq": seq, "type": "error", "message": str(exc)}) | |
| except Exception: | |
| logger.exception("Error during ZeroGPU streaming prediction") | |
| seq += 1 | |
| yield json.dumps({"seq": seq, "type": "error", "message": "Inference failed on GPU worker."}) | |
| def _is_same_host_origin(origin: str, host_hdr: str) -> bool: | |
| if not origin: | |
| return True | |
| parsed = urllib.parse.urlparse(origin) | |
| if parsed.scheme not in ("http", "https") or not parsed.netloc: | |
| return False | |
| origin_host = parsed.netloc.split(":", 1)[0].strip().lower() | |
| req_host = (host_hdr or "").split(":", 1)[0].strip().lower() | |
| if origin_host in ("127.0.0.1", "localhost") and req_host in ("127.0.0.1", "localhost"): | |
| return True | |
| return bool(req_host and secrets.compare_digest(origin_host, req_host)) | |
| def _client_key(request: Request) -> str: | |
| fwd = (request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip() | |
| if fwd: | |
| return fwd | |
| return request.client.host if request.client else "127.0.0.1" | |
| class _StudioSecurityMiddleware(BaseHTTPMiddleware): | |
| """Enforces method allow-list, API rate limits, CSRF checks, and CSP headers.""" | |
| async def dispatch(self, request: Request, call_next): | |
| if request.method not in ALLOWED_METHODS: | |
| return JSONResponse({"error": "Method not allowed."}, status_code=405) | |
| path = request.url.path | |
| is_studio_or_api = ( | |
| path == "/studio" | |
| or path.startswith("/api/") | |
| or path.startswith("/studio_static/") | |
| ) | |
| if path.startswith("/api/"): | |
| now = time.monotonic() | |
| bucket = _rate_buckets[f"{_client_key(request)}:{request.method}"] | |
| while bucket and now - bucket[0] > 60.0: | |
| bucket.popleft() | |
| limit = 30 if request.method == "POST" else 240 | |
| if len(bucket) >= limit: | |
| return JSONResponse({"error": "Rate limit exceeded. Please wait briefly."}, status_code=429) | |
| bucket.append(now) | |
| if request.method == "POST": | |
| origin = request.headers.get("origin", "") | |
| host_hdr = request.headers.get("host", "") | |
| if not _is_same_host_origin(origin, host_hdr): | |
| return JSONResponse({"error": "Forbidden origin."}, status_code=403) | |
| csrf_hdr = request.headers.get("x-csrf-token", "") | |
| if not csrf_hdr or not secrets.compare_digest(csrf_hdr, SESSION_CSRF_TOKEN): | |
| return JSONResponse({"error": "Invalid or missing security token."}, status_code=403) | |
| response = await call_next(request) | |
| response.headers["X-Content-Type-Options"] = "nosniff" | |
| response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" | |
| response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()" | |
| if is_studio_or_api: | |
| response.headers["Content-Security-Policy"] = ( | |
| "default-src 'self'; " | |
| "script-src 'self'; " | |
| "style-src 'self' https://fonts.googleapis.com; " | |
| "img-src 'self' data:; " | |
| "connect-src 'self'; " | |
| "font-src 'self' https://fonts.gstatic.com; " | |
| "object-src 'none'; " | |
| "base-uri 'self'; " | |
| "frame-ancestors 'self' https://huggingface.co https://*.hf.space https://gemma.ai https://*.pages.github.io" | |
| ) | |
| if path.startswith("/api/") and "Cache-Control" not in response.headers: | |
| response.headers["Cache-Control"] = "no-store" | |
| elif (path == "/studio" or path.startswith("/studio_static/")) and "Cache-Control" not in response.headers: | |
| response.headers["Cache-Control"] = "no-cache, must-revalidate" | |
| else: | |
| response.headers["Content-Security-Policy"] = ( | |
| "frame-ancestors 'self' https://huggingface.co https://*.hf.space https://gemma.ai https://*.pages.github.io" | |
| ) | |
| return response | |
| def mount_studio_routes(app: FastAPI) -> None: | |
| """Attaches the Perturbation Studio UI and lightweight CPU helper endpoints onto Gradio's FastAPI app.""" | |
| app.mount("/studio_static", StaticFiles(directory=str(STATIC_DIR)), name="studio_static") | |
| raw_index_html = (STATIC_DIR / "index.html").read_text(encoding="utf-8") | |
| versioned_index_html = raw_index_html.replace( | |
| "/studio_static/styles.css", f"/studio_static/styles.css?v={ASSET_VERSION}" | |
| ).replace( | |
| "/studio_static/app.js", f"/studio_static/app.js?v={ASSET_VERSION}" | |
| ) | |
| async def studio_index() -> HTMLResponse: | |
| return HTMLResponse( | |
| content=versioned_index_html, | |
| headers={"Cache-Control": "no-store, must-revalidate"}, | |
| ) | |
| async def model_status() -> JSONResponse: | |
| return JSONResponse(engine.get_model_status()) | |
| async def bootstrap() -> JSONResponse: | |
| sample_genes = sorted(list(engine.kg.keys())) | |
| featured_genes = [ | |
| "MYC", "DNMT1", "TP53", "KRAS", "EGFR", "GATA1", | |
| "BRCA1", "EZH2", "HDAC1", "STAT3", "BCL2", "CDK4", | |
| ] | |
| return JSONResponse({ | |
| "csrf_token": SESSION_CSRF_TOKEN, | |
| "device": engine.device, | |
| "dtype": str(engine.dtype).replace("torch.", ""), | |
| "model_loaded": engine._model is not None, | |
| "model_status": engine.get_model_status(), | |
| "presets": CURATED_PRESETS, | |
| "featured_genes": [g for g in featured_genes if g in engine.kg], | |
| "total_kg_genes": len(sample_genes), | |
| "baseline_cells": { | |
| ds: engine.get_cell_baseline_summary(ds, 0) | |
| for ds in ("tahoe", "k562") | |
| }, | |
| }) | |
| async def get_cell_summary( | |
| dataset: Literal["tahoe", "k562"] = Query(default="tahoe"), | |
| cell_idx: int = Query(default=0, ge=0, le=99), | |
| ) -> JSONResponse: | |
| try: | |
| return JSONResponse(engine.get_cell_baseline_summary(dataset, cell_idx)) | |
| except ValueError as exc: | |
| raise HTTPException(status_code=400, detail=str(exc)) from exc | |
| async def get_molecule(smiles: str = Query(..., min_length=1, max_length=200)) -> JSONResponse: | |
| try: | |
| return JSONResponse(parse_smiles_2d(smiles)) | |
| except ValueError as exc: | |
| raise HTTPException(status_code=400, detail=str(exc)) from exc | |
| async def get_gene_graph(gene: str = Query(..., min_length=1, max_length=20)) -> JSONResponse: | |
| try: | |
| return JSONResponse(engine.get_gene_graph(gene)) | |
| except ValueError as exc: | |
| raise HTTPException(status_code=404, detail=str(exc)) from exc | |
| async def predict_stream(req: PredictRequest): | |
| try: | |
| engine.prepare_cell_and_prompt( | |
| dataset=req.dataset, | |
| cell_idx=req.cell_idx, | |
| kind=req.kind, | |
| drug_name=req.drug_name, | |
| smiles=req.smiles, | |
| concentration_um=req.concentration_um, | |
| gene=req.gene, | |
| ) | |
| except ValueError as exc: | |
| raise HTTPException(status_code=400, detail=str(exc)) from exc | |
| def _ndjson_gen(): | |
| for chunk in predict_zero_gpu(req.model_dump_json()): | |
| yield chunk + "\n" | |
| return StreamingResponse( | |
| _ndjson_gen(), | |
| media_type="application/x-ndjson", | |
| headers={ | |
| "X-Accel-Buffering": "no", | |
| "Cache-Control": "no-cache, no-transform", | |
| }, | |
| ) | |
| SHELL_CSS = """ | |
| html, body { | |
| margin: 0 !important; | |
| padding: 0 !important; | |
| width: 100% !important; | |
| height: 100% !important; | |
| overflow: hidden !important; | |
| background: #030711 !important; | |
| } | |
| .gradio-container { | |
| margin: 0 !important; | |
| padding: 0 !important; | |
| max-width: 100% !important; | |
| width: 100vw !important; | |
| height: 100dvh !important; | |
| overflow: hidden !important; | |
| background: #030711 !important; | |
| } | |
| footer { | |
| display: none !important; | |
| } | |
| #cellgemma-studio-shell { | |
| position: fixed; | |
| inset: 0; | |
| width: 100vw; | |
| height: 100dvh; | |
| margin: 0; | |
| padding: 0; | |
| z-index: 1; | |
| } | |
| #cellgemma-studio-frame { | |
| width: 100%; | |
| height: 100%; | |
| border: 0; | |
| display: block; | |
| } | |
| .toast-wrap { | |
| z-index: 9999 !important; | |
| } | |
| """ | |
| SHELL_JS = """ | |
| () => { | |
| window.__cgPendingPayload = "{}"; | |
| window.__triggerCellGemmaZeroGPU = (payloadJsonStr) => { | |
| window.__cgPendingPayload = payloadJsonStr || "{}"; | |
| const btn = document.querySelector("#cg-gpu-btn button, button#cg-gpu-btn"); | |
| if (!btn) return false; | |
| btn.click(); | |
| return true; | |
| }; | |
| window.__cancelCellGemmaZeroGPU = () => { | |
| const btn = document.querySelector("#cg-gpu-cancel button, button#cg-gpu-cancel"); | |
| if (btn) btn.click(); | |
| }; | |
| } | |
| """ | |
| def create_demo() -> gr.Blocks: | |
| with gr.Blocks( | |
| title="CellGemma · Single-Cell Perturbation Studio", | |
| fill_height=True, | |
| fill_width=True, | |
| analytics_enabled=False, | |
| ) as demo: | |
| gr.HTML( | |
| value=( | |
| '<div id="cellgemma-studio-shell">' | |
| f'<iframe id="cellgemma-studio-frame" src="/studio?v={ASSET_VERSION}" ' | |
| 'title="CellGemma Single-Cell Perturbation Studio"></iframe>' | |
| "</div>" | |
| ), | |
| apply_default_css=False, | |
| container=False, | |
| padding=False, | |
| ) | |
| # Hidden Gradio event bridge so ZeroGPU X-IP-Token quota headers negotiate natively | |
| gpu_req = gr.Textbox(value="", visible="hidden", elem_id="cg-gpu-req") | |
| gpu_out = gr.Textbox(value="", visible="hidden", elem_id="cg-gpu-out") | |
| gpu_btn = gr.Button("Run", visible="hidden", elem_id="cg-gpu-btn") | |
| gpu_cancel = gr.Button("Cancel", visible="hidden", elem_id="cg-gpu-cancel") | |
| run_ev = gpu_btn.click( | |
| fn=predict_zero_gpu, | |
| inputs=[gpu_req], | |
| outputs=[gpu_out], | |
| js="() => window.__cgPendingPayload || '{}'", | |
| show_progress="hidden", | |
| api_name="predict", | |
| ) | |
| gpu_out.change( | |
| fn=None, | |
| inputs=[gpu_out], | |
| outputs=[], | |
| js=( | |
| "(val) => {" | |
| " const f = document.getElementById('cellgemma-studio-frame');" | |
| " if (val && f && f.contentWindow && f.contentWindow.__onZeroGpuStream) {" | |
| " f.contentWindow.__onZeroGpuStream(val);" | |
| " }" | |
| "}" | |
| ), | |
| trigger_mode="multiple", | |
| show_progress="hidden", | |
| ) | |
| run_ev.then( | |
| fn=None, | |
| inputs=[gpu_out], | |
| outputs=[], | |
| js=( | |
| "(val) => {" | |
| " const f = document.getElementById('cellgemma-studio-frame');" | |
| " if (f && f.contentWindow && f.contentWindow.__onZeroGpuDone) {" | |
| " f.contentWindow.__onZeroGpuDone(val);" | |
| " }" | |
| "}" | |
| ), | |
| show_progress="hidden", | |
| ) | |
| gpu_cancel.click( | |
| fn=None, | |
| inputs=None, | |
| outputs=None, | |
| cancels=[run_ev], | |
| show_progress="hidden", | |
| ) | |
| return demo | |
| if __name__ == "__main__": | |
| is_hf_space = bool(os.environ.get("SPACE_ID")) | |
| default_host = "0.0.0.0" if is_hf_space else "127.0.0.1" | |
| bind_host = os.environ.get("GRADIO_SERVER_NAME", default_host) | |
| bind_port = int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", "7860"))) | |
| demo_blocks = create_demo() | |
| fastapi_app, _, _ = demo_blocks.launch( | |
| server_name=bind_host, | |
| server_port=bind_port, | |
| ssr_mode=False, | |
| prevent_thread_lock=True, | |
| footer_links=[], | |
| show_error=True, | |
| app_kwargs={"middleware": [Middleware(_StudioSecurityMiddleware)]}, | |
| css=SHELL_CSS, | |
| js=SHELL_JS, | |
| ) | |
| mount_studio_routes(fastapi_app) | |
| demo_blocks.block_thread() | |