"""Hugging Face ZeroGPU + Gradio server for CellGemma Perturbation Studio.""" from __future__ import annotations try: import spaces except ImportError: class _SpacesFallback: @staticmethod 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 Any, Iterator, Literal import cellxgene_census import gradio as gr import pandas as pd import requests from fastapi import FastAPI, HTTPException, Query, Request from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from huggingface_hub import hf_hub_download 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() 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) 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() # --- Catalogues prédéfinis & APIs pour Cellules et Perturbations --- PRESET_HUMAN_CELLS = [ {"id": "local_tahoe", "name": "A549 · Carcinome pulmonaire (Malade)", "ontology": "LOCAL_TAHOE", "dataset": "tahoe", "tag": "Cancer"}, {"id": "local_k562", "name": "K562 · Leucémie myéloïde (Malade)", "ontology": "LOCAL_K562", "dataset": "k562", "tag": "Cancer"}, {"id": "mcf7", "name": "MCF-7 · Adénocarcinome mammaire (Sein)", "ontology": "luminal breast carcinoma cell", "dataset": "tahoe", "tag": "Cancer"}, {"id": "skbr3", "name": "SK-BR-3 · Carcinome mammaire HER2+", "ontology": "breast cancer cell", "dataset": "tahoe", "tag": "Cancer"}, {"id": "cd4_t", "name": "Lymphocyte T CD4+ (Sain · Immunité)", "ontology": "CD4-positive, alpha-beta T cell", "dataset": "tahoe", "tag": "Sain"}, {"id": "cd8_t", "name": "Lymphocyte T CD8+ cytotoxique (Sain · Immunité)", "ontology": "CD8-positive, alpha-beta T cell", "dataset": "tahoe", "tag": "Sain"}, {"id": "b_cell", "name": "Lymphocyte B (Sain · Sang)", "ontology": "B cell", "dataset": "k562", "tag": "Sain"}, {"id": "macrophage", "name": "Macrophage alvéolaire (Sain · Poumon)", "ontology": "macrophage", "dataset": "tahoe", "tag": "Sain"}, {"id": "pneumocyte2", "name": "Pneumocyte type II (Sain · Poumon)", "ontology": "type II pneumocyte", "dataset": "tahoe", "tag": "Sain"}, {"id": "hepatocyte", "name": "Hépatocyte (Sain · Foie)", "ontology": "hepatocyte", "dataset": "tahoe", "tag": "Sain"}, {"id": "adipocyte", "name": "Adipocyte (Tissu adipeux)", "ontology": "adipocyte", "dataset": "tahoe", "tag": "Sain"}, {"id": "astrocyte", "name": "Astrocyte (Cerveau)", "ontology": "astrocyte", "dataset": "tahoe", "tag": "Sain"}, {"id": "neuron", "name": "Neurone excitateur (Cerveau)", "ontology": "glutamatergic neuron", "dataset": "tahoe", "tag": "Sain"}, {"id": "cardiomyocyte", "name": "Cardiomyocyte (Cœur)", "ontology": "cardiac muscle cell", "dataset": "tahoe", "tag": "Sain"}, {"id": "fibroblast", "name": "Fibroblaste (Tissu conjonctif)", "ontology": "fibroblast", "dataset": "tahoe", "tag": "Sain"}, {"id": "epithelial", "name": "Cellule épithéliale", "ontology": "epithelial cell", "dataset": "tahoe", "tag": "Sain"}, ] PRESET_PERTURBATIONS = [ {"id": "panobinostat", "name": "Panobinostat", "kind": "drug", "category": "Molécule · Inhibiteur HDAC", "smiles": "Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1", "gene": "", "dataset": "tahoe"}, {"id": "dasatinib", "name": "Dasatinib", "kind": "drug", "category": "Molécule · Inhibiteur Kinase", "smiles": "Cc1nc(Nc2ncc(C(=O)Nc3c(C)cccc3Cl)s2)cc(N2CCN(CCO)CC2)n1", "gene": "", "dataset": "tahoe"}, {"id": "trametinib", "name": "Trametinib", "kind": "drug", "category": "Molécule · Inhibiteur MEK1/2", "smiles": "CC(=O)Nc1cccc(-n2c(=O)n(C3CC3)c(=O)c3c(Nc4ccc(I)cc4F)n(C)c(=O)c(C)c32)c1", "gene": "", "dataset": "tahoe"}, {"id": "imatinib", "name": "Imatinib", "kind": "drug", "category": "Molécule · Inhibiteur BCR-ABL", "smiles": "CC1=C(C=C(C=C1)NC(=O)C2=CC=C(C=C2)CN3CCN(CC3)C)NC4=NC=CC(=N4)C5=CN=CC=C5", "gene": "", "dataset": "k562"}, {"id": "tgfb_mimic", "name": "SB-431542 (Modulateur Cytokine TGF-β)", "kind": "cytokine", "category": "Cytokine / Voie TGF-β", "smiles": "C1OC2=C(O1)C=C(C=C2)C3=NC(=C(N3)C4=CC=CC=N4)C5=CC=C(C=C5)C(=O)N", "gene": "", "dataset": "tahoe"}, {"id": "myc_crispr", "name": "MYC (Extinction CRISPRi)", "kind": "crispr", "category": "CRISPR · Facteur de transcription", "smiles": "", "gene": "MYC", "dataset": "k562"}, {"id": "dnmt1_crispr", "name": "DNMT1 (Extinction CRISPRi)", "kind": "crispr", "category": "CRISPR · Épigénétique", "smiles": "", "gene": "DNMT1", "dataset": "k562"}, {"id": "tp53_crispr", "name": "TP53 (Extinction CRISPRi)", "kind": "crispr", "category": "CRISPR · Suppresseur de tumeur", "smiles": "", "gene": "TP53", "dataset": "k562"}, {"id": "egfr_crispr", "name": "EGFR (Extinction CRISPRi)", "kind": "crispr", "category": "CRISPR · Récepteur membranaire", "smiles": "", "gene": "EGFR", "dataset": "tahoe"}, ] # Cache global pour stocker les types cellulaires uniques de Census (chargé une seule fois) _CACHED_CENSUS_CELL_TYPES: list[str] = [] def _load_tahoe_drugs() -> dict[str, str]: catalog: dict[str, str] = {p["name"]: p["smiles"] for p in PRESET_PERTURBATIONS if p.get("smiles")} try: meta_path = hf_hub_download( repo_id="tahoebio/Tahoe-100M", filename="metadata/drug_metadata.parquet", repo_type="dataset", ) df_drugs = pd.read_parquet(meta_path) for _, row in df_drugs.iterrows(): name = str(row.get("drug", "")).strip() smiles = str(row.get("canonical_smiles", "")).strip() if name and smiles and smiles.lower() != "nan": catalog[name] = smiles except Exception: pass return catalog TAHOE_DRUGS_CATALOG = _load_tahoe_drugs() class PredictRequest(BaseModel): dataset: Literal["tahoe", "k562"] = "tahoe" cell_idx: int = Field(default=0, ge=0, le=99) custom_cell_id: str | None = None custom_cell: dict[str, float] | None = None kind: Literal["drug", "cytokine", "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) @spaces.GPU(duration=60) def predict_zero_gpu(req_json: str) -> Iterator[str]: 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, custom_cell_id=req.custom_cell_id, custom_cell=req.custom_cell, 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() # Autorise l'environnement local if origin_host in ("127.0.0.1", "localhost") and req_host in ("127.0.0.1", "localhost"): return True # Autorise automatiquement les espaces Hugging Face et proxys cloud if "hf.space" in origin_host or os.environ.get("SPACE_ID"): 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): 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 = 60 if request.method == "POST" else 300 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' 'unsafe-inline'; " "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " "img-src 'self' data:; " "connect-src 'self' https://pubchem.ncbi.nlm.nih.gov https://www.ebi.ac.uk; " "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" return response TOP_DUAL_SELECTOR_INJECTION = """
➔
🧬 Sélectionner une Cellule Source Humaine
Cellules humaines prédéfinies (Saines & Malades)
⚡ Sélectionner une Perturbation
Perturbations usuelles prédéfinies
""" def mount_studio_routes(app: FastAPI) -> None: 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}" ) if "" in versioned_index_html: versioned_index_html = versioned_index_html.replace("", f"{TOP_DUAL_SELECTOR_INJECTION}\n") else: versioned_index_html += TOP_DUAL_SELECTOR_INJECTION @app.get("/studio") async def studio_index() -> HTMLResponse: return HTMLResponse( content=versioned_index_html, headers={"Cache-Control": "no-store, must-revalidate"}, ) @app.get("/api/model_status") async def model_status() -> JSONResponse: return JSONResponse(engine.get_model_status()) @app.get("/api/bootstrap") 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, "preset_cells": PRESET_HUMAN_CELLS, "preset_perturbations": PRESET_PERTURBATIONS, "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") }, }) @app.get("/api/search_cells") async def search_cells(q: str = Query(..., min_length=1, max_length=100)) -> JSONResponse: global _CACHED_CENSUS_CELL_TYPES ql = q.strip().lower() # 1. Recherche dans nos presets locaux sûrs results: list[dict[str, Any]] = [ c for c in PRESET_HUMAN_CELLS if ql in c["name"].lower() or ql in c["ontology"].lower() ] # 2. Chargement paresseux et mise en cache des types cellulaires Census (une seule fois) if not _CACHED_CENSUS_CELL_TYPES: try: with cellxgene_census.open_soma() as census: adata_obs = cellxgene_census.get_anndata( census=census, organism="Homo sapiens", obs_column_names=["cell_type"], ) _CACHED_CENSUS_CELL_TYPES = sorted(adata_obs.obs["cell_type"].unique().tolist()) except Exception as exc: logger.warning("Impossible de précharger les types cellulaires Census : %s", exc) # 3. Filtrage instantané en Python sur la liste en cache seen_ontologies = {r["ontology"].lower() for r in results} matching = [ct for ct in _CACHED_CENSUS_CELL_TYPES if ql in ct.lower()] for ct in matching[:10]: if ct.lower() not in seen_ontologies: seen_ontologies.add(ct.lower()) results.append({ "id": f"census_{ct.lower().replace(' ', '_')}", "name": f"{ct.capitalize()} (Certifié Census)", "ontology": ct, "dataset": "tahoe", "tag": "Census Direct" }) return JSONResponse(results[:10]) @app.post("/api/fetch_cell_profile") async def fetch_cell_profile(payload: dict[str, Any]) -> JSONResponse: ontology = payload.get("ontology", "LOCAL_TAHOE") name = payload.get("name", "Cellule Humaine") dataset = payload.get("dataset", "tahoe") if ontology == "LOCAL_TAHOE": summary = engine.get_cell_baseline_summary("tahoe", 0) summary["custom_cell_id"] = None return JSONResponse(summary) if ontology == "LOCAL_K562": summary = engine.get_cell_baseline_summary("k562", 0) summary["custom_cell_id"] = None return JSONResponse(summary) cell_key = f"census_{ontology.lower().replace(' ', '_')}" if cell_key in engine.custom_cell_profiles: return JSONResponse({ **engine.get_cell_baseline_summary(dataset, 0, custom_cell_id=cell_key), "custom_cell_id": cell_key, }) try: with cellxgene_census.open_soma() as census: # 1. Premier essai avec le filtre strict (type + primary data) try: adata = cellxgene_census.get_anndata( census=census, organism="Homo sapiens", obs_value_filter=f"cell_type == '{ontology}' and is_primary_data == True", obs_coords=slice(0, 50), ) except Exception: adata = None # 2. Si 0 résultat ou échec, deuxième essai assoupli (uniquement le type cellulaire) if adata is None or adata.n_obs == 0: adata = cellxgene_census.get_anndata( census=census, organism="Homo sapiens", obs_value_filter=f"cell_type == '{ontology}'", obs_coords=slice(0, 50), ) if adata.n_obs > 0: X = adata.X.toarray() if hasattr(adata.X, "toarray") else np.asarray(adata.X) lib_sizes = X.sum(axis=1, keepdims=True) lib_sizes[lib_sizes == 0] = 1.0 X_norm = np.log1p((X / lib_sizes) * 1e4) mean_expr = X_norm.mean(axis=0) genes = [str(g).upper() for g in adata.var["feature_name"].values] expr_map = {g: float(v) for g, v in zip(genes, mean_expr) if v > 0.01 and g in engine.kg} summary = engine.register_custom_cell(cell_key, name, expr_map, base_dataset=dataset) return JSONResponse({**{k: v for k, v in summary.items() if k != "expression_map"}, "custom_cell_id": cell_key}) else: raise HTTPException(status_code=404, detail=f"Aucune cellule correspondante trouvée dans CELLxGENE Census pour : {ontology}") except HTTPException as he: raise he except Exception as exc: logger.error("Erreur critique lors du chargement Census pour %s : %s", ontology, exc) raise HTTPException(status_code=500, detail=f"Échec du chargement distant du profil transcriptomique : {str(exc)}") @app.get("/api/search_perturbations") async def search_perturbations(q: str = Query(..., min_length=1, max_length=100)) -> JSONResponse: ql = q.strip().lower() qu = q.strip().upper() results: list[dict[str, Any]] = [ p for p in PRESET_PERTURBATIONS if ql in p["name"].lower() or ql in p.get("category", "").lower() ] matching_genes = [g for g in engine.kg.keys() if g.startswith(qu)][:5] for g in matching_genes: results.append({ "id": f"crispr_{g}", "name": f"{g} (CRISPR Knockdown)", "kind": "crispr", "category": "CRISPR · Gène humain", "gene": g, "smiles": "", "dataset": "k562", }) for drug_name, smiles in TAHOE_DRUGS_CATALOG.items(): if ql in drug_name.lower() and not any(r["name"].lower() == drug_name.lower() for r in results): results.append({ "id": f"tahoe_{drug_name}", "name": drug_name, "kind": "drug", "category": "Molécule · Tahoe-100M", "smiles": smiles, "gene": "", "dataset": "tahoe", }) if len(results) >= 10: break if len(results) < 10: try: r = requests.get( f"https://pubchem.ncbi.nlm.nih.gov/rest/autocomplete/compound/{urllib.parse.quote(q)}/json?limit=5", timeout=3.0, ) if r.status_code == 200: terms = r.json().get("dictionary_terms", {}).get("compound", []) for term in terms: if not any(r["name"].lower() == term.lower() for r in results): results.append({ "id": f"pubchem_{term}", "name": term, "kind": "drug", "category": "Molécule / Ligand · PubChem API", "smiles": "", "gene": "", "dataset": "tahoe", }) except Exception: pass return JSONResponse(results[:12]) @app.post("/api/fetch_perturbation_details") async def fetch_perturbation_details(payload: dict[str, Any]) -> JSONResponse: kind = payload.get("kind", "drug") name = payload.get("name", "").strip() smiles = payload.get("smiles", "").strip() gene = payload.get("gene", "").strip().upper() if kind == "crispr" or (gene and gene in engine.kg): target_gene = gene or name.split(" ")[0].upper() graph = engine.get_gene_graph(target_gene) return JSONResponse({ "kind": "crispr", "name": target_gene, "gene": target_gene, "smiles": "", "dataset": "k562", "viz": graph, }) if not smiles and name: if name in TAHOE_DRUGS_CATALOG: smiles = TAHOE_DRUGS_CATALOG[name] else: try: r = requests.get( f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{urllib.parse.quote(name)}/property/CanonicalSMILES/JSON", timeout=4.0, ) if r.status_code == 200: smiles = r.json()["PropertyTable"]["Properties"][0]["CanonicalSMILES"] except Exception: pass if not smiles: smiles = "CC(=O)OC1=CC=CC=C1C(=O)O" mol_viz = parse_smiles_2d(smiles) return JSONResponse({ "kind": kind, "name": name or "Composé", "smiles": mol_viz["canonical_smiles"], "gene": "", "dataset": payload.get("dataset", "tahoe"), "viz": mol_viz, }) @app.get("/api/cell_summary") 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 @app.get("/api/molecule") 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 @app.get("/api/gene_graph") 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 @app.post("/api/predict_stream") async def predict_stream(req: PredictRequest): logger.info( "Requête de prédiction reçue — Dataset: %s, Cell Idx: %d, Custom Cell ID: %s, Kind: %s, Drug: %s", req.dataset, req.cell_idx, req.custom_cell_id, req.kind, req.drug_name, ) 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, custom_cell_id=req.custom_cell_id, custom_cell=req.custom_cell, ) except ValueError as exc: logger.error("Erreur de validation lors de la préparation de la cellule/prompt : %s", exc) raise HTTPException(status_code=400, detail=str(exc)) from exc except Exception as exc: logger.exception("Erreur inattendue dans prepare_cell_and_prompt") raise HTTPException(status_code=500, detail=f"Échec de l'initialisation de la prédiction : {str(exc)}") def _ndjson_gen(): try: for chunk in predict_zero_gpu(req.model_dump_json()): yield chunk + "\n" except Exception as exc: logger.error("Erreur durant le streaming des chunks de prédiction : %s", exc) yield json.dumps({"seq": -1, "type": "error", "message": str(exc)}) + "\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; } """ 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=( '
' f'' "
" ), apply_default_css=False, container=False, padding=False, ) 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()