"""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 = """