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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
"""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:
        @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 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)


@spaces.GPU(duration=60)
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}"
    )

    @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,
            "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/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):
        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()