Spaces:
sebps
/
Sleeping

cellgemma / app.py
sebps's picture
Update app.py
aef88fa verified
Raw History Blame Contribute Delete
47.7 kB
"""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 = """ <style> #preset-bar, .preset-strip, .preset-tabs, [data-role="preset-bar"] { display: none !important; } #cg-dual-topbar { display: flex; align-items: center; justify-content: center; gap: 14px; padding: 10px 18px; background: rgba(11, 17, 32, 0.92); border-bottom: 1px solid rgba(99, 179, 237, 0.18); backdrop-filter: blur(12px); position: sticky; top: 0; z-index: 900; font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; } .cg-pill-btn { display: flex; align-items: center; gap: 12px; background: rgba(20, 30, 54, 0.85); border: 1px solid rgba(99, 179, 237, 0.3); border-radius: 12px; padding: 8px 16px; color: #f1f5f9; cursor: pointer; transition: all 0.18s ease; min-width: 260px; text-align: left; } .cg-pill-btn:hover { border-color: #38bdf8; background: rgba(30, 46, 82, 0.95); transform: translateY(-1px); box-shadow: 0 4px 16px rgba(56, 189, 248, 0.18); } .cg-pill-icon { font-size: 20px; width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; background: rgba(56, 189, 248, 0.14); border-radius: 8px; } .cg-pill-meta { display: flex; flex-direction: column; overflow: hidden; } .cg-pill-label { font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: #94a3b8; font-weight: 600; } .cg-pill-value { font-size: 13.5px; font-weight: 600; color: #ffffff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 240px; } .cg-arrow-sep { color: #38bdf8; font-weight: 700; font-size: 16px; } .cg-modal-backdrop { display: none; position: fixed; inset: 0; background: rgba(3, 7, 17, 0.78); backdrop-filter: blur(6px); z-index: 9999; align-items: center; justify-content: center; } .cg-modal-backdrop.open { display: flex; } .cg-modal-card { background: #0f172a; border: 1px solid rgba(56, 189, 248, 0.35); border-radius: 16px; width: 92%; max-width: 560px; padding: 22px; color: #f8fafc; box-shadow: 0 24px 60px rgba(0, 0, 0, 0.65); font-family: 'Inter', sans-serif; } .cg-modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; } .cg-modal-title { font-size: 16px; font-weight: 700; color: #38bdf8; } .cg-close-btn { background: transparent; border: none; color: #94a3b8; font-size: 20px; cursor: pointer; } .cg-search-input { width: 100%; box-sizing: border-box; padding: 11px 14px; border-radius: 10px; border: 1px solid rgba(148, 163, 184, 0.3); background: #1e293b; color: #fff; font-size: 14px; outline: none; margin-bottom: 12px; } .cg-search-input:focus { border-color: #38bdf8; } .cg-section-subtitle { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #94a3b8; margin: 8px 0 8px 0; } .cg-results-list { max-height: 280px; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; } .cg-result-item { display: flex; justify-content: space-between; align-items: center; padding: 10px 12px; border-radius: 10px; background: rgba(30, 41, 59, 0.65); border: 1px solid rgba(148, 163, 184, 0.14); cursor: pointer; transition: background 0.15s; } .cg-result-item:hover { background: rgba(56, 189, 248, 0.18); border-color: #38bdf8; } .cg-badge { font-size: 11px; padding: 2px 8px; border-radius: 999px; background: rgba(56, 189, 248, 0.18); color: #7dd3fc; } </style> <div id="cg-dual-topbar"> <button type="button" class="cg-pill-btn" id="cg-btn-cell"> <div class="cg-pill-icon">🧬</div> <div class="cg-pill-meta"> <span class="cg-pill-label">Cellule Source</span> <span class="cg-pill-value" id="cg-label-cell">A549 · Carcinome pulmonaire</span> </div> </button> <span class="cg-arrow-sep">➔</span> <button type="button" class="cg-pill-btn" id="cg-btn-pert"> <div class="cg-pill-icon">⚡</div> <div class="cg-pill-meta"> <span class="cg-pill-label">Perturbation Appliquée</span> <span class="cg-pill-value" id="cg-label-pert">Panobinostat (HDAC)</span> </div> </button> </div> <div class="cg-modal-backdrop" id="cg-modal-cell"> <div class="cg-modal-card"> <div class="cg-modal-header"> <span class="cg-modal-title">🧬 Sélectionner une Cellule Source Humaine</span> <button type="button" class="cg-close-btn" id="cg-close-cell">✕</button> </div> <input type="text" class="cg-search-input" id="cg-input-cell" placeholder="Rechercher par API (ex: T cell, Hepatocyte, Glioblastoma, Macrophage...)" autocomplete="off" /> <div class="cg-section-subtitle" id="cg-subtitle-cell">Cellules humaines prédéfinies (Saines & Malades)</div> <div class="cg-results-list" id="cg-list-cell"></div> </div> </div> <div class="cg-modal-backdrop" id="cg-modal-pert"> <div class="cg-modal-card"> <div class="cg-modal-header"> <span class="cg-modal-title">⚡ Sélectionner une Perturbation</span> <button type="button" class="cg-close-btn" id="cg-close-pert">✕</button> </div> <input type="text" class="cg-search-input" id="cg-input-pert" placeholder="Rechercher molécule, cytokine ou gène CRISPR (ex: Imatinib, TNF, MYC, TP53...)" autocomplete="off" /> <div class="cg-section-subtitle" id="cg-subtitle-pert">Perturbations usuelles prédéfinies</div> <div class="cg-results-list" id="cg-list-pert"></div> </div> </div> <script> (function() { let csrfToken = ""; let presetCells = []; let presetPerts = []; window.__cgActiveSelection = { dataset: "tahoe", cell_idx: 0, custom_cell_id: null, cell_name: "A549 · Carcinome pulmonaire", kind: "drug", drug_name: "Panobinostat", smiles: "Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1", gene: "", concentration_um: 0.5 }; // Intercepte le fetch pour propager l'état actif complet dans la simulation const origFetch = window.fetch; window.fetch = async function(resource, config) { if (typeof resource === "string" && resource.includes("/api/predict_stream") && config && config.body) { try { const body = JSON.parse(config.body); const sel = window.__cgActiveSelection; body.dataset = sel.dataset; body.cell_idx = sel.cell_idx; body.custom_cell_id = sel.custom_cell_id; body.kind = sel.kind; body.drug_name = sel.drug_name; body.smiles = sel.smiles; body.gene = sel.gene; config.body = JSON.stringify(body); } catch (e) {} } return origFetch.apply(this, arguments); }; if (window.parent && window.parent.__triggerCellGemmaZeroGPU) { const origTrigger = window.parent.__triggerCellGemmaZeroGPU; window.parent.__triggerCellGemmaZeroGPU = function(payloadStr) { try { const body = JSON.parse(payloadStr || "{}"); const sel = window.__cgActiveSelection; body.dataset = sel.dataset; body.cell_idx = sel.cell_idx; body.custom_cell_id = sel.custom_cell_id; body.kind = sel.kind; body.drug_name = sel.drug_name; body.smiles = sel.smiles; body.gene = sel.gene; return origTrigger(JSON.stringify(body)); } catch (e) { return origTrigger(payloadStr); } }; } async function initPanel() { const topBar = document.getElementById("cg-dual-topbar"); const appRoot = document.querySelector("header")?.parentElement || document.body; const headerEl = document.querySelector("header"); if (headerEl && headerEl.nextSibling) { appRoot.insertBefore(topBar, headerEl.nextSibling); } else { appRoot.prepend(topBar); } try { const res = await origFetch("/api/bootstrap"); const data = await res.json(); csrfToken = data.csrf_token || ""; presetCells = data.preset_cells || []; presetPerts = data.preset_perturbations || []; renderCellList(presetCells); renderPertList(presetPerts); } catch (e) { console.error("Erreur bootstrap:", e); } } function renderCellList(items) { const list = document.getElementById("cg-list-cell"); list.innerHTML = ""; items.forEach(item => { const div = document.createElement("div"); div.className = "cg-result-item"; div.innerHTML = `<span><strong>${item.name}</strong></span><span class="cg-badge">${item.tag || "Humain"}</span>`; div.onclick = () => selectCell(item); list.appendChild(div); }); } async function selectCell(item) { const labelEl = document.getElementById("cg-label-cell"); const modalCard = document.querySelector("#cg-modal-cell .cg-modal-card"); let progressBox = document.getElementById("cg-cell-progress"); if (!progressBox) { progressBox = document.createElement("div"); progressBox.id = "cg-cell-progress"; progressBox.style.cssText = "margin-top: 10px; padding: 10px; background: rgba(56,189,248,0.1); border: 1px solid #38bdf8; border-radius: 8px; font-size: 12px; color: #38bdf8;"; modalCard.appendChild(progressBox); } labelEl.textContent = "⏳ Chargement distant..."; progressBox.innerHTML = `<strong>Chargement du séquencage scRNA-seq :</strong> ${item.name}<br>` + `<div style="width:100%; background:#1e293b; height:6px; border-radius:3px; margin-top:6px; overflow:hidden;">` + `<div id="cg-progress-bar" style="width: 30%; height:100%; background:#38bdf8; transition: width 0.4s ease;"></div></div>`; try { document.getElementById("cg-progress-bar").style.width = "70%"; if (!csrfToken) { const bootRes = await origFetch("/api/bootstrap"); const bootData = await bootRes.json(); csrfToken = bootData.csrf_token || ""; } const res = await origFetch("/api/fetch_cell_profile", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-Token": csrfToken }, body: JSON.stringify(item) }); if (!res.ok) { const errData = await res.json(); throw new Error(errData.detail || "Erreur lors de la récupération distante."); } const profile = await res.json(); document.getElementById("cg-progress-bar").style.width = "100%"; setTimeout(() => { document.getElementById("cg-modal-cell").classList.remove("open"); if (progressBox) progressBox.remove(); }, 400); window.__cgActiveSelection.dataset = profile.dataset || "tahoe"; window.__cgActiveSelection.custom_cell_id = profile.custom_cell_id || null; window.__cgActiveSelection.cell_name = item.name; labelEl.textContent = item.name; // Émet l'événement pour mettre à jour l'UI globale window.dispatchEvent(new CustomEvent("cellgemma:cell-updated", { detail: { ...profile, name: item.name } })); } catch (e) { console.error("Erreur de chargement de cellule :", e); labelEl.textContent = "❌ Erreur de chargement"; progressBox.style.background = "rgba(244,63,94,0.1)"; progressBox.style.borderColor = "#f43f5e"; progressBox.style.color = "#f43f5e"; progressBox.innerHTML = `<strong>Échec du chargement :</strong> ${e.message}`; } } // Écouteur pour mettre à jour le titre affiché sous l'illustration de la cellule dans l'UI principale window.addEventListener("cellgemma:cell-updated", (event) => { const profile = event.detail; if (profile && profile.name) { const cellTitleEl = document.querySelector(".cell-title-display, #cell-title, .cell-name-label, .cell-subtitle"); if (cellTitleEl) { cellTitleEl.textContent = profile.name; } } }); function renderPertList(items) { const list = document.getElementById("cg-list-pert"); list.innerHTML = ""; items.forEach(item => { const div = document.createElement("div"); div.className = "cg-result-item"; div.innerHTML = `<span><strong>${item.name}</strong></span><span class="cg-badge">${item.category || item.kind}</span>`; div.onclick = () => selectPert(item); list.appendChild(div); }); } async function selectPert(item) { const labelEl = document.getElementById("cg-label-pert"); labelEl.textContent = "⏳ Chargement des caractéristiques..."; document.getElementById("cg-modal-pert").classList.remove("open"); try { const res = await origFetch("/api/fetch_perturbation_details", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-Token": csrfToken }, body: JSON.stringify(item) }); const details = await res.json(); window.__cgActiveSelection.kind = details.kind; window.__cgActiveSelection.drug_name = details.name; window.__cgActiveSelection.smiles = details.smiles || ""; window.__cgActiveSelection.gene = details.gene || ""; if (details.dataset) window.__cgActiveSelection.dataset = details.dataset; labelEl.textContent = `${details.name} (${details.kind.toUpperCase()})`; const smilesInput = document.querySelector('input[name="smiles"], #smiles-input'); if (smilesInput && details.smiles) { smilesInput.value = details.smiles; smilesInput.dispatchEvent(new Event("input", { bubbles: true })); } const geneInput = document.querySelector('input[name="gene"], #gene-input'); if (geneInput && details.gene) { geneInput.value = details.gene; geneInput.dispatchEvent(new Event("input", { bubbles: true })); } } catch (e) { labelEl.textContent = item.name; } } document.getElementById("cg-btn-cell").onclick = () => { document.getElementById("cg-modal-cell").classList.add("open"); document.getElementById("cg-input-cell").focus(); }; document.getElementById("cg-close-cell").onclick = () => document.getElementById("cg-modal-cell").classList.remove("open"); document.getElementById("cg-btn-pert").onclick = () => { document.getElementById("cg-modal-pert").classList.add("open"); document.getElementById("cg-input-pert").focus(); }; document.getElementById("cg-close-pert").onclick = () => document.getElementById("cg-modal-pert").classList.remove("open"); let cellTimer = null; document.getElementById("cg-input-cell").addEventListener("input", (e) => { clearTimeout(cellTimer); const q = e.target.value.trim(); if (!q) { document.getElementById("cg-subtitle-cell").textContent = "Cellules humaines prédéfinies (Saines & Malades)"; renderCellList(presetCells); return; } cellTimer = setTimeout(async () => { document.getElementById("cg-subtitle-cell").textContent = "Résultats API (CELLxGENE Census)..."; const res = await origFetch(`/api/search_cells?q=${encodeURIComponent(q)}`); const results = await res.json(); renderCellList(results); }, 260); }); let pertTimer = null; document.getElementById("cg-input-pert").addEventListener("input", (e) => { clearTimeout(pertTimer); const q = e.target.value.trim(); if (!q) { document.getElementById("cg-subtitle-pert").textContent = "Perturbations usuelles prédéfinies"; renderPertList(presetPerts); return; } pertTimer = setTimeout(async () => { document.getElementById("cg-subtitle-pert").textContent = "Résultats API (PubChem / Tahoe / Gènes CRISPR)..."; const res = await origFetch(`/api/search_perturbations?q=${encodeURIComponent(q)}`); const results = await res.json(); renderPertList(results); }, 260); }); if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", initPanel); } else { initPanel(); } })(); </script> """ 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 "</body>" in versioned_index_html: versioned_index_html = versioned_index_html.replace("</body>", f"{TOP_DUAL_SELECTOR_INJECTION}\n</body>") 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=( '<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, ) 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()
"""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"},