Spaces:
Running on Zero

MaartenGr commited on
Commit
328fef0
·
0 Parent(s):

Preparing for release :)

Browse files
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.png filter=lfs diff=lfs merge=lfs -text
23
+ *.pt filter=lfs diff=lfs merge=lfs -text
24
+ *.pth filter=lfs diff=lfs merge=lfs -text
25
+ *.rar filter=lfs diff=lfs merge=lfs -text
26
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
27
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
29
+ *.tar filter=lfs diff=lfs merge=lfs -text
30
+ *.tflite filter=lfs diff=lfs merge=lfs -text
31
+ *.tgz filter=lfs diff=lfs merge=lfs -text
32
+ *.wasm filter=lfs diff=lfs merge=lfs -text
33
+ *.xz filter=lfs diff=lfs merge=lfs -text
34
+ *.zip filter=lfs diff=lfs merge=lfs -text
35
+ *.zst filter=lfs diff=lfs merge=lfs -text
36
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CellGemma Perturbation Studio
3
+ emoji: 🧬
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 6.30.0
8
+ python_version: '3.12'
9
+ app_file: app.py
10
+ pinned: false
11
+ license: apache-2.0
12
+ short_description: Single-cell drug & CRISPR predictions with CellGemma
13
+ ---
14
+
15
+ # CellGemma · Single-Cell Perturbation Studio
16
+
17
+ Interactive visual studio demonstrating how **CellGemma** (`Gemma 4 E4B` + dataset-specific Stage 2 `ExpressionDecoder`) predicts single-cell transcriptional shifts in response to:
18
+
19
+ - **Small-molecule compounds** on single **A549** lung carcinoma control cells (SMILES structure + concentration in µM)
20
+ - **CRISPRi gene knockdowns** on single **K562** chronic myeloid leukemia control cells (target human gene + STRING functional interaction network)
21
+
22
+ ## Configuration
23
+
24
+ By default, the Space loads weights and assets from `google/cellgemma-e4b`. You can optionally configure:
25
+
26
+ - `CELLGEMMA_MODEL_ID`: Hugging Face model repository ID (defaults to `google/cellgemma-e4b`).
27
+ - `HF_TOKEN`: Optional Hugging Face access token secret if reading from a gated or private repository.
28
+
29
+ ## Running Locally
30
+
31
+ ```bash
32
+ pip install -r requirements.txt
33
+ python app.py
34
+ ```
35
+
36
+ Then open `http://127.0.0.1:7860` in your browser.
app.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hugging Face ZeroGPU + Gradio server for CellGemma Perturbation Studio."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # CRITICAL: `spaces` MUST be imported before `torch` or `transformers` on ZeroGPU
6
+ try:
7
+ import spaces
8
+ except ImportError:
9
+ class _SpacesFallback:
10
+ @staticmethod
11
+ def GPU(*args, **kwargs):
12
+ def _decorator(fn):
13
+ return fn
14
+ if len(args) == 1 and callable(args[0]) and not kwargs:
15
+ return args[0]
16
+ return _decorator
17
+
18
+ spaces = _SpacesFallback() # type: ignore[assignment]
19
+
20
+ import collections
21
+ import hashlib
22
+ import json
23
+ import logging
24
+ import os
25
+ import secrets
26
+ import time
27
+ import urllib.parse
28
+ from pathlib import Path
29
+ from typing import Iterator, Literal
30
+
31
+ import gradio as gr
32
+ from fastapi import FastAPI, HTTPException, Query, Request
33
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
34
+ from fastapi.staticfiles import StaticFiles
35
+ from pydantic import BaseModel, Field
36
+ from starlette.middleware import Middleware
37
+ from starlette.middleware.base import BaseHTTPMiddleware
38
+
39
+ from engine import (
40
+ CURATED_PRESETS,
41
+ IS_ZEROGPU,
42
+ CellGemmaEngine,
43
+ parse_smiles_2d,
44
+ )
45
+
46
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
47
+ logger = logging.getLogger("cellgemma.space")
48
+
49
+ ROOT_DIR = Path(__file__).resolve().parent
50
+ STATIC_DIR = ROOT_DIR / "static"
51
+ ALLOWED_METHODS = {"GET", "POST", "HEAD"}
52
+
53
+
54
+ def _compute_asset_version() -> str:
55
+ h = hashlib.sha256()
56
+ for name in ("index.html", "styles.css", "app.js"):
57
+ p = STATIC_DIR / name
58
+ if p.exists():
59
+ h.update(p.read_bytes())
60
+ return h.hexdigest()[:10]
61
+
62
+
63
+ ASSET_VERSION = _compute_asset_version()
64
+
65
+
66
+ # Ephemeral per-instance CSRF token for direct API fallback calls (never hardcoded or logged)
67
+ # TODO(security): Public read-only demo Space relies on Hugging Face Spaces ZeroGPU X-IP-Token quotas; add OAuth if user accounts are added.
68
+ def _init_csrf_secret() -> str:
69
+ env_tok = os.getenv("CELLGEMMA_CSRF_SECRET")
70
+ if env_tok and len(env_tok) >= 32:
71
+ return env_tok
72
+ return secrets.token_hex(32)
73
+
74
+
75
+ SESSION_CSRF_TOKEN = _init_csrf_secret()
76
+ _rate_buckets: dict[str, collections.deque[float]] = collections.defaultdict(collections.deque)
77
+
78
+ # Instantiate global CellGemma engine on main thread (registers CUDA tensors before launch on ZeroGPU)
79
+ engine = CellGemmaEngine()
80
+ if not IS_ZEROGPU and engine.device in ("cuda", "mps"):
81
+ logger.info("Pre-warming CellGemma E4B weights in background on %s ...", engine.device)
82
+ engine.start_background_preload()
83
+
84
+
85
+ class PredictRequest(BaseModel):
86
+ dataset: Literal["tahoe", "k562"]
87
+ cell_idx: int = Field(default=0, ge=0, le=99)
88
+ kind: Literal["drug", "crispr"]
89
+ drug_name: str = Field(default="Custom Compound", max_length=60)
90
+ smiles: str = Field(default="", max_length=200)
91
+ concentration_um: float = Field(default=0.5, ge=0.001, le=100.0)
92
+ gene: str = Field(default="", max_length=20)
93
+ max_new_tokens: int = Field(default=180, ge=32, le=1024)
94
+ temperature: float = Field(default=0.0, ge=0.0, le=1.5)
95
+
96
+
97
+ @spaces.GPU(duration=60)
98
+ def predict_zero_gpu(req_json: str) -> Iterator[str]:
99
+ """ZeroGPU worker generator streaming Stage 1 gene tokens and Stage 2 expression deltas."""
100
+ try:
101
+ raw = json.loads(req_json or "{}")
102
+ req = PredictRequest.model_validate(raw)
103
+ except Exception:
104
+ yield json.dumps({"seq": 1, "type": "error", "message": "Invalid perturbation input parameters."})
105
+ return
106
+
107
+ seq = 0
108
+ try:
109
+ for event in engine.stream_predict(
110
+ dataset=req.dataset,
111
+ cell_idx=req.cell_idx,
112
+ kind=req.kind,
113
+ drug_name=req.drug_name,
114
+ smiles=req.smiles,
115
+ concentration_um=req.concentration_um,
116
+ gene=req.gene,
117
+ max_new_tokens=req.max_new_tokens,
118
+ temperature=req.temperature,
119
+ ):
120
+ seq += 1
121
+ payload = dict(event)
122
+ payload["seq"] = seq
123
+ yield json.dumps(payload)
124
+ except ValueError as exc:
125
+ seq += 1
126
+ yield json.dumps({"seq": seq, "type": "error", "message": str(exc)})
127
+ except Exception:
128
+ logger.exception("Error during ZeroGPU streaming prediction")
129
+ seq += 1
130
+ yield json.dumps({"seq": seq, "type": "error", "message": "Inference failed on GPU worker."})
131
+
132
+
133
+ def _is_same_host_origin(origin: str, host_hdr: str) -> bool:
134
+ if not origin:
135
+ return True
136
+ parsed = urllib.parse.urlparse(origin)
137
+ if parsed.scheme not in ("http", "https") or not parsed.netloc:
138
+ return False
139
+ origin_host = parsed.netloc.split(":", 1)[0].strip().lower()
140
+ req_host = (host_hdr or "").split(":", 1)[0].strip().lower()
141
+ if origin_host in ("127.0.0.1", "localhost") and req_host in ("127.0.0.1", "localhost"):
142
+ return True
143
+ return bool(req_host and secrets.compare_digest(origin_host, req_host))
144
+
145
+
146
+ def _client_key(request: Request) -> str:
147
+ fwd = (request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip()
148
+ if fwd:
149
+ return fwd
150
+ return request.client.host if request.client else "127.0.0.1"
151
+
152
+
153
+ class _StudioSecurityMiddleware(BaseHTTPMiddleware):
154
+ """Enforces method allow-list, API rate limits, CSRF checks, and CSP headers."""
155
+
156
+ async def dispatch(self, request: Request, call_next):
157
+ if request.method not in ALLOWED_METHODS:
158
+ return JSONResponse({"error": "Method not allowed."}, status_code=405)
159
+
160
+ path = request.url.path
161
+ is_studio_or_api = (
162
+ path == "/studio"
163
+ or path.startswith("/api/")
164
+ or path.startswith("/studio_static/")
165
+ )
166
+
167
+ if path.startswith("/api/"):
168
+ now = time.monotonic()
169
+ bucket = _rate_buckets[f"{_client_key(request)}:{request.method}"]
170
+ while bucket and now - bucket[0] > 60.0:
171
+ bucket.popleft()
172
+ limit = 30 if request.method == "POST" else 240
173
+ if len(bucket) >= limit:
174
+ return JSONResponse({"error": "Rate limit exceeded. Please wait briefly."}, status_code=429)
175
+ bucket.append(now)
176
+
177
+ if request.method == "POST":
178
+ origin = request.headers.get("origin", "")
179
+ host_hdr = request.headers.get("host", "")
180
+ if not _is_same_host_origin(origin, host_hdr):
181
+ return JSONResponse({"error": "Forbidden origin."}, status_code=403)
182
+ csrf_hdr = request.headers.get("x-csrf-token", "")
183
+ if not csrf_hdr or not secrets.compare_digest(csrf_hdr, SESSION_CSRF_TOKEN):
184
+ return JSONResponse({"error": "Invalid or missing security token."}, status_code=403)
185
+
186
+ response = await call_next(request)
187
+
188
+ response.headers["X-Content-Type-Options"] = "nosniff"
189
+ response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
190
+ response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
191
+
192
+ if is_studio_or_api:
193
+ response.headers["Content-Security-Policy"] = (
194
+ "default-src 'self'; "
195
+ "script-src 'self'; "
196
+ "style-src 'self' https://fonts.googleapis.com; "
197
+ "img-src 'self' data:; "
198
+ "connect-src 'self'; "
199
+ "font-src 'self' https://fonts.gstatic.com; "
200
+ "object-src 'none'; "
201
+ "base-uri 'self'; "
202
+ "frame-ancestors 'self' https://huggingface.co https://*.hf.space https://gemma.ai https://*.pages.github.io"
203
+ )
204
+ if path.startswith("/api/") and "Cache-Control" not in response.headers:
205
+ response.headers["Cache-Control"] = "no-store"
206
+ elif (path == "/studio" or path.startswith("/studio_static/")) and "Cache-Control" not in response.headers:
207
+ response.headers["Cache-Control"] = "no-cache, must-revalidate"
208
+ else:
209
+ response.headers["Content-Security-Policy"] = (
210
+ "frame-ancestors 'self' https://huggingface.co https://*.hf.space https://gemma.ai https://*.pages.github.io"
211
+ )
212
+
213
+ return response
214
+
215
+
216
+ def mount_studio_routes(app: FastAPI) -> None:
217
+ """Attaches the Perturbation Studio UI and lightweight CPU helper endpoints onto Gradio's FastAPI app."""
218
+ app.mount("/studio_static", StaticFiles(directory=str(STATIC_DIR)), name="studio_static")
219
+
220
+ raw_index_html = (STATIC_DIR / "index.html").read_text(encoding="utf-8")
221
+ versioned_index_html = raw_index_html.replace(
222
+ "/studio_static/styles.css", f"/studio_static/styles.css?v={ASSET_VERSION}"
223
+ ).replace(
224
+ "/studio_static/app.js", f"/studio_static/app.js?v={ASSET_VERSION}"
225
+ )
226
+
227
+ @app.get("/studio")
228
+ async def studio_index() -> HTMLResponse:
229
+ return HTMLResponse(
230
+ content=versioned_index_html,
231
+ headers={"Cache-Control": "no-store, must-revalidate"},
232
+ )
233
+
234
+ @app.get("/api/model_status")
235
+ async def model_status() -> JSONResponse:
236
+ return JSONResponse(engine.get_model_status())
237
+
238
+ @app.get("/api/bootstrap")
239
+ async def bootstrap() -> JSONResponse:
240
+ sample_genes = sorted(list(engine.kg.keys()))
241
+ featured_genes = [
242
+ "MYC", "DNMT1", "TP53", "KRAS", "EGFR", "GATA1",
243
+ "BRCA1", "EZH2", "HDAC1", "STAT3", "BCL2", "CDK4",
244
+ ]
245
+ return JSONResponse({
246
+ "csrf_token": SESSION_CSRF_TOKEN,
247
+ "device": engine.device,
248
+ "dtype": str(engine.dtype).replace("torch.", ""),
249
+ "model_loaded": engine._model is not None,
250
+ "model_status": engine.get_model_status(),
251
+ "presets": CURATED_PRESETS,
252
+ "featured_genes": [g for g in featured_genes if g in engine.kg],
253
+ "total_kg_genes": len(sample_genes),
254
+ "baseline_cells": {
255
+ ds: engine.get_cell_baseline_summary(ds, 0)
256
+ for ds in ("tahoe", "k562")
257
+ },
258
+ })
259
+
260
+ @app.get("/api/cell_summary")
261
+ async def get_cell_summary(
262
+ dataset: Literal["tahoe", "k562"] = Query(default="tahoe"),
263
+ cell_idx: int = Query(default=0, ge=0, le=99),
264
+ ) -> JSONResponse:
265
+ try:
266
+ return JSONResponse(engine.get_cell_baseline_summary(dataset, cell_idx))
267
+ except ValueError as exc:
268
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
269
+
270
+ @app.get("/api/molecule")
271
+ async def get_molecule(smiles: str = Query(..., min_length=1, max_length=200)) -> JSONResponse:
272
+ try:
273
+ return JSONResponse(parse_smiles_2d(smiles))
274
+ except ValueError as exc:
275
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
276
+
277
+ @app.get("/api/gene_graph")
278
+ async def get_gene_graph(gene: str = Query(..., min_length=1, max_length=20)) -> JSONResponse:
279
+ try:
280
+ return JSONResponse(engine.get_gene_graph(gene))
281
+ except ValueError as exc:
282
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
283
+
284
+ @app.post("/api/predict_stream")
285
+ async def predict_stream(req: PredictRequest):
286
+ try:
287
+ engine.prepare_cell_and_prompt(
288
+ dataset=req.dataset,
289
+ cell_idx=req.cell_idx,
290
+ kind=req.kind,
291
+ drug_name=req.drug_name,
292
+ smiles=req.smiles,
293
+ concentration_um=req.concentration_um,
294
+ gene=req.gene,
295
+ )
296
+ except ValueError as exc:
297
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
298
+
299
+ def _ndjson_gen():
300
+ for chunk in predict_zero_gpu(req.model_dump_json()):
301
+ yield chunk + "\n"
302
+
303
+ return StreamingResponse(
304
+ _ndjson_gen(),
305
+ media_type="application/x-ndjson",
306
+ headers={
307
+ "X-Accel-Buffering": "no",
308
+ "Cache-Control": "no-cache, no-transform",
309
+ },
310
+ )
311
+
312
+
313
+ SHELL_CSS = """
314
+ html, body {
315
+ margin: 0 !important;
316
+ padding: 0 !important;
317
+ width: 100% !important;
318
+ height: 100% !important;
319
+ overflow: hidden !important;
320
+ background: #030711 !important;
321
+ }
322
+ .gradio-container {
323
+ margin: 0 !important;
324
+ padding: 0 !important;
325
+ max-width: 100% !important;
326
+ width: 100vw !important;
327
+ height: 100dvh !important;
328
+ overflow: hidden !important;
329
+ background: #030711 !important;
330
+ }
331
+ footer {
332
+ display: none !important;
333
+ }
334
+ #cellgemma-studio-shell {
335
+ position: fixed;
336
+ inset: 0;
337
+ width: 100vw;
338
+ height: 100dvh;
339
+ margin: 0;
340
+ padding: 0;
341
+ z-index: 1;
342
+ }
343
+ #cellgemma-studio-frame {
344
+ width: 100%;
345
+ height: 100%;
346
+ border: 0;
347
+ display: block;
348
+ }
349
+ .toast-wrap {
350
+ z-index: 9999 !important;
351
+ }
352
+ """
353
+
354
+ SHELL_JS = """
355
+ () => {
356
+ window.__cgPendingPayload = "{}";
357
+ window.__triggerCellGemmaZeroGPU = (payloadJsonStr) => {
358
+ window.__cgPendingPayload = payloadJsonStr || "{}";
359
+ const btn = document.querySelector("#cg-gpu-btn button, button#cg-gpu-btn");
360
+ if (!btn) return false;
361
+ btn.click();
362
+ return true;
363
+ };
364
+ window.__cancelCellGemmaZeroGPU = () => {
365
+ const btn = document.querySelector("#cg-gpu-cancel button, button#cg-gpu-cancel");
366
+ if (btn) btn.click();
367
+ };
368
+ }
369
+ """
370
+
371
+
372
+ def create_demo() -> gr.Blocks:
373
+ with gr.Blocks(
374
+ title="CellGemma · Single-Cell Perturbation Studio",
375
+ fill_height=True,
376
+ fill_width=True,
377
+ analytics_enabled=False,
378
+ ) as demo:
379
+ gr.HTML(
380
+ value=(
381
+ '<div id="cellgemma-studio-shell">'
382
+ f'<iframe id="cellgemma-studio-frame" src="/studio?v={ASSET_VERSION}" '
383
+ 'title="CellGemma Single-Cell Perturbation Studio"></iframe>'
384
+ "</div>"
385
+ ),
386
+ apply_default_css=False,
387
+ container=False,
388
+ padding=False,
389
+ )
390
+
391
+ # Hidden Gradio event bridge so ZeroGPU X-IP-Token quota headers negotiate natively
392
+ gpu_req = gr.Textbox(value="", visible="hidden", elem_id="cg-gpu-req")
393
+ gpu_out = gr.Textbox(value="", visible="hidden", elem_id="cg-gpu-out")
394
+ gpu_btn = gr.Button("Run", visible="hidden", elem_id="cg-gpu-btn")
395
+ gpu_cancel = gr.Button("Cancel", visible="hidden", elem_id="cg-gpu-cancel")
396
+
397
+ run_ev = gpu_btn.click(
398
+ fn=predict_zero_gpu,
399
+ inputs=[gpu_req],
400
+ outputs=[gpu_out],
401
+ js="() => window.__cgPendingPayload || '{}'",
402
+ show_progress="hidden",
403
+ api_name="predict",
404
+ )
405
+ gpu_out.change(
406
+ fn=None,
407
+ inputs=[gpu_out],
408
+ outputs=[],
409
+ js=(
410
+ "(val) => {"
411
+ " const f = document.getElementById('cellgemma-studio-frame');"
412
+ " if (val && f && f.contentWindow && f.contentWindow.__onZeroGpuStream) {"
413
+ " f.contentWindow.__onZeroGpuStream(val);"
414
+ " }"
415
+ "}"
416
+ ),
417
+ trigger_mode="multiple",
418
+ show_progress="hidden",
419
+ )
420
+ run_ev.then(
421
+ fn=None,
422
+ inputs=[gpu_out],
423
+ outputs=[],
424
+ js=(
425
+ "(val) => {"
426
+ " const f = document.getElementById('cellgemma-studio-frame');"
427
+ " if (f && f.contentWindow && f.contentWindow.__onZeroGpuDone) {"
428
+ " f.contentWindow.__onZeroGpuDone(val);"
429
+ " }"
430
+ "}"
431
+ ),
432
+ show_progress="hidden",
433
+ )
434
+ gpu_cancel.click(
435
+ fn=None,
436
+ inputs=None,
437
+ outputs=None,
438
+ cancels=[run_ev],
439
+ show_progress="hidden",
440
+ )
441
+
442
+ return demo
443
+
444
+
445
+ if __name__ == "__main__":
446
+ is_hf_space = bool(os.environ.get("SPACE_ID"))
447
+ default_host = "0.0.0.0" if is_hf_space else "127.0.0.1"
448
+ bind_host = os.environ.get("GRADIO_SERVER_NAME", default_host)
449
+ bind_port = int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", "7860")))
450
+
451
+ demo_blocks = create_demo()
452
+ fastapi_app, _, _ = demo_blocks.launch(
453
+ server_name=bind_host,
454
+ server_port=bind_port,
455
+ ssr_mode=False,
456
+ prevent_thread_lock=True,
457
+ footer_links=[],
458
+ show_error=True,
459
+ app_kwargs={"middleware": [Middleware(_StudioSecurityMiddleware)]},
460
+ css=SHELL_CSS,
461
+ js=SHELL_JS,
462
+ )
463
+ mount_studio_routes(fastapi_app)
464
+ demo_blocks.block_thread()
engine.py ADDED
@@ -0,0 +1,1133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core CellGemma Two-Stage Single-Cell Inference & 3D Molecular/Network Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import os
8
+ import queue
9
+ import re
10
+ import threading
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any, Iterator
14
+
15
+ import numpy as np
16
+ import safetensors.torch
17
+ import torch
18
+ from huggingface_hub import hf_hub_download
19
+ from rdkit import Chem
20
+ from rdkit.Chem import AllChem, Descriptors, rdDepictor, rdMolDescriptors
21
+ from torch import nn
22
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
23
+
24
+ DEFAULT_MODEL_ID = os.environ.get("CELLGEMMA_MODEL_ID", "google/cellgemma-e4b")
25
+ IS_ZEROGPU = os.environ.get("SPACES_ZERO_GPU") == "1"
26
+
27
+ PREAMBLE = (
28
+ "Examine how the single-cell sample, captured in 'Source:', responds "
29
+ "transcriptionally to the perturbation under the stated experimental "
30
+ "conditions. You are given the dataset-wide average prediction in 'Mean "
31
+ "Global prediction:' and you need to predict the residual from that mean "
32
+ "to the true final expression."
33
+ )
34
+
35
+ SMILES_ALLOW_RE = re.compile(r"^[A-Za-z0-9@+\-\[\]\(\)=#$%/\\.,]{1,200}$")
36
+ GENE_ALLOW_RE = re.compile(r"^[A-Z0-9\-]{1,20}$")
37
+
38
+ # Single-cell showcase presets grounded in controls_sample.json
39
+ CURATED_PRESETS: list[dict[str, Any]] = [
40
+ {
41
+ "id": "panobinostat",
42
+ "dataset": "tahoe",
43
+ "kind": "drug",
44
+ "name": "Panobinostat",
45
+ "role": "HDAC Inhibitor · Unpacks DNA & Raises Surface Flags",
46
+ "smiles": "Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1",
47
+ "concentration_um": 0.5,
48
+ "cell_idx": 0,
49
+ "summary": "Relaxes tightly packed chromatin in A549 lung-cancer cells, turning up histones (+H1-0, +H3-3B) and 'eat-me' surface flag +CALR while turning down p53 brake -MDM2.",
50
+ },
51
+ {
52
+ "id": "dasatinib",
53
+ "dataset": "tahoe",
54
+ "kind": "drug",
55
+ "name": "Dasatinib",
56
+ "role": "Kinase Inhibitor · Blocks Invasion Receptors",
57
+ "smiles": "Cc1nc(Nc2ncc(C(=O)Nc3c(C)cccc3Cl)s2)cc(N2CCN(CCO)CC2)n1",
58
+ "concentration_um": 0.5,
59
+ "cell_idx": 0,
60
+ "summary": "Inhibits SRC/ABL/EPHA2 kinases in A549 lung-cancer cells, turning down invasion & growth receptors (-LRP1, -IGFBP3) while remodeling structural filaments (+VIM, +PLOD2).",
61
+ },
62
+ {
63
+ "id": "trametinib",
64
+ "dataset": "tahoe",
65
+ "kind": "drug",
66
+ "name": "Trametinib",
67
+ "role": "MEK1/2 Inhibitor · Cuts MAPK Growth Relay",
68
+ "smiles": "CC(=O)Nc1cccc(-n2c(=O)n(C3CC3)c(=O)c3c(Nc4ccc(I)cc4F)n(C)c(=O)c(C)c32)c1",
69
+ "concentration_um": 0.5,
70
+ "cell_idx": 0,
71
+ "summary": "Blocks MEK1/2 signaling downstream of KRAS in A549 cells, suppressing migration/MAPK feedback genes (-ARHGAP26, -LRP1, -DUSP5) and boosting redox defense (+TXNRD1).",
72
+ },
73
+ {
74
+ "id": "myc_kd",
75
+ "dataset": "k562",
76
+ "kind": "crispr",
77
+ "name": "Mute MYC",
78
+ "role": "Master Growth Oncogene · Collapses Ribosome Factories",
79
+ "gene": "MYC",
80
+ "concentration_um": 1.0,
81
+ "cell_idx": 0,
82
+ "summary": "CRISPRi knockdown of master growth switch MYC in K562 leukemia cells shuts down ribosome & polyamine factories (-C1QBP, -SRM, -WDR43, -RRP1B) and switches on red-blood-cell maturation (+GYPB, +HBZ, +ALAS2, +HBG2).",
83
+ },
84
+ {
85
+ "id": "dnmt1_kd",
86
+ "dataset": "k562",
87
+ "kind": "crispr",
88
+ "name": "Mute DNMT1",
89
+ "role": "DNA Methylation Lock · Lifts Epigenetic Silencing",
90
+ "gene": "DNMT1",
91
+ "concentration_um": 1.0,
92
+ "cell_idx": 0,
93
+ "summary": "CRISPRi knockdown of DNA methyltransferase DNMT1 lifts epigenetic silencing, exposing surface & secreted proteins (+SLC7A8, +LGALS1, +MDK) while suppressing nucleolar assembly (-NOLC1, -MRTO4).",
94
+ },
95
+ ]
96
+
97
+ # Subcellular location ("surface" | "nucleus" | "cytoplasm"), plain-English nickname, & explanation
98
+ GENE_ANNOTATIONS: dict[str, tuple[str, str, str]] = {
99
+ # Surface receptors, adhesion molecules, transporters & immune flags
100
+ "CALR": ("surface", "Calreticulin 'Eat-Me' Flag", "Surface chaperone that flags stressed tumor cells for immune engulfment."),
101
+ "B2M": ("surface", "MHC-I Antigen Presentation", "Essential MHC Class I subunit enabling T-cells to inspect tumor antigens."),
102
+ "GPNMB": ("surface", "CAR-T Surface Beacon", "Transmembrane glycoprotein targeted by solid-tumor CAR-T immunotherapies."),
103
+ "MAGEA10": ("surface", "Cancer-Testis Immune Antigen", "Normally silent germline antigen unmasked on demethylated tumor cells."),
104
+ "PAGE5": ("surface", "Unmasked Tumor Antigen", "Cancer-testis antigen awakened when DNA methylation locks are removed."),
105
+ "GYPB": ("surface", "Glycophorin B Red-Cell Coat", "Major red-blood-cell membrane coat protein induced as K562 matures."),
106
+ "GYPC": ("surface", "Glycophorin C Membrane Coat", "Erythroid plasma-membrane glycoprotein stabilizing mature red cells."),
107
+ "LGALS1": ("surface", "Galectin-1 Surface Lectin", "Cell-surface carbohydrate-binding protein remodeled during lineage shifts."),
108
+ "MDK": ("surface", "Midkine Secreted Signal", "Secreted growth/immune signaling factor induced upon epigenetic remodeling."),
109
+ "SLC7A8": ("surface", "LAT2 Surface Transporter", "Plasma-membrane neutral amino-acid channel awakened after demethylation."),
110
+ "AQP3": ("surface", "Aquaporin-3 Water Channel", "Cell-membrane water/glycerol pore upregulated during differentiation."),
111
+ "CAVIN1": ("surface", "Caveolae Membrane Sculptor", "Stabilizes plasma-membrane signaling pockets under MEK blockade."),
112
+ "AREG": ("surface", "Amphiregulin EGFR Ligand", "Secreted cell-surface growth-factor feedback signal."),
113
+ "LRP1": ("surface", "LRP1 Invasion Receptor", "Large cell-surface endocytic & migration receptor suppressed by kinase blockade."),
114
+ "PTPRJ": ("surface", "DEP-1 Surface Phosphatase", "Transmembrane receptor tyrosine phosphatase remodeled at cell junctions."),
115
+ "CA12": ("surface", "Hypoxia Acid-Shield (CA12)", "Cell-surface carbonic anhydrase helping tumor cells survive acidic niches."),
116
+ "SERPINE1": ("surface", "PAI-1 Matrix Invasion Shield", "Secreted adhesion & extracellular matrix regulator driving tumor migration."),
117
+ "IGFBP3": ("surface", "IGF Growth-Factor Carrier", "Extracellular growth-factor binding protein suppressed by kinase inhibition."),
118
+ "STC1": ("surface", "Stanniocalcin-1 Secreted Signal", "Secreted calcium/hypoxia survival hormone downregulated by MEK inhibition."),
119
+ "ADAM9": ("surface", "ADAM9 Surface Sheddase", "Membrane metalloprotease remodeling cell-surface receptors."),
120
+ "MYOF": ("surface", "Myoferlin Membrane Repair", "Plasma-membrane repair protein induced under signaling stress."),
121
+ "EPHA2": ("surface", "EPHA2 Surface Kinase", "Ephrin receptor tyrosine kinase regulating adhesion and surface antigen levels."),
122
+ "EGFR": ("surface", "EGFR Growth Receptor", "Transmembrane growth-factor antenna driving epithelial proliferation."),
123
+ "ITGA2": ("surface", "Integrin Alpha-2 Hook", "Surface collagen-adhesion receptor downregulated when MAPK signaling drops."),
124
+ "ICAM1": ("surface", "ICAM-1 Immune Docking Velcro", "Adhesion ligand stabilizing physical contact with immune T-cells."),
125
+ "ANXA1": ("surface", "Annexin A1 Membrane Signal", "Phospholipid-binding surface modulator induced during differentiation."),
126
+ "SEMA4B": ("surface", "Semaphorin-4B Surface Cue", "Transmembrane guidance receptor remodeled under Src/RTK kinase blockade."),
127
+
128
+ # Nuclear chromatin, histones, transcription factors & nucleolar ribosome assembly
129
+ "H1-0": ("nucleus", "Linker Histone H1.0", "Terminal-differentiation histone induced when HDAC inhibitors unpack DNA."),
130
+ "H3-3B": ("nucleus", "Active Histone H3.3B", "Replacement histone loaded into newly opened, active DNA regions."),
131
+ "H1-2": ("nucleus", "Linker Histone H1.2", "Nuclear chromatin-compaction histone remodeled upon cell-cycle exit."),
132
+ "H1-4": ("nucleus", "Replication Histone H1.4", "S-phase chromatin linker downregulated as rapid division slows."),
133
+ "NAP1L1": ("nucleus", "Histone Chaperone NAP1L1", "Shuttles histones into the nucleus to assemble nucleosomes."),
134
+ "SMAD3": ("nucleus", "TGF-Beta Nuclear Regulator", "Transcription factor driving pro-tumor mesenchymal & survival programs."),
135
+ "MDM2": ("nucleus", "p53 Suppressor Brake (MDM2)", "Destroys tumor-suppressor p53; turning MDM2 down unleashes p53 checkpoints."),
136
+ "NRIP1": ("nucleus", "Nuclear Receptor Co-Repressor", "Transcriptional co-regulator modulating hormone and metabolic genes."),
137
+ "CDKN1A": ("nucleus", "p21 Cell-Division Brake", "Directly locks nuclear cyclin-CDK motors to halt tumor cell division."),
138
+ "GADD45A": ("nucleus", "DNA Stress Arrest Sensor", "Nuclear checkpoint protein induced when MYC proliferation stops."),
139
+ "CCND3": ("nucleus", "Cyclin D3 Lineage Switch", "Coordinates final erythroid maturation divisions before growth exit."),
140
+ "MYC": ("nucleus", "MYC Master Growth Switch", "Oncogenic transcription factor driving cell division and ribosome production."),
141
+ "DNMT1": ("nucleus", "DNA Methylation Lock (DNMT1)", "Copies repressive methyl marks onto DNA to keep genes silenced."),
142
+ "USP34": ("nucleus", "Wnt Signaling Stabilizer", "Deubiquitinase sustaining nuclear beta-catenin survival transcription."),
143
+ "DUSP5": ("nucleus", "Nuclear ERK Phosphatase", "Direct nuclear feedback readout of active MAPK/ERK growth signaling; drops under MEK blockade."),
144
+ "ZC3H11A": ("nucleus", "Nuclear mRNA Export Complex", "TREX-associated nuclear export factor required under rapid growth."),
145
+ "ZCCHC7": ("nucleus", "Nuclear RNA Surveillance", "Nucleolar TRAMP-complex cofactor degrading aberrant RNAs."),
146
+ "MSI2": ("nucleus", "Stemness RNA Regulator MSI2", "Maintains undifferentiated leukemia/tumor stem-cell programs."),
147
+ "SF3B1": ("nucleus", "Core Spliceosome Hub SF3B1", "Nuclear pre-mRNA splicing factor downregulated as proliferation slows."),
148
+ "PTMA": ("nucleus", "Prothymosin-Alpha Chromatin", "MYC-regulated nuclear protein keeping proliferating chromatin accessible."),
149
+ "HMGA1": ("nucleus", "HMGA1 Chromatin Architect", "Oncogenic architectural DNA protein repressed when MYC is silenced."),
150
+ "RRP1B": ("nucleus", "Nucleolar rRNA Processor 1B", "Direct MYC target building 60S ribosomes inside the nucleolus."),
151
+ "WDR43": ("nucleus", "Small-Subunit Processome", "Essential nucleolar ribosome-assembly protein; collapses without MYC."),
152
+ "TSR1": ("nucleus", "40S Ribosome Maturation", "Nucleolar assembly factor suppressed when growth signaling drops."),
153
+ "MRTO4": ("nucleus", "60S Ribosome Stalk Loader", "Nuclear pre-60S ribosome assembly factor downregulated on demethylation."),
154
+ "NOLC1": ("nucleus", "Nucleolar Scaffold NOLC1", "Core nucleolar organizer linking RNA Pol I transcription to ribosome assembly."),
155
+ "NOP16": ("nucleus", "Nucleolar 60S Factor NOP16", "MYC-responsive nucleolar protein assembling large ribosomal subunits."),
156
+ "RRP9": ("nucleus", "U3 snoRNP Cleavage Factor", "Processes precursor rRNA inside the nucleolus."),
157
+ "SNU13": ("nucleus", "Box C/D snoRNP Core", "Essential nucleolar rRNA-modification & spliceosome protein."),
158
+ "EXOSC7": ("nucleus", "Nuclear RNA Exosome Core", "Trims ribosomal RNA precursors in rapidly dividing cells."),
159
+ "NCL": ("nucleus", "Nucleolin Ribosome Hub", "Major nucleolar protein driving rRNA synthesis in cancer cells."),
160
+ "NPM1": ("nucleus", "Nucleophosmin Growth Hub", "Central nucleolar chaperone shuttling ribosomal subunits."),
161
+ "DCTPP1": ("nucleus", "dCTP Nucleotide Sanitizer", "Maintains DNA replication nucleotide pools in dividing tumor cells."),
162
+ "GPATCH2L": ("nucleus", "G-Patch RNA Splicing Factor", "Nuclear G-patch domain cofactor partnering with RNA helicases during splicing."),
163
+
164
+ # Cytoplasmic chaperones, ribosomes, mitochondria, cytoskeleton & metabolism
165
+ "HSPA5": ("cytoplasm", "BiP ER Stress Chaperone", "Master endoplasmic-reticulum protein-folding sensor induced by HDAC inhibition."),
166
+ "HSP90B1": ("cytoplasm", "Grp94 Folding Chaperone", "ER chaperone folding secreted & immune-presentation proteins."),
167
+ "HSP90AA1": ("cytoplasm", "HSP90-Alpha Chaperone", "Stress-inducible cytosolic chaperone hyperacetylated by Panobinostat."),
168
+ "HSPD1": ("cytoplasm", "HSP60 Mitochondrial Chaperone", "Refolds proteins inside mitochondria under kinase/metabolic stress."),
169
+ "CRYAB": ("cytoplasm", "Alpha-B Crystallin Shield", "Small heat-shock protein stabilizing cytoskeleton filaments."),
170
+ "HBZ": ("cytoplasm", "Embryonic Zeta-Globin", "Oxygen-binding hemoglobin chain switched on as K562 matures into a red cell."),
171
+ "HBG2": ("cytoplasm", "Fetal Hemoglobin Gamma-2", "Hallmark oxygen-carrying hemoglobin induced during leukemia differentiation."),
172
+ "HBG1": ("cytoplasm", "Fetal Hemoglobin Gamma-1", "Beta-like globin chain marking K562 red-blood-cell maturation."),
173
+ "HBA1": ("cytoplasm", "Adult Hemoglobin Alpha-1", "Core alpha-globin subunit awakened upon erythroid differentiation."),
174
+ "ALAS2": ("cytoplasm", "Heme Synthesis Enzyme ALAS2", "Rate-limiting enzyme building red-blood-cell heme groups."),
175
+ "BLVRB": ("cytoplasm", "Biliverdin Reductase B", "Erythroid heme-metabolism enzyme tracking red-cell commitment."),
176
+ "SLC25A37": ("cytoplasm", "Mitoferrin-1 Iron Importer", "Pumps iron into mitochondria to build hemoglobin in maturing cells."),
177
+ "C1QBP": ("cytoplasm", "Mitochondrial Protein Factory", "Direct MYC target powering oxidative metabolism; drops sharply when MYC is muted."),
178
+ "SRM": ("cytoplasm", "Spermidine Synthase (MYC Target)", "Canonical MYC-driven polyamine growth enzyme; collapses on MYC knockdown."),
179
+ "PPA1": ("cytoplasm", "Pyrophosphatase Energy Driver", "Fuels biosynthetic reactions in rapidly dividing cells; drops without MYC."),
180
+ "EIF3B": ("cytoplasm", "Translation Initiation eIF3B", "Core scaffold starting mRNA-to-protein translation in growing cells."),
181
+ "MRPL15": ("cytoplasm", "Mitochondrial Ribosome L15", "Synthesizes respiratory proteins inside mitochondria; downregulated on MYC loss."),
182
+ "PABPC4": ("cytoplasm", "mRNA Poly(A) Stabilizer", "Binds mRNA tails to boost cytoplasmic translation."),
183
+ "TOMM40": ("cytoplasm", "Mitochondrial Import Pore", "Main outer-membrane channel importing proteins into mitochondria."),
184
+ "TXNIP": ("cytoplasm", "Glucose Uptake Brake TXNIP", "Blocks tumor sugar import (GLUT1) and restrains Warburg growth."),
185
+ "MYL6": ("cytoplasm", "Myosin Light Chain 6", "Regulatory actomyosin motor subunit remodeled as cell migration halts."),
186
+ "RND3": ("cytoplasm", "RhoE Cytoskeletal GTPase", "Antagonizes RhoA-ROCK stress fibers upon Src/tyrosine kinase inhibition."),
187
+ "RPL36": ("cytoplasm", "60S Ribosomal Subunit L36", "Large-subunit ribosomal protein rebalanced during translational arrest."),
188
+ "TXNRD1": ("cytoplasm", "Thioredoxin Reductase Antioxidant", "Protects cells against oxidative stress when MAPK signaling is blocked."),
189
+ "PLOD2": ("cytoplasm", "Collagen Cross-Linking Enzyme", "ER hydroxylase remodeled during tyrosine-kinase inhibition."),
190
+ "VIM": ("cytoplasm", "Vimentin Structural Filament", "Intermediate cytoskeleton filament reorganized as cell shape & motility shift."),
191
+ "MYH9": ("cytoplasm", "Myosin-IIA Contractile Motor", "Actin-bundling motor remodeling cell tension and morphology."),
192
+ "MYO10": ("cytoplasm", "Myosin-X Filopodia Motor", "Cytoskeletal motor reorganized upon MEK pathway inhibition."),
193
+ "ACTG1": ("cytoplasm", "Gamma-Actin Cytoskeleton", "Core structural microfilament remodeled during chromatin unpacking."),
194
+ "SPTBN1": ("cytoplasm", "Beta-II Spectrin Scaffold", "Membrane-cytoskeleton linker modulated alongside TGF-beta/SMAD3."),
195
+ "TRIO": ("cytoplasm", "Rho/Rac Cytoskeleton Relay", "Guanine exchange factor remodeling actin architecture."),
196
+ "ARHGAP26": ("cytoplasm", "FAK/Rho Migration Regulator", "Focal-adhesion GTPase regulator downregulated when MEK signaling stops."),
197
+ "ARHGAP5": ("cytoplasm", "p190-B RhoGAP Motility Relay", "Integrin/cytoskeleton signaling relay reduced under MEK blockade."),
198
+ "NPC1": ("cytoplasm", "Cholesterol Trafficking Pore", "Endosomal lipid transporter downregulated when growth kinases are blocked."),
199
+ "GRB10": ("cytoplasm", "Growth-Receptor Adapter GRB10", "Cytoplasmic signaling adapter linking RTK/mTOR pathways."),
200
+ "AKT3": ("cytoplasm", "AKT3 Survival Kinase", "Pro-survival PI3K-AKT kinase suppressed by Panobinostat."),
201
+ "SOD2": ("cytoplasm", "Mitochondrial Superoxide Shield", "Antioxidant enzyme inside mitochondria remodeled under HDAC inhibition."),
202
+ "ALDOA": ("cytoplasm", "Aldolase-A Glycolysis Enzyme", "Core sugar-splitting enzyme adjusted during metabolic reprogramming."),
203
+ "GPI": ("cytoplasm", "Glucose-6-Phosphate Isomerase", "Glycolytic metabolic enzyme modulated under MEK inhibition."),
204
+ "GBE1": ("cytoplasm", "Glycogen Branching Enzyme", "Hypoxia-linked energy-storage enzyme downregulated after HDAC inhibition."),
205
+ "DHRS2": ("cytoplasm", "Dicarbonyl Stress Reductase", "Detoxifies reactive lipid/carbonyl species in stressed cells."),
206
+ "FTL": ("cytoplasm", "Ferritin Light-Chain Iron Cage", "Safely stores intracellular iron to prevent oxidative damage."),
207
+ "ATG7": ("cytoplasm", "Autophagy Recycling Enzyme", "Core E1-like enzyme driving autophagosome membrane assembly."),
208
+ "RPS27A": ("cytoplasm", "40S Ribosome-Ubiquitin S27a", "Small ribosomal subunit protein coupling translation to ubiquitin."),
209
+ "RPS17": ("cytoplasm", "40S Ribosomal Subunit S17", "Cytoplasmic small ribosomal subunit protein."),
210
+ "RPS5": ("cytoplasm", "40S Ribosomal Subunit S5", "Decoding-center protein of the 40S ribosome."),
211
+ "RPS6": ("cytoplasm", "40S Ribosomal Sensor S6", "mTOR/S6K-regulated ribosomal subunit tracking growth state."),
212
+ "RPL7": ("cytoplasm", "60S Ribosomal Subunit L7", "Large ribosomal subunit protein assembling peptides."),
213
+ "RPL23": ("cytoplasm", "60S Ribosomal Subunit L23", "Large ribosomal protein that also regulates MDM2-p53 feedback."),
214
+ "RPL26": ("cytoplasm", "60S Ribosomal Subunit L26", "Large ribosomal subunit boosting p53 translation under stress."),
215
+ "RPL31": ("cytoplasm", "60S Ribosomal Subunit L31", "Polypeptide exit-tunnel subunit of the 60S ribosome."),
216
+ "MT-ND1": ("cytoplasm", "Mitochondrial Complex I (ND1)", "Core electron-transport chain subunit inside mitochondria."),
217
+ "MT-ND2": ("cytoplasm", "Mitochondrial Complex I (ND2)", "Proton-pumping respiratory subunit inside mitochondria."),
218
+ "FNDC3B": ("cytoplasm", "FNDC3B ER-Membrane Adhesion", "Endoplasmic-reticulum membrane regulator promoting cell migration and stress survival."),
219
+ "NDRG1": ("cytoplasm", "NDRG1 Stress/Hypoxia Sensor", "Iron- and stress-regulated protein modulating lipid trafficking and differentiation."),
220
+ "FTH1": ("cytoplasm", "Ferritin Heavy-Chain Iron Cage", "Ferroxidase iron-storage subunit preventing labile iron oxidative stress."),
221
+ "PABPC1": ("cytoplasm", "mRNA Poly(A) Translation Hub", "Cytoplasmic poly(A)-binding protein stabilizing mRNA tails for translation."),
222
+ "IRAK2": ("cytoplasm", "IRAK2 Innate Signaling Kinase", "Receptor-proximal kinase relaying stress and inflammatory NF-kB signals."),
223
+ "CRYM": ("cytoplasm", "Mu-Crystallin Thyroid Binder", "Cytosolic ketimine reductase & thyroid-hormone binding protein awakened on differentiation."),
224
+ "CPXM1": ("surface", "CPXM1 Matrix Metallocarboxypeptidase", "Secreted cell-surface/extraceullar matrix remodeling protein unmasked on demethylation."),
225
+ "NOSIP": ("cytoplasm", "NOSIP Ubiquitin E3 Modulator", "Regulates protein turnover and mitotic/erythropoietic maturation."),
226
+ "GAL": ("surface", "Galanin Secreted Neuropeptide", "Normally silent secreted signaling peptide unmasked when DNMT1 methylation drops."),
227
+ "PSAP": ("cytoplasm", "Prosaposin Lysosomal Factor", "Lysosomal sphingolipid activator & secreted trophic factor remodeled during differentiation."),
228
+ "SNRPD1": ("nucleus", "Spliceosome Core Sm-D1", "Essential Sm-ring core subunit of nuclear U1/U2/U4/U5 spliceosomal snRNPs; drops when MYC is muted."),
229
+ "SNRPD2": ("nucleus", "Spliceosome Core Sm-D2", "Nuclear Sm-ring subunit assembling spliceosomal snRNPs during active proliferation."),
230
+ "SNRPD3": ("nucleus", "Spliceosome Core Sm-D3", "Core nuclear spliceosome scaffold required for pre-mRNA splicing in dividing cells."),
231
+ "SNRPE": ("nucleus", "Spliceosome Core Sm-E", "Nuclear snRNP core ring protein downregulated upon cell-cycle exit."),
232
+ "SNRPF": ("nucleus", "Spliceosome Core Sm-F", "Nuclear pre-mRNA spliceosome assembly subunit."),
233
+ "SNRPG": ("nucleus", "Spliceosome Core Sm-G", "Heptameric Sm-ring nuclear splicing subunit."),
234
+ "HSP90AB1": ("cytoplasm", "HSP90-Beta Folding Chaperone", "Constitutive cytosolic chaperone stabilizing signaling kinases and steroid receptors."),
235
+ "HSPA8": ("cytoplasm", "HSC70 Constitutive Chaperone", "Housekeeping cytosolic clathrin-uncoating and protein-folding ATPase."),
236
+ "HSPE1": ("cytoplasm", "HSP10 Mitochondrial Co-Chaperone", "Partners with mitochondrial HSP60 to fold respiratory enzymes."),
237
+ "FKBP4": ("cytoplasm", "FKBP52 HSP90 Co-Chaperone", "MYC-regulated immunophilin co-chaperone assisting HSP90 protein complexes."),
238
+ "PPP1R15A": ("cytoplasm", "GADD34 Stress Phosphatase", "Integrated stress-response feedback subunit dephosphorylating eIF2-alpha."),
239
+ "DDIT3": ("nucleus", "CHOP ER-Stress Factor (DDIT3)", "Nuclear transcription factor activated by unfolded-protein and metabolic stress."),
240
+ "BTG1": ("nucleus", "BTG1 Anti-Proliferation Brake", "Nuclear mRNA deadenylation regulator enforcing cell-cycle exit and differentiation."),
241
+ "BTG2": ("nucleus", "BTG2 p53-Linked Growth Brake", "Anti-proliferative nuclear checkpoint cofactor halting G1/S progression."),
242
+ "ODC1": ("cytoplasm", "Ornithine Decarboxylase (MYC)", "Direct MYC-driven rate-limiting enzyme of polyamine synthesis for cell growth."),
243
+ "PAICS": ("cytoplasm", "Purine Synthesis Enzyme PAICS", "MYC-activated de novo purine nucleotide synthesis enzyme fueling DNA replication."),
244
+ "NME1": ("cytoplasm", "Nucleoside Kinase A (NME1)", "MYC-responsive nucleotide pool kinase synthesizing NTPs."),
245
+ "TFRC": ("surface", "CD71 Transferrin Iron Receptor", "Cell-surface iron-uptake receptor supporting heme synthesis and proliferation."),
246
+ "SLC3A2": ("surface", "CD98 Amino-Acid Transporter", "Plasma-membrane heavy chain importing essential amino acids for mTOR growth."),
247
+ "CD63": ("surface", "CD63 Tetraspanin Membrane Coat", "Cell-surface & endolysosomal tetraspanin scaffold remodeled during differentiation."),
248
+ "GP1BB": ("surface", "Glycoprotein Ib-Beta Receptor", "Myeloid/megakaryocytic lineage surface membrane glycoprotein."),
249
+ "MIF": ("surface", "MIF Secreted Cytokine Signal", "Secreted pro-survival cytokine modulated upon growth-factor or MYC blockade."),
250
+ "HNRNPA1": ("nucleus", "hnRNP-A1 Splicing Regulator", "MYC-regulated nuclear RNA-binding protein controlling alternative splicing."),
251
+ "HNRNPH1": ("nucleus", "hnRNP-H1 Nuclear RNA Splicer", "Nuclear G-quadruplex RNA splicing factor."),
252
+ "EGR1": ("nucleus", "EGR1 Immediate-Early Factor", "Nuclear zinc-finger transcription factor directly tracking MAPK/ERK signaling."),
253
+ "NFE2L1": ("nucleus", "NRF1 Proteasome Stress Sensor", "ER-tethered nuclear transcription factor maintaining proteasome homeostasis."),
254
+ "HMGA2": ("nucleus", "HMGA2 Chromatin Architect", "Architectural nuclear DNA-bending protein sustaining proliferative plasticity."),
255
+ "H2AZ1": ("nucleus", "Variant Histone H2A.Z", "Promoter-poising nuclear histone variant remodeled during transcriptional shifts."),
256
+ "H1-3": ("nucleus", "Linker Histone H1.3", "Replication-coupled nuclear chromatin compaction histone."),
257
+ "H1-5": ("nucleus", "Linker Histone H1.5", "Nuclear heterochromatin linker histone downregulated as division slows."),
258
+ "RANBP1": ("nucleus", "Ran-GTP Nuclear Transport", "Regulates nuclear-pore cargo import/export in proliferating cells."),
259
+ "ANP32B": ("nucleus", "Histone Chaperone ANP32B", "Nuclear chromatin assembly & mRNA export regulator."),
260
+ "ACTB": ("cytoplasm", "Beta-Actin Cytoskeleton", "Essential contractile microfilament driving cell shape and motility."),
261
+ "GAPDH": ("cytoplasm", "GAPDH Glycolytic Dehydrogenase", "Central cytoplasmic glycolysis enzyme coupling ATP production to redox state."),
262
+ "EEF2": ("cytoplasm", "Elongation Factor eEF2", "Ribosomal translocation GTPase driving polypeptide chain elongation."),
263
+ "EEF1A1": ("cytoplasm", "Elongation Factor eEF1A1", "Delivers aminoacyl-tRNAs to the ribosome during translation."),
264
+ "VDAC1": ("cytoplasm", "Mitochondrial Porin VDAC1", "Outer mitochondrial membrane metabolite and ATP channel."),
265
+ "PHB2": ("cytoplasm", "Prohibitin-2 Inner Mito Scaffold", "Stabilizes mitochondrial respiratory cristae and mitophagy signaling."),
266
+ "FABP5": ("cytoplasm", "Fatty-Acid Binding Protein 5", "Intracellular lipid chaperone fueling membrane synthesis."),
267
+ "S100A11": ("cytoplasm", "S100A11 Calcium Membrane Linker", "Calcium-sensing cytoskeletal & plasma-membrane repair adapter."),
268
+ "MT-CO1": ("cytoplasm", "Cytochrome c Oxidase I (CO1)", "Catalytic mitochondrial Complex IV respiratory subunit."),
269
+ "MT-CO3": ("cytoplasm", "Cytochrome c Oxidase III (CO3)", "Core mitochondrial Complex IV electron-transport subunit."),
270
+ "MT-ATP6": ("cytoplasm", "Mitochondrial ATP Synthase 6", "Proton-channel subunit driving mitochondrial ATP synthesis."),
271
+ "MT-CYB": ("cytoplasm", "Mitochondrial Cytochrome b", "Central Complex III electron-transfer subunit inside mitochondria."),
272
+ "MT-ND4": ("cytoplasm", "Mitochondrial Complex I (ND4)", "Proton-pumping NADH dehydrogenase subunit inside mitochondria."),
273
+ "MT-ND6": ("cytoplasm", "Mitochondrial Complex I (ND6)", "Essential membrane subunit of mitochondrial respiratory Complex I."),
274
+ }
275
+
276
+ _LOC_CODE_MAP = {"n": "nucleus", "s": "surface", "c": "cytoplasm"}
277
+
278
+
279
+ def _load_gene_catalog() -> dict[str, list[str]]:
280
+ """Loads the 19,881-gene HGNC/HPA compartment & protein-name lookup catalog."""
281
+ here = Path(__file__).resolve().parent
282
+ for candidate in (here / "gene_catalog.json", here.parent / "data" / "gene_catalog.json"):
283
+ if candidate.is_file():
284
+ try:
285
+ with open(candidate, encoding="utf-8") as f:
286
+ return json.load(f)
287
+ except Exception:
288
+ return {}
289
+ return {}
290
+
291
+
292
+ GENE_CATALOG: dict[str, list[str]] = _load_gene_catalog()
293
+
294
+
295
+ def _infer_fallback_annotation(gene: str, partners: list[str]) -> tuple[str, str, str]:
296
+ """Provides biologically grounded compartment & protein name for every HGNC symbol."""
297
+ partner_str = f" Interacts with {', '.join(partners[:4])}." if partners else ""
298
+ cat = GENE_CATALOG.get(gene)
299
+ if cat and len(cat) >= 2:
300
+ loc = _LOC_CODE_MAP.get(cat[0], "cytoplasm")
301
+ short_name = cat[1]
302
+ return (loc, short_name, f"{short_name} ({gene}).{partner_str}")
303
+ if gene.startswith(("RPL", "RPS")):
304
+ return ("cytoplasm", f"Ribosomal Subunit ({gene})", f"Cytoplasmic protein-synthesis ribosome component.{partner_str}")
305
+ if gene.startswith("MRPL") or gene.startswith("MRPS") or gene.startswith("MT-"):
306
+ return ("cytoplasm", f"Mitochondrial Energy Subunit ({gene})", f"Mitochondrial respiratory or translation subunit.{partner_str}")
307
+ if gene.startswith(("H1-", "H2A", "H2B", "H3-", "H4", "HIST", "ZNF", "POLR", "SNRP", "SF3", "SRSF", "HNRNP")):
308
+ return ("nucleus", f"Nuclear Splicing / Chromatin ({gene})", f"Nuclear RNA processing or chromatin regulator.{partner_str}")
309
+ if gene.startswith(("SLC", "CD", "HLA-", "ITG", "EPH", "FZD", "GPR", "TMEM", "ATP1", "AQP")):
310
+ return ("surface", f"Membrane Channel / Receptor ({gene})", f"Cell-surface transmembrane transport or signaling protein.{partner_str}")
311
+ if gene.startswith(("HSP", "DNAJ", "BAG")):
312
+ return ("cytoplasm", f"Protein-Folding Chaperone ({gene})", f"Cellular stress-response folding chaperone.{partner_str}")
313
+ return ("cytoplasm", f"{gene} Cellular Factor", f"Differentially expressed protein-coding gene ({gene}).{partner_str}")
314
+
315
+
316
+ class ExpressionDecoder(nn.Module):
317
+ """Dataset-specific Stage 2 MLP reconstructing continuous residual deltas."""
318
+
319
+ def __init__(self, input_dim: int, hidden_dims: list[int], max_exp_arg: float = 88.0):
320
+ super().__init__()
321
+ self.input_dim = input_dim
322
+ self.max_exp_arg = max_exp_arg
323
+ self.bn0 = nn.BatchNorm1d(input_dim + 1)
324
+ layers: list[nn.Module] = [self.bn0]
325
+ d = input_dim + 1
326
+ for h in hidden_dims:
327
+ layers += [nn.Linear(d, h), nn.ReLU()]
328
+ d = h
329
+ self.mlp = nn.Sequential(*layers, nn.Linear(d, 1))
330
+
331
+ def forward(self, features: torch.Tensor, control_expression: torch.Tensor) -> torch.Tensor:
332
+ eps = 1e-6
333
+ ctrl = control_expression.view(-1, 1)
334
+ x = self.mlp(torch.cat([features, ctrl], dim=1))
335
+ ctrl_safe = ctrl - torch.where(x >= 0, eps, -eps)
336
+ exp_term = (x / ctrl_safe).clamp(max=self.max_exp_arg)
337
+ neg_delta = ctrl_safe * (torch.exp(exp_term) - 1.0)
338
+ return torch.where(x > 0, x, neg_delta) + eps
339
+
340
+
341
+ def parse_smiles_2d(smiles: str, new_atom_start: int | None = None) -> dict[str, Any]:
342
+ """Validates SMILES, canonicalizes via RDKit, and computes 3D ETKDGv3/MMFF94 coordinates."""
343
+ cleaned = smiles.strip()
344
+ if not SMILES_ALLOW_RE.match(cleaned):
345
+ raise ValueError("Invalid characters or length in SMILES string.")
346
+ mol = Chem.MolFromSmiles(cleaned)
347
+ if mol is None or mol.GetNumAtoms() == 0 or mol.GetNumAtoms() > 120:
348
+ raise ValueError("Could not parse chemical SMILES into a valid molecule.")
349
+
350
+ canonical = Chem.MolToSmiles(mol, canonical=True)
351
+ mol_base = Chem.MolFromSmiles(canonical)
352
+ assert mol_base is not None
353
+
354
+ rdDepictor.Compute2DCoords(mol_base)
355
+ conf_2d = mol_base.GetConformer()
356
+ coords_3d: list[tuple[float, float, float]] = []
357
+
358
+ try:
359
+ mol_h = Chem.AddHs(Chem.MolFromSmiles(canonical))
360
+ params = AllChem.ETKDGv3()
361
+ params.randomSeed = 42
362
+ status = AllChem.EmbedMolecule(mol_h, params)
363
+ if status == 0:
364
+ AllChem.MMFFOptimizeMolecule(mol_h, maxIters=100)
365
+ mol_3d = Chem.RemoveHs(mol_h)
366
+ conf_3d = mol_3d.GetConformer()
367
+ for idx in range(mol_3d.GetNumAtoms()):
368
+ p = conf_3d.GetAtomPosition(idx)
369
+ coords_3d.append((float(p.x), float(p.y), float(p.z)))
370
+ except Exception:
371
+ coords_3d = []
372
+
373
+ if len(coords_3d) != mol_base.GetNumAtoms():
374
+ coords_3d = []
375
+ for idx in range(mol_base.GetNumAtoms()):
376
+ p = conf_2d.GetAtomPosition(idx)
377
+ coords_3d.append((float(p.x), float(-p.y), math.sin(idx * 0.9) * 0.25))
378
+
379
+ arr = np.array(coords_3d, dtype=np.float64)
380
+ arr -= arr.mean(axis=0, keepdims=True)
381
+ max_r = float(np.max(np.linalg.norm(arr, axis=1))) if len(arr) > 1 else 1.0
382
+ scale = 1.85 / max(1.0, max_r)
383
+ arr *= scale
384
+
385
+ nodes = []
386
+ for idx, atom in enumerate(mol_base.GetAtoms()):
387
+ p2 = conf_2d.GetAtomPosition(idx)
388
+ nodes.append({
389
+ "id": idx,
390
+ "elem": atom.GetSymbol(),
391
+ "x": round(float(arr[idx, 0]), 4),
392
+ "y": round(float(arr[idx, 1]), 4),
393
+ "z": round(float(arr[idx, 2]), 4),
394
+ "x2d": round(float(p2.x), 4),
395
+ "y2d": round(float(-p2.y), 4),
396
+ "aromatic": bool(atom.GetIsAromatic()),
397
+ "isNew": bool(new_atom_start is not None and idx >= new_atom_start),
398
+ })
399
+
400
+ edges = []
401
+ for bond in mol_base.GetBonds():
402
+ btype = bond.GetBondTypeAsDouble()
403
+ edges.append({
404
+ "a": bond.GetBeginAtomIdx(),
405
+ "b": bond.GetEndAtomIdx(),
406
+ "order": 2 if btype == 2.0 else (3 if btype == 3.0 else 1),
407
+ "aromatic": bool(bond.GetIsAromatic()),
408
+ })
409
+
410
+ return {
411
+ "mode": "drug",
412
+ "canonical_smiles": canonical,
413
+ "num_atoms": mol_base.GetNumHeavyAtoms(),
414
+ "mol_weight": round(float(Descriptors.MolWt(mol_base)), 1),
415
+ "num_rings": int(rdMolDescriptors.CalcNumRings(mol_base)),
416
+ "nodes": nodes,
417
+ "edges": edges,
418
+ }
419
+
420
+
421
+ class CellGemmaEngine:
422
+ """Manages single-cell controls, 3D molecular/network inputs, and live CellGemma inference."""
423
+
424
+ def __init__(self, model_id: str = DEFAULT_MODEL_ID):
425
+ self.model_id = model_id
426
+ self.hf_token = os.environ.get("HF_TOKEN") or None
427
+ self.device, self.dtype = self._select_device()
428
+ self._model: AutoModelForCausalLM | None = None
429
+ self._tokenizer: AutoTokenizer | None = None
430
+ self._model_lock = threading.Lock()
431
+ self._load_lock = threading.Lock()
432
+ self.model_load_state: str = "not_loaded"
433
+ self.model_load_started_at: float = 0.0
434
+ self.model_load_error: str = ""
435
+
436
+ self.controls_all: dict[str, Any] = {}
437
+ self.kg: dict[str, str] = {}
438
+ self.decoders: dict[str, tuple[ExpressionDecoder, dict[str, float]]] = {}
439
+ self.genes_by_ds: dict[str, list[str]] = {}
440
+ self.gene_to_idx_by_ds: dict[str, dict[str, int]] = {}
441
+
442
+ self._load_lightweight_assets()
443
+
444
+ # On Hugging Face ZeroGPU, weights MUST be loaded and moved .to("cuda")
445
+ # synchronously on the main thread before gr.Blocks.launch() packs tensors.
446
+ if IS_ZEROGPU:
447
+ self.ensure_model_loaded()
448
+
449
+ @staticmethod
450
+ def _select_device() -> tuple[str, torch.dtype]:
451
+ if IS_ZEROGPU or torch.cuda.is_available():
452
+ return "cuda", torch.bfloat16
453
+ if torch.backends.mps.is_available():
454
+ return "mps", torch.bfloat16
455
+ default_threads = min(32, max(4, (os.cpu_count() or 8) // 2))
456
+ cpu_threads = int(os.environ.get("CELLGEMMA_CPU_THREADS", str(default_threads)))
457
+ torch.set_num_threads(cpu_threads)
458
+ return "cpu", torch.float32
459
+
460
+ def _download_json(self, filename: str) -> Any:
461
+ path = hf_hub_download(self.model_id, filename, token=self.hf_token)
462
+ with open(path, encoding="utf-8") as f:
463
+ return json.load(f)
464
+
465
+ def _load_lightweight_assets(self) -> None:
466
+ """Loads controls_sample.json, kg_sentences.json, and Stage 2 decoders."""
467
+ self.controls_all = self._download_json("controls_sample.json")
468
+ self.kg = self._download_json("kg_sentences.json")
469
+
470
+ for ds in ("tahoe", "k562"):
471
+ cfg = self._download_json(f"decoders/{ds}/config.json")
472
+ dec = ExpressionDecoder(cfg["input_dim"], cfg["hidden_dims"])
473
+ weights_path = hf_hub_download(
474
+ self.model_id, f"decoders/{ds}/model.safetensors", token=self.hf_token
475
+ )
476
+ dec.load_state_dict(safetensors.torch.load_file(weights_path))
477
+ dec.eval()
478
+ raw_deltas = self._download_json(f"decoders/{ds}/mean_delta_global.json")
479
+ mean_deltas = {k.upper(): float(v) for k, v in raw_deltas.items()}
480
+ self.decoders[ds] = (dec, mean_deltas)
481
+
482
+ genes = [g.upper() for g in self.controls_all[ds]["genes"]]
483
+ self.genes_by_ds[ds] = genes
484
+ self.gene_to_idx_by_ds[ds] = {g: i for i, g in enumerate(genes)}
485
+
486
+ def get_cell_baseline_summary(self, dataset: str, cell_idx: int = 0) -> dict[str, Any]:
487
+ """Returns baseline expression facts for a single untreated control cell."""
488
+ if dataset not in ("tahoe", "k562"):
489
+ raise ValueError("Unknown dataset.")
490
+ cells = self.controls_all[dataset]["cells"]
491
+ idx = max(0, min(len(cells) - 1, int(cell_idx)))
492
+ vec = np.array(cells[idx]["expression"], dtype=np.float32)
493
+ genes = self.genes_by_ds[dataset]
494
+ nz_count = int(np.sum(vec > 0))
495
+ top_order = np.argsort(-vec)[:8]
496
+ top_list = [
497
+ {"gene": genes[int(i)], "expr": round(float(vec[int(i)]), 2)}
498
+ for i in top_order
499
+ if vec[int(i)] > 0
500
+ ]
501
+ cell_line = "A549 Lung Carcinoma" if dataset == "tahoe" else "K562 Chronic Myeloid Leukemia"
502
+ return {
503
+ "dataset": dataset,
504
+ "cell_idx": idx,
505
+ "cell_id": cells[idx]["cell_id"],
506
+ "cell_line": cell_line,
507
+ "total_genes": len(genes),
508
+ "expressed_genes": nz_count,
509
+ "top_baseline_genes": top_list,
510
+ }
511
+
512
+ def get_gene_graph(self, gene: str, max_spokes: int = 10) -> dict[str, Any]:
513
+ """Extracts STRING functional interaction spokes in 3D spherical coordinates."""
514
+ sym = gene.strip().upper()
515
+ if not GENE_ALLOW_RE.match(sym) or sym not in self.kg:
516
+ raise ValueError(f"Unknown human gene symbol: {sym}")
517
+
518
+ lines = self.kg[sym].strip().splitlines()
519
+ partners: list[str] = []
520
+ for line in lines[1:]:
521
+ parts = line.split()
522
+ if len(parts) >= 3 and parts[1] == "functional":
523
+ other = parts[2].upper()
524
+ if other != sym and other not in partners:
525
+ partners.append(other)
526
+ if len(partners) >= max_spokes:
527
+ break
528
+
529
+ nodes = [{"id": 0, "elem": sym, "x": 0.0, "y": 0.0, "z": 0.0, "isHub": True}]
530
+ edges = []
531
+ n = max(1, len(partners))
532
+ golden = math.pi * (3.0 - math.sqrt(5.0))
533
+ for idx, p_sym in enumerate(partners):
534
+ y_norm = 1.0 - (2.0 * (idx + 0.5) / n)
535
+ rad_xy = math.sqrt(max(0.0, 1.0 - y_norm * y_norm))
536
+ theta = golden * idx
537
+ r = 1.65
538
+ nodes.append({
539
+ "id": idx + 1,
540
+ "elem": p_sym,
541
+ "x": round(math.cos(theta) * rad_xy * r, 4),
542
+ "y": round(y_norm * r * 0.85, 4),
543
+ "z": round(math.sin(theta) * rad_xy * r, 4),
544
+ "isSpoke": True,
545
+ })
546
+ edges.append({"a": 0, "b": idx + 1, "order": 1, "dashed": True})
547
+
548
+ return {
549
+ "mode": "crispr",
550
+ "gene": sym,
551
+ "total_edges": max(0, len(lines) - 1),
552
+ "partners": partners,
553
+ "nodes": nodes,
554
+ "edges": edges,
555
+ }
556
+
557
+ def start_background_preload(self) -> None:
558
+ """Pre-warms CellGemma weights in the background on local GPU / MPS."""
559
+ if IS_ZEROGPU or self.model_load_state in ("loading", "ready"):
560
+ return
561
+ threading.Thread(target=self.ensure_model_loaded, daemon=True).start()
562
+
563
+ def get_model_status(self) -> dict[str, Any]:
564
+ elapsed = (
565
+ round(max(0.0, time.perf_counter() - self.model_load_started_at), 1)
566
+ if self.model_load_state == "loading" and self.model_load_started_at > 0
567
+ else 0.0
568
+ )
569
+ return {
570
+ "device": self.device,
571
+ "dtype": str(self.dtype).replace("torch.", ""),
572
+ "state": self.model_load_state,
573
+ "elapsed_s": elapsed,
574
+ "error": self.model_load_error,
575
+ }
576
+
577
+ def ensure_model_loaded(self) -> None:
578
+ """Loads the Gemma4ForCausalLM checkpoint onto CUDA (ZeroGPU-safe), MPS, or CPU."""
579
+ if self._model is not None and self._tokenizer is not None:
580
+ self.model_load_state = "ready"
581
+ return
582
+ with self._load_lock:
583
+ if self._model is not None and self._tokenizer is not None:
584
+ self.model_load_state = "ready"
585
+ return
586
+ self.model_load_state = "loading"
587
+ self.model_load_started_at = time.perf_counter()
588
+ self.model_load_error = ""
589
+ try:
590
+ self._tokenizer = AutoTokenizer.from_pretrained(
591
+ self.model_id, token=self.hf_token
592
+ )
593
+ if self.device == "mps":
594
+ try:
595
+ model = AutoModelForCausalLM.from_pretrained(
596
+ self.model_id,
597
+ dtype=self.dtype,
598
+ low_cpu_mem_usage=True,
599
+ attn_implementation="eager",
600
+ token=self.hf_token,
601
+ ).to("mps")
602
+ except Exception:
603
+ self.dtype = torch.float16
604
+ model = AutoModelForCausalLM.from_pretrained(
605
+ self.model_id,
606
+ dtype=self.dtype,
607
+ low_cpu_mem_usage=True,
608
+ attn_implementation="eager",
609
+ token=self.hf_token,
610
+ ).to("mps")
611
+ elif self.device == "cuda":
612
+ # Move weights directly onto CUDA for ZeroGPU tensor packing
613
+ model = AutoModelForCausalLM.from_pretrained(
614
+ self.model_id,
615
+ dtype=self.dtype,
616
+ low_cpu_mem_usage=True,
617
+ token=self.hf_token,
618
+ ).to("cuda")
619
+ else:
620
+ model = AutoModelForCausalLM.from_pretrained(
621
+ self.model_id,
622
+ dtype=self.dtype,
623
+ low_cpu_mem_usage=True,
624
+ token=self.hf_token,
625
+ )
626
+ self._model = model.eval()
627
+ self.model_load_state = "ready"
628
+ except Exception as exc:
629
+ self.model_load_state = "error"
630
+ self.model_load_error = str(exc)
631
+ raise
632
+
633
+ def prepare_cell_and_prompt(
634
+ self,
635
+ dataset: str,
636
+ cell_idx: int,
637
+ kind: str,
638
+ drug_name: str = "",
639
+ smiles: str = "",
640
+ concentration_um: float = 0.5,
641
+ gene: str = "",
642
+ ) -> tuple[np.ndarray, np.ndarray, str, dict[str, Any]]:
643
+ """Builds Stage 1 prompt and returns (ctrl_expr, baseline, prompt, input_viz)."""
644
+ if dataset not in ("tahoe", "k562"):
645
+ raise ValueError("Dataset must be 'tahoe' or 'k562'.")
646
+ cells = self.controls_all[dataset]["cells"]
647
+ if not (0 <= cell_idx < len(cells)):
648
+ raise ValueError(f"cell_idx must be between 0 and {len(cells) - 1}.")
649
+
650
+ genes = self.genes_by_ds[dataset]
651
+ _, mean_deltas = self.decoders[dataset]
652
+ ctrl_expr = np.array(cells[cell_idx]["expression"], dtype=np.float32)
653
+ mean_vec = np.array([mean_deltas.get(g, 0.0) for g in genes], dtype=np.float32)
654
+ baseline = np.maximum(0.0, ctrl_expr + mean_vec)
655
+
656
+ if kind == "drug":
657
+ mol_info = parse_smiles_2d(smiles)
658
+ safe_name = re.sub(r"[^A-Za-z0-9 \-()_/+]", "", drug_name or "Custom Compound")[:60].strip()
659
+ perturbation_text = (
660
+ f"Drug name: {safe_name}\n"
661
+ f"Drug SMILES: {mol_info['canonical_smiles']}\n"
662
+ f"Concentration: {concentration_um} uM"
663
+ )
664
+ viz = mol_info
665
+ elif kind == "crispr":
666
+ sym = gene.strip().upper()
667
+ viz = self.get_gene_graph(sym)
668
+ kg_sent = self.kg[sym].strip()
669
+ perturbation_text = f"Gene knockdown: {kg_sent}"
670
+ else:
671
+ raise ValueError("kind must be 'drug' or 'crispr'.")
672
+
673
+ def top_k_genes(vec: np.ndarray, k: int = 1000) -> str:
674
+ order = np.argsort(vec)[::-1]
675
+ ranked = [genes[i] for i in order if vec[i] > 0][:k]
676
+ return " ".join(ranked)
677
+
678
+ prompt = (
679
+ f"{PREAMBLE}\n\n{perturbation_text}\n\n"
680
+ f"Source: {top_k_genes(ctrl_expr)}\n\n"
681
+ f"Mean Global prediction: {top_k_genes(baseline)}\n"
682
+ "Target: "
683
+ )
684
+ return ctrl_expr, baseline, prompt, viz
685
+
686
+ def _build_gene_entry(
687
+ self,
688
+ signed_sym: str,
689
+ g: str,
690
+ emit_order: int,
691
+ dir_rank: int,
692
+ ctrl_val: float,
693
+ base_val: float,
694
+ pred_val: float,
695
+ lfc_val: float,
696
+ res_val: float,
697
+ ) -> dict[str, Any]:
698
+ partners: list[str] = []
699
+ if g in self.kg:
700
+ for ln in self.kg[g].splitlines()[1:6]:
701
+ ps = ln.split()
702
+ if len(ps) >= 3:
703
+ partners.append(ps[2])
704
+ if g in GENE_ANNOTATIONS:
705
+ loc, nick, desc = GENE_ANNOTATIONS[g]
706
+ else:
707
+ loc, nick, desc = _infer_fallback_annotation(g, partners)
708
+
709
+ return {
710
+ "rank": emit_order,
711
+ "dir_rank": dir_rank,
712
+ "sym": signed_sym,
713
+ "gene": g,
714
+ "loc": loc,
715
+ "ctrl_expr": round(ctrl_val, 3),
716
+ "base_expr": round(base_val, 3),
717
+ "pred_expr": round(pred_val, 3),
718
+ "lfc": round(lfc_val, 4),
719
+ "residual": round(res_val, 4),
720
+ "mean_shift": round(base_val - ctrl_val, 4),
721
+ "nick": nick,
722
+ "desc": desc,
723
+ "partners": partners[:4],
724
+ "annotated": g in GENE_ANNOTATIONS,
725
+ }
726
+
727
+ def reconstruct_and_summarize(
728
+ self,
729
+ dataset: str,
730
+ cell_idx: int,
731
+ raw_text: str,
732
+ ctrl_expr: np.ndarray,
733
+ baseline: np.ndarray,
734
+ top_n_genes: int = 48,
735
+ is_truncated: bool = False,
736
+ include_all_genes: bool = False,
737
+ ) -> dict[str, Any]:
738
+ """Runs Stage 2 ExpressionDecoder on a single cell with balanced +UP and -DOWN rankings."""
739
+ g2i = self.gene_to_idx_by_ds[dataset]
740
+ decoder, _ = self.decoders[dataset]
741
+
742
+ up: list[str] = []
743
+ down: list[str] = []
744
+ interleaved: list[tuple[str, str, int]] = []
745
+ seen: set[str] = set()
746
+ for tok in raw_text.split():
747
+ if len(tok) < 2 or tok[0] not in ("+", "-"):
748
+ continue
749
+ sym = tok[1:].upper()
750
+ if sym in g2i and sym not in seen:
751
+ seen.add(sym)
752
+ if tok[0] == "+":
753
+ up.append(sym)
754
+ interleaved.append(("+" + sym, sym, len(up)))
755
+ else:
756
+ down.append(sym)
757
+ interleaved.append(("-" + sym, sym, len(down)))
758
+
759
+ residual_vec = np.zeros_like(baseline)
760
+ if up or down:
761
+ task_oh = [0.0] * 7 + [1.0]
762
+ eff_up = float(max(len(up), 550) if is_truncated else len(up))
763
+ eff_dn = float(max(len(down), 550) if is_truncated else len(down))
764
+ feats: list[list[float]] = []
765
+ ctrl_vals: list[float] = []
766
+ idxs: list[int] = []
767
+ for is_up, g_list in ((1.0, up), (0.0, down)):
768
+ for rank, g in enumerate(g_list):
769
+ idx = g2i[g]
770
+ feats.append([is_up, float(rank), eff_up, eff_dn] + task_oh)
771
+ ctrl_vals.append(float(baseline[idx]))
772
+ idxs.append(idx)
773
+ with torch.no_grad():
774
+ deltas = decoder(
775
+ torch.tensor(feats, dtype=torch.float32),
776
+ torch.tensor(ctrl_vals, dtype=torch.float32),
777
+ )
778
+ residual_vec[idxs] = deltas.cpu().numpy().flatten()
779
+
780
+ predicted_expr = baseline + residual_vec
781
+ predicted_lfc = predicted_expr - ctrl_expr
782
+
783
+ all_entries: list[dict[str, Any]] = []
784
+ for emit_idx, (signed_sym, g, dir_rank) in enumerate(interleaved):
785
+ idx = g2i[g]
786
+ all_entries.append(
787
+ self._build_gene_entry(
788
+ signed_sym=signed_sym,
789
+ g=g,
790
+ emit_order=emit_idx + 1,
791
+ dir_rank=dir_rank,
792
+ ctrl_val=float(ctrl_expr[idx]),
793
+ base_val=float(baseline[idx]),
794
+ pred_val=float(predicted_expr[idx]),
795
+ lfc_val=float(predicted_lfc[idx]),
796
+ res_val=float(residual_vec[idx]),
797
+ )
798
+ )
799
+
800
+ up_entries = sorted(
801
+ [e for e in all_entries if e["sym"].startswith("+")],
802
+ key=lambda e: (-abs(e["residual"]), e["dir_rank"]),
803
+ )
804
+ down_entries = sorted(
805
+ [e for e in all_entries if e["sym"].startswith("-")],
806
+ key=lambda e: (-abs(e["residual"]), e["dir_rank"]),
807
+ )
808
+
809
+ half = max(12, top_n_genes // 2)
810
+ combined = sorted(
811
+ up_entries[:half] + down_entries[:half],
812
+ key=lambda e: -abs(e["residual"]),
813
+ )[:top_n_genes]
814
+
815
+ verdict = self._synthesize_verdict(
816
+ dataset=dataset,
817
+ up_entries=up_entries,
818
+ down_entries=down_entries,
819
+ count_up=len(up),
820
+ count_down=len(down),
821
+ )
822
+ cell_meta = self.get_cell_baseline_summary(dataset, cell_idx)
823
+
824
+ out_payload: dict[str, Any] = {
825
+ "dataset": dataset,
826
+ "cell_idx": cell_idx,
827
+ "cell_id": cell_meta["cell_id"],
828
+ "cell_line": cell_meta["cell_line"],
829
+ "total_genes": cell_meta["total_genes"],
830
+ "count_up": len(up),
831
+ "count_down": len(down),
832
+ "verdict": verdict,
833
+ "top_up": up_entries[:12],
834
+ "top_down": down_entries[:12],
835
+ "gene_stars": combined,
836
+ }
837
+ if include_all_genes or not is_truncated:
838
+ out_payload["all_genes"] = up_entries + down_entries
839
+ return out_payload
840
+
841
+ def _synthesize_verdict(
842
+ self,
843
+ dataset: str,
844
+ up_entries: list[dict[str, Any]],
845
+ down_entries: list[dict[str, Any]],
846
+ count_up: int,
847
+ count_down: int,
848
+ ) -> dict[str, Any]:
849
+ """Builds a plain-English summary and pins signature genes for graphic callouts."""
850
+ up_syms = {e["gene"] for e in up_entries[:15]}
851
+ dn_syms = {e["gene"] for e in down_entries[:15]}
852
+
853
+ lead_up = ", ".join(f"{e['sym']} ({e['nick']})" for e in up_entries[:2]) or "none"
854
+ lead_dn = ", ".join(f"{e['sym']} ({e['nick']})" for e in down_entries[:2]) or "none"
855
+
856
+ def _first_match(entries: list[dict[str, Any]], candidates: set[str], limit: int = 1) -> list[str]:
857
+ found = [e["sym"] for e in entries[:15] if e["gene"] in candidates]
858
+ return found[:limit]
859
+
860
+ if {"GYPB", "HBZ", "ALAS2"} & up_syms and ({"C1QBP", "SRM", "RRP1B", "WDR43"} & dn_syms):
861
+ return {
862
+ "badge": "Growth Engine Shut Down · Red-Cell Genes On",
863
+ "headline": "Leukemia Cell Shuts Down Ribosome Factories and Switches On Red-Blood-Cell Genes",
864
+ "summary": (
865
+ f"In this K562 cell, muting MYC collapses protein & polyamine growth factories "
866
+ f"({lead_dn}) while turning up oxygen-carrying globin and red-cell surface genes ({lead_up})."
867
+ ),
868
+ "featured_up": _first_match(up_entries, {"GYPB", "HBZ", "ALAS2", "HBG2"}),
869
+ "featured_down": _first_match(down_entries, {"C1QBP", "SRM", "WDR43", "RRP1B"}),
870
+ }
871
+ if {"SLC7A8", "LGALS1", "MDK"} & up_syms and ({"NOLC1", "MRTO4"} & dn_syms):
872
+ return {
873
+ "badge": "DNA Silencing Lifted · Surface Proteins Up",
874
+ "headline": "Lifting DNA Methylation Turns Up Surface Transporters & Slows Nucleolar Assembly",
875
+ "summary": (
876
+ f"In this K562 cell, muting DNMT1 turns up previously quiet membrane & secreted genes "
877
+ f"({lead_up}) while dialing down nucleolar ribosome builders ({lead_dn})."
878
+ ),
879
+ "featured_up": _first_match(up_entries, {"SLC7A8", "LGALS1", "MDK"}),
880
+ "featured_down": _first_match(down_entries, {"NOLC1", "MRTO4"}),
881
+ }
882
+ if {"CALR", "H1-0", "H3-3B"} <= up_syms and "MDM2" in dn_syms:
883
+ return {
884
+ "badge": "Chromatin Unpacked · Surface Flag Raised",
885
+ "headline": "Unpacked DNA Raises 'Eat-Me' Surface Flag (+CALR) and Lowers p53 Brake (-MDM2)",
886
+ "summary": (
887
+ f"In this A549 lung-cancer cell, Panobinostat turns up chromatin histones and surface chaperone +CALR "
888
+ f"while turning down tumor survival regulators ({lead_dn})."
889
+ ),
890
+ "featured_up": ["+CALR"],
891
+ "featured_down": ["-MDM2"],
892
+ }
893
+ if "LRP1" in dn_syms and ({"PLOD2", "VIM"} & up_syms):
894
+ return {
895
+ "badge": "Invasion Receptor Down · Cytoskeleton Shifted",
896
+ "headline": "Kinase Blockade Turns Down Invasion Receptors (-LRP1) and Remodels Filaments",
897
+ "summary": (
898
+ f"In this A549 lung-cancer cell, blocking SRC/ABL/EPHA2 kinases lowers migration & growth "
899
+ f"receptors ({lead_dn}) while shifting structural & chaperone genes ({lead_up})."
900
+ ),
901
+ "featured_up": _first_match(up_entries, {"VIM", "PLOD2"}),
902
+ "featured_down": ["-LRP1"],
903
+ }
904
+ if "TXNRD1" in up_syms and "ARHGAP26" in dn_syms:
905
+ return {
906
+ "badge": "MAPK Relay Cut · Stress Defense Up",
907
+ "headline": "Blocking MEK1/2 Lowers Motility Signaling and Turns Up Antioxidant Defense (+TXNRD1)",
908
+ "summary": (
909
+ f"In this A549 cell, cutting the MEK growth relay dials down motility & MAPK feedback genes "
910
+ f"({lead_dn}) while boosting redox & membrane stabilizers ({lead_up})."
911
+ ),
912
+ "featured_up": ["+TXNRD1"],
913
+ "featured_down": ["-ARHGAP26"],
914
+ }
915
+
916
+ cell_label = "A549 lung-cancer cell" if dataset == "tahoe" else "K562 leukemia cell"
917
+ return {
918
+ "badge": f"{count_up + count_down} Gene Knobs Shifted",
919
+ "headline": f"CellGemma Predicted {count_up} Upregulated (+) and {count_down} Downregulated (-) Genes",
920
+ "summary": f"Inside this single {cell_label}, top increases are {lead_up} and top decreases are {lead_dn}.",
921
+ "featured_up": [e["sym"] for e in up_entries[:1]],
922
+ "featured_down": [e["sym"] for e in down_entries[:1]],
923
+ }
924
+
925
+ def stream_predict(
926
+ self,
927
+ dataset: str,
928
+ cell_idx: int,
929
+ kind: str,
930
+ drug_name: str = "",
931
+ smiles: str = "",
932
+ concentration_um: float = 0.5,
933
+ gene: str = "",
934
+ max_new_tokens: int = 180,
935
+ temperature: float = 0.0,
936
+ ) -> Iterator[dict[str, Any]]:
937
+ """Streams live heartbeats, Stage 1 gene tokens, and Stage 2 single-cell reconstructions."""
938
+ ctrl_expr, baseline, prompt, input_viz = self.prepare_cell_and_prompt(
939
+ dataset=dataset,
940
+ cell_idx=cell_idx,
941
+ kind=kind,
942
+ drug_name=drug_name,
943
+ smiles=smiles,
944
+ concentration_um=concentration_um,
945
+ gene=gene,
946
+ )
947
+
948
+ hw_map = {"mps": "Apple Metal GPU (MPS)", "cuda": "NVIDIA CUDA GPU", "cpu": "Multi-Core CPU"}
949
+ hw_label = hw_map.get(self.device, self.device.upper())
950
+ dtype_label = str(self.dtype).replace("torch.", "")
951
+
952
+ if self._model is None or self._tokenizer is None:
953
+ load_t0 = time.perf_counter()
954
+ if IS_ZEROGPU:
955
+ self.ensure_model_loaded()
956
+ else:
957
+ self.start_background_preload()
958
+ while self.model_load_state == "loading" or (
959
+ self.model_load_state == "not_loaded" and self._model is None
960
+ ):
961
+ elapsed_load = round(time.perf_counter() - load_t0, 1)
962
+ yield {
963
+ "type": "heartbeat",
964
+ "step": 1,
965
+ "phase": "loading_model",
966
+ "device": hw_label,
967
+ "elapsed_s": elapsed_load,
968
+ "message": f"Loading CellGemma E4B weights onto {hw_label} ({dtype_label})... {elapsed_load:.1f}s",
969
+ "input_viz": input_viz,
970
+ }
971
+ time.sleep(0.4)
972
+ if self.model_load_state == "error" or self._model is None:
973
+ raise RuntimeError(self.model_load_error or "Failed to load CellGemma E4B weights.")
974
+
975
+ assert self._model is not None and self._tokenizer is not None
976
+
977
+ with self._model_lock:
978
+ formatted = f"<bos><|turn>user\n{prompt}<turn|>\n<|turn>model\n"
979
+ inputs = self._tokenizer(
980
+ formatted, return_tensors="pt", add_special_tokens=False
981
+ ).to(self.device)
982
+ prompt_tok_len = int(inputs["input_ids"].shape[1])
983
+ eot_id = self._tokenizer.convert_tokens_to_ids("<turn|>")
984
+
985
+ streamer = TextIteratorStreamer(
986
+ self._tokenizer, skip_prompt=True, skip_special_tokens=True
987
+ )
988
+ capped_max = max(32, min(1024, int(max_new_tokens)))
989
+ temp_val = max(0.0, min(1.5, float(temperature)))
990
+ gen_kwargs: dict[str, Any] = dict(
991
+ **inputs,
992
+ streamer=streamer,
993
+ max_new_tokens=capped_max,
994
+ do_sample=temp_val > 0.01,
995
+ pad_token_id=self._tokenizer.pad_token_id,
996
+ eos_token_id=[self._tokenizer.eos_token_id, eot_id],
997
+ )
998
+ if temp_val > 0.01:
999
+ gen_kwargs["temperature"] = temp_val
1000
+
1001
+ chunk_q: queue.Queue[str | None] = queue.Queue()
1002
+ gen_error: list[Exception] = []
1003
+
1004
+ def _run_gen() -> None:
1005
+ try:
1006
+ with torch.no_grad():
1007
+ self._model.generate(**gen_kwargs)
1008
+ except Exception as exc: # pragma: no cover
1009
+ gen_error.append(exc)
1010
+ finally:
1011
+ try:
1012
+ streamer.end()
1013
+ except Exception:
1014
+ pass
1015
+
1016
+ def _pump_streamer() -> None:
1017
+ try:
1018
+ for piece in streamer:
1019
+ if piece:
1020
+ chunk_q.put(piece)
1021
+ finally:
1022
+ chunk_q.put(None)
1023
+
1024
+ start_t = time.perf_counter()
1025
+ worker = threading.Thread(target=_run_gen, daemon=True)
1026
+ pumper = threading.Thread(target=_pump_streamer, daemon=True)
1027
+ worker.start()
1028
+ pumper.start()
1029
+
1030
+ yield {
1031
+ "type": "started",
1032
+ "step": 2,
1033
+ "phase": "encoding_cell",
1034
+ "device": hw_label,
1035
+ "prompt_tokens": prompt_tok_len,
1036
+ "max_new_tokens": capped_max,
1037
+ "input_viz": input_viz,
1038
+ "message": f"Encoding Single Cell #{cell_idx} ({prompt_tok_len:,} tokens) on {hw_label}...",
1039
+ }
1040
+
1041
+ accumulated_chunks: list[str] = []
1042
+ last_reconstruct_tokens = 0
1043
+ first_token_seen = False
1044
+
1045
+ while True:
1046
+ try:
1047
+ piece = chunk_q.get(timeout=0.4)
1048
+ except queue.Empty:
1049
+ elapsed = round(time.perf_counter() - start_t, 1)
1050
+ if not first_token_seen:
1051
+ yield {
1052
+ "type": "heartbeat",
1053
+ "step": 2,
1054
+ "phase": "encoding_cell",
1055
+ "device": hw_label,
1056
+ "prompt_tokens": prompt_tok_len,
1057
+ "elapsed_s": elapsed,
1058
+ "message": f"Reading 1,000 baseline cell genes & perturbation ({prompt_tok_len:,} tokens)... {elapsed:.1f}s",
1059
+ }
1060
+ continue
1061
+
1062
+ if piece is None:
1063
+ break
1064
+
1065
+ first_token_seen = True
1066
+ accumulated_chunks.append(piece)
1067
+ full_text = "".join(accumulated_chunks)
1068
+ words = full_text.split()
1069
+ if not full_text.endswith((" ", "\n")) and words:
1070
+ complete_words = words[:-1]
1071
+ else:
1072
+ complete_words = words
1073
+ toks = [t for t in complete_words if len(t) >= 2 and t[0] in ("+", "-")]
1074
+ elapsed = max(1e-3, time.perf_counter() - start_t)
1075
+
1076
+ if len(toks) >= 1 and (last_reconstruct_tokens == 0 or len(toks) - last_reconstruct_tokens >= 2):
1077
+ last_reconstruct_tokens = len(toks)
1078
+ partial_state = self.reconstruct_and_summarize(
1079
+ dataset=dataset,
1080
+ cell_idx=cell_idx,
1081
+ raw_text=" ".join(toks),
1082
+ ctrl_expr=ctrl_expr,
1083
+ baseline=baseline,
1084
+ is_truncated=True,
1085
+ )
1086
+ latest_sym = toks[-1]
1087
+ bare_latest = latest_sym[1:].upper()
1088
+ latest_nick = GENE_ANNOTATIONS.get(bare_latest, ("cytoplasm", "Gene Shift", ""))[1]
1089
+ yield {
1090
+ "type": "partial",
1091
+ "step": 3,
1092
+ "phase": "streaming_genes",
1093
+ "device": hw_label,
1094
+ "elapsed_s": round(elapsed, 2),
1095
+ "tok_per_s": round(len(toks) / elapsed, 1),
1096
+ "gene_count": len(toks),
1097
+ "latest_gene": {"sym": latest_sym, "nick": latest_nick},
1098
+ "recent_tokens": toks[-8:],
1099
+ "state": partial_state,
1100
+ }
1101
+
1102
+ worker.join()
1103
+ pumper.join()
1104
+ if gen_error:
1105
+ raise RuntimeError(f"Model generation failed on {hw_label}: {gen_error[0]}") from gen_error[0]
1106
+
1107
+ total_elapsed = max(1e-3, time.perf_counter() - start_t)
1108
+ final_text = "".join(accumulated_chunks).strip()
1109
+ gen_subword_count = len(self._tokenizer.encode(final_text, add_special_tokens=False))
1110
+ hit_cap = gen_subword_count >= int(capped_max * 0.85) and int(capped_max) < 2048
1111
+ final_state = self.reconstruct_and_summarize(
1112
+ dataset=dataset,
1113
+ cell_idx=cell_idx,
1114
+ raw_text=final_text,
1115
+ ctrl_expr=ctrl_expr,
1116
+ baseline=baseline,
1117
+ is_truncated=hit_cap,
1118
+ include_all_genes=True,
1119
+ )
1120
+ final_toks = final_state["count_up"] + final_state["count_down"]
1121
+ yield {
1122
+ "type": "complete",
1123
+ "step": 4,
1124
+ "phase": "complete",
1125
+ "device": hw_label,
1126
+ "elapsed_s": round(total_elapsed, 2),
1127
+ "tok_per_s": round(max(1, final_toks) / total_elapsed, 1),
1128
+ "prompt_tokens": prompt_tok_len,
1129
+ "prompt": prompt,
1130
+ "raw_text": final_text,
1131
+ "input_viz": input_viz,
1132
+ "state": final_state,
1133
+ }
gene_catalog.json ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spaces
2
+ gradio>=6.28.0
3
+ huggingface-hub>=1.0.0
4
+ transformers>=5.20.0
5
+ accelerate>=1.2.0
6
+ safetensors>=0.5.0
7
+ torch>=2.5.0
8
+ numpy>=1.26.0
9
+ rdkit>=2024.3.1
10
+ pydantic>=2.10.0
11
+ fastapi>=0.115.0
12
+ uvicorn>=0.34.0
static/app.js ADDED
The diff for this file is too large to render. See raw diff
 
static/cellgemma_logo_dark.png ADDED

Git LFS Details

  • SHA256: 7e8aa25acf58f5887fa9b8ca100f8d20c280cd42fb10efa0c9aa1af363a1656e
  • Pointer size: 130 Bytes
  • Size of remote file: 51.3 kB
static/cellgemma_logo_light.png ADDED

Git LFS Details

  • SHA256: 1a4bca985c1ff5a50d730a35bd8b14baa6dfa747d9deb8f30bfc1bb89e7aa1cf
  • Pointer size: 130 Bytes
  • Size of remote file: 50.6 kB
static/index.html ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en" class="theme-dark">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>CellGemma · Single-Cell Perturbation Studio</title>
7
+ <meta
8
+ name="description"
9
+ content="Interactive visual studio showing how CellGemma (Gemma 4 E4B) predicts single-cell gene expression shifts in response to a small-molecule drug or CRISPR gene knockdown."
10
+ />
11
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
12
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
13
+ <link
14
+ href="https://fonts.googleapis.com/css2?family=Google+Sans+Mono:wght@500;600;700&family=Google+Sans+Text:wght@400;500;600&family=Google+Sans:wght@500;600;700&display=swap"
15
+ rel="stylesheet"
16
+ />
17
+ <link rel="stylesheet" href="/studio_static/styles.css" />
18
+ </head>
19
+ <body class="theme-dark">
20
+ <div class="app-frame">
21
+ <!-- 1. Precision Single-Row Top Bar -->
22
+ <header class="top-bar">
23
+ <div class="brand-lockup">
24
+ <h1 class="sr-only">CellGemma Single-Cell Perturbation Studio</h1>
25
+ <img
26
+ id="brand-logo-dark"
27
+ class="brand-wordmark wordmark-for-dark"
28
+ src="/studio_static/cellgemma_logo_dark.png"
29
+ alt="CellGemma"
30
+ width="138"
31
+ height="20"
32
+ />
33
+ <img
34
+ id="brand-logo-light"
35
+ class="brand-wordmark wordmark-for-light"
36
+ src="/studio_static/cellgemma_logo_light.png"
37
+ alt="CellGemma"
38
+ width="138"
39
+ height="20"
40
+ />
41
+ <span class="brand-variant-tag" title="Built on Gemma 4 (E4B)">E4B</span>
42
+ </div>
43
+
44
+ <nav class="preset-strip" aria-label="Perturbation presets">
45
+ <span class="preset-group-label">Drugs</span>
46
+ <div id="drug-preset-pills"></div>
47
+ <span class="preset-divider" aria-hidden="true"></span>
48
+ <span class="preset-group-label">CRISPR</span>
49
+ <div id="crispr-preset-pills"></div>
50
+ </nav>
51
+
52
+ <div class="run-controls">
53
+ <button
54
+ type="button"
55
+ class="theme-toggle-btn"
56
+ id="theme-toggle-btn"
57
+ aria-label="Toggle dark and light visual theme"
58
+ title="Switch between Bioluminescent Dark and Optical Quartz Light"
59
+ >
60
+ <svg class="theme-icon icon-sun" viewBox="0 0 20 20" fill="none" aria-hidden="true">
61
+ <circle cx="10" cy="10" r="3.8" stroke="currentColor" stroke-width="1.7" />
62
+ <path
63
+ d="M10 2.2v2.1M10 15.7v2.1M2.2 10h2.1M15.7 10h2.1M4.48 4.48l1.48 1.48M14.04 14.04l1.48 1.48M15.52 4.48l-1.48 1.48M5.96 14.04l-1.48 1.48"
64
+ stroke="currentColor"
65
+ stroke-width="1.7"
66
+ stroke-linecap="round"
67
+ />
68
+ </svg>
69
+ <svg class="theme-icon icon-moon" viewBox="0 0 20 20" fill="none" aria-hidden="true">
70
+ <path
71
+ d="M15.6 12.4A6.4 6.4 0 0 1 7.6 4.4a6.4 6.4 0 1 0 8 8Z"
72
+ stroke="currentColor"
73
+ stroke-width="1.7"
74
+ stroke-linejoin="round"
75
+ />
76
+ </svg>
77
+ <span id="theme-toggle-label">Light</span>
78
+ </button>
79
+
80
+ <button type="button" class="customize-toggle-btn" id="customize-btn" aria-expanded="false">
81
+ Customize ▾
82
+ </button>
83
+
84
+ <button
85
+ type="button"
86
+ class="reset-btn"
87
+ id="reset-btn"
88
+ title="Reset simulation to clean empty starting state"
89
+ >
90
+ <svg class="reset-icon" viewBox="0 0 20 20" fill="none" aria-hidden="true">
91
+ <path
92
+ d="M4.2 7.2A6.5 6.5 0 1 1 5.1 14.3M4.0 3.6v3.9h3.9"
93
+ stroke="currentColor"
94
+ stroke-width="1.75"
95
+ stroke-linecap="round"
96
+ stroke-linejoin="round"
97
+ />
98
+ </svg>
99
+ <span>Reset</span>
100
+ </button>
101
+
102
+ <button type="button" class="run-cta-btn" id="run-btn">
103
+ ▶ Run CellGemma
104
+ </button>
105
+ </div>
106
+
107
+ <!-- Optional Floating Customize Popover (Closed by Default) -->
108
+ <section class="customize-popover hidden" id="customize-popover" aria-label="Customize perturbation input">
109
+ <div class="popover-top">
110
+ <div class="popover-tabs">
111
+ <button type="button" class="pop-tab-btn active" id="pop-tab-drug">Small-Molecule Drug (A549)</button>
112
+ <button type="button" class="pop-tab-btn" id="pop-tab-crispr">CRISPR Knockdown (K562)</button>
113
+ </div>
114
+ <button type="button" class="popover-close-btn" id="popover-close-btn">Done</button>
115
+ </div>
116
+
117
+ <div class="popover-grid">
118
+ <div class="mini-mol-box" id="mini-mol-box" title="Drag to spin 3D structure">
119
+ <canvas class="mini-mol-canvas" id="mini-mol-canvas"></canvas>
120
+ </div>
121
+
122
+ <div class="popover-fields">
123
+ <div id="pop-drug-fields">
124
+ <div class="pop-row">
125
+ <label for="smiles-input">SMILES Structure</label>
126
+ <span class="pop-mono" id="mol-meta-readout">RDKit 3D</span>
127
+ </div>
128
+ <input type="text" class="pop-input" id="smiles-input" spellcheck="false" autocomplete="off" />
129
+ <div class="pop-row">
130
+ <label for="dose-slider">Concentration</label>
131
+ <span class="pop-mono" id="dose-readout">0.50 µM</span>
132
+ </div>
133
+ <input type="range" class="pop-slider" id="dose-slider" min="0.05" max="5.0" step="0.05" value="0.50" />
134
+ </div>
135
+
136
+ <div class="hidden" id="pop-crispr-fields">
137
+ <div class="pop-row">
138
+ <label for="gene-input">Target Human Gene</label>
139
+ <span class="pop-mono" id="kg-edge-readout">STRING Network</span>
140
+ </div>
141
+ <input type="text" class="pop-input" id="gene-input" maxlength="20" spellcheck="false" autocomplete="off" />
142
+ <div class="pop-gene-chips" id="featured-gene-chips"></div>
143
+ </div>
144
+
145
+ <div class="pop-row">
146
+ <label for="cell-idx-slider">Single Control Cell</label>
147
+ <span class="pop-mono" id="cell-idx-readout">Cell #0</span>
148
+ </div>
149
+ <input type="range" class="pop-slider" id="cell-idx-slider" min="0" max="99" step="1" value="0" />
150
+
151
+ <div class="pop-row">
152
+ <label for="temp-slider">Sampling Temperature</label>
153
+ <span class="pop-mono" id="temp-readout">0.0 (Deterministic)</span>
154
+ </div>
155
+ <input type="range" class="pop-slider" id="temp-slider" min="0" max="1.0" step="0.1" value="0" />
156
+ </div>
157
+ </div>
158
+ </section>
159
+ </header>
160
+
161
+ <!-- 2. Hero Visual Stage -->
162
+ <main class="hero-stage-card">
163
+ <div class="hero-canvas-wrap" id="hero-canvas-wrap">
164
+ <canvas class="hero-canvas" id="hero-canvas"></canvas>
165
+ </div>
166
+ </main>
167
+
168
+ <!-- 3. Precision Bottom Equalizer Strip (Fixed Height — Zero Layout Shift) -->
169
+ <section class="bottom-strip" aria-label="Predicted gene expression shifts">
170
+ <div class="error-inline hidden" id="error-banner" role="alert"></div>
171
+
172
+ <div class="outcome-strip" id="outcome-strip">
173
+ <div class="outcome-header-block">
174
+ <h2 class="outcome-headline" id="verdict-headline">Awaiting Simulation — Click ▶ Run CellGemma</h2>
175
+ <div class="outcome-meta-line">
176
+ <span class="outcome-sub" id="verdict-sub">A549 Lung Carcinoma · Single Cell #0</span>
177
+ <div class="outcome-badges">
178
+ <button
179
+ type="button"
180
+ class="outcome-action-btn hidden"
181
+ id="view-prompt-btn"
182
+ title="Inspect exact Stage 1 text prompt and raw model tokens"
183
+ >
184
+ Prompt
185
+ </button>
186
+ <button
187
+ type="button"
188
+ class="outcome-action-btn hidden"
189
+ id="download-csv-btn"
190
+ title="Download all predicted single-cell gene shifts as CSV"
191
+ >
192
+ ↓ CSV
193
+ </button>
194
+ <span class="pill-stat-up pill-stat-muted" id="count-up-pill">↑ — UP</span>
195
+ <span class="pill-stat-down pill-stat-muted" id="count-down-pill">↓ — DOWN</span>
196
+ </div>
197
+ </div>
198
+ </div>
199
+
200
+ <div class="bars-two-col">
201
+ <div class="bars-column">
202
+ <div class="bars-col-label up">↑ Top Genes Turned UP (% Shift vs Baseline)</div>
203
+ <div id="bars-up-list"></div>
204
+ </div>
205
+ <div class="bars-column">
206
+ <div class="bars-col-label down">↓ Top Genes Turned DOWN (% Shift vs Baseline)</div>
207
+ <div id="bars-down-list"></div>
208
+ </div>
209
+ </div>
210
+ </div>
211
+ </section>
212
+
213
+ <!-- Raw Stage 1 Prompt & Model Output Inspector Modal -->
214
+ <div
215
+ class="prompt-modal-backdrop hidden"
216
+ id="prompt-modal-backdrop"
217
+ role="dialog"
218
+ aria-modal="true"
219
+ aria-labelledby="prompt-modal-title"
220
+ >
221
+ <div class="prompt-modal-card">
222
+ <div class="prompt-modal-header">
223
+ <div>
224
+ <h3 class="prompt-modal-title" id="prompt-modal-title">Stage 1 Prompt &amp; Emitted Gene Tokens</h3>
225
+ <p class="prompt-modal-sub" id="prompt-modal-meta">CellGemma E4B Single-Cell Transcriptional Input</p>
226
+ </div>
227
+ <div class="prompt-modal-actions">
228
+ <button type="button" class="pop-btn-secondary" id="copy-prompt-btn">Copy Prompt</button>
229
+ <button type="button" class="popover-close-btn" id="close-prompt-modal-btn">Close</button>
230
+ </div>
231
+ </div>
232
+ <div class="prompt-modal-body">
233
+ <div class="prompt-section-label">Stage 1 Input Prompt (Control Cell + Perturbation + Global Mean)</div>
234
+ <pre class="prompt-code-box" id="prompt-modal-input"></pre>
235
+ <div class="prompt-section-label">Stage 1 Raw Model Output (Ordered Residual Gene Tokens)</div>
236
+ <pre class="prompt-code-box prompt-code-box-compact" id="prompt-modal-output"></pre>
237
+ </div>
238
+ </div>
239
+ </div>
240
+ </div>
241
+
242
+ <script src="/studio_static/app.js"></script>
243
+ </body>
244
+ </html>
static/styles.css ADDED
@@ -0,0 +1,1070 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* CellGemma · Single-Cell Perturbation Studio — Dual-Theme Optical Design System */
2
+
3
+ html.theme-dark,
4
+ body.theme-dark {
5
+ color-scheme: dark;
6
+ --bg-page: #030711;
7
+ --bg-ambient-top: rgba(29, 78, 216, 0.14);
8
+ --bg-card: rgba(10, 19, 36, 0.88);
9
+ --bg-card-solid: #0b1528;
10
+ --bg-pill: rgba(15, 28, 52, 0.92);
11
+ --bg-pill-hover: rgba(30, 48, 82, 0.72);
12
+ --bg-pill-active: #16294b;
13
+ --bg-input: #070f1e;
14
+ --bg-stage-center: #0a1934;
15
+ --bg-stage-mid: #050d1d;
16
+ --bg-stage-edge: #030813;
17
+
18
+ --ink-strong: #f1f5f9;
19
+ --ink-body: #cbd5e1;
20
+ --ink-muted: #7c90ad;
21
+
22
+ --border-subtle: rgba(148, 179, 224, 0.14);
23
+ --border-strong: rgba(148, 179, 224, 0.25);
24
+ --inset-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.06);
25
+
26
+ --blue-primary: #2b74ff;
27
+ --blue-hover: #4285ff;
28
+ --blue-accent-ink: #60a5fa;
29
+ --blue-tint: rgba(43, 116, 255, 0.16);
30
+
31
+ --up-ink: #34d399;
32
+ --up-bright: #10b981;
33
+ --up-tint: rgba(16, 185, 129, 0.14);
34
+
35
+ --down-ink: #fb7185;
36
+ --down-bright: #f43f5e;
37
+ --down-tint: rgba(244, 63, 94, 0.14);
38
+
39
+ --bar-track-fill: rgba(148, 163, 184, 0.13);
40
+ --row-hover-bg: rgba(30, 48, 82, 0.45);
41
+ --loc-badge-bg: rgba(148, 163, 184, 0.12);
42
+ --loc-badge-ink: #94a3b8;
43
+
44
+ --shadow-bar: 0 8px 28px rgba(0, 0, 0, 0.42), inset 0 1px 0 rgba(255, 255, 255, 0.05);
45
+ --shadow-stage: 0 20px 54px rgba(0, 0, 0, 0.56), inset 0 1px 0 rgba(255, 255, 255, 0.06);
46
+ --shadow-popover: 0 26px 64px rgba(0, 0, 0, 0.72), 0 4px 16px rgba(0, 0, 0, 0.45);
47
+ --shadow-active-pill: 0 2px 6px rgba(0, 0, 0, 0.28);
48
+ }
49
+
50
+ html.theme-light,
51
+ body.theme-light {
52
+ color-scheme: light;
53
+ --bg-page: #edf2fa;
54
+ --bg-ambient-top: rgba(43, 116, 255, 0.07);
55
+ --bg-card: rgba(255, 255, 255, 0.94);
56
+ --bg-card-solid: #ffffff;
57
+ --bg-pill: #eef3fb;
58
+ --bg-pill-hover: rgba(255, 255, 255, 0.90);
59
+ --bg-pill-active: #ffffff;
60
+ --bg-input: #f8fafd;
61
+ --bg-stage-center: #ffffff;
62
+ --bg-stage-mid: #f7faff;
63
+ --bg-stage-edge: #ebf2fc;
64
+
65
+ --ink-strong: #0d172a;
66
+ --ink-body: #334155;
67
+ --ink-muted: #64748b;
68
+
69
+ --border-subtle: rgba(15, 23, 42, 0.085);
70
+ --border-strong: rgba(15, 23, 42, 0.15);
71
+ --inset-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.92);
72
+
73
+ --blue-primary: #1a68e8;
74
+ --blue-hover: #1557c4;
75
+ --blue-accent-ink: #1a68e8;
76
+ --blue-tint: rgba(26, 104, 232, 0.10);
77
+
78
+ --up-ink: #047857;
79
+ --up-bright: #10b981;
80
+ --up-tint: #ecfdf5;
81
+
82
+ --down-ink: #be123c;
83
+ --down-bright: #f43f5e;
84
+ --down-tint: #fff1f2;
85
+
86
+ --bar-track-fill: #e7edf6;
87
+ --row-hover-bg: #f3f7fd;
88
+ --loc-badge-bg: #edf2f9;
89
+ --loc-badge-ink: #52637a;
90
+
91
+ --shadow-bar: 0 2px 12px rgba(15, 23, 42, 0.045), inset 0 1px 0 rgba(255, 255, 255, 0.95);
92
+ --shadow-stage: 0 12px 36px rgba(15, 23, 42, 0.065), 0 1px 3px rgba(15, 23, 42, 0.04);
93
+ --shadow-popover: 0 22px 48px rgba(15, 23, 42, 0.16), 0 2px 10px rgba(15, 23, 42, 0.06);
94
+ --shadow-active-pill: 0 1px 4px rgba(15, 23, 42, 0.08);
95
+ }
96
+
97
+ .theme-switching,
98
+ .theme-switching * {
99
+ transition: none !important;
100
+ }
101
+
102
+ body,
103
+ .app-frame {
104
+ --font-display: "Google Sans", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
105
+ --font-sans: "Google Sans Text", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
106
+ --font-mono: "Google Sans Mono", "JetBrains Mono", ui-monospace, SFMono-Regular, monospace;
107
+ }
108
+
109
+ *,
110
+ *::before,
111
+ *::after {
112
+ box-sizing: border-box;
113
+ }
114
+
115
+ html,
116
+ body {
117
+ margin: 0;
118
+ padding: 0;
119
+ min-height: 100%;
120
+ background-color: var(--bg-page);
121
+ background-image: radial-gradient(ellipse 80% 42% at 50% 0%, var(--bg-ambient-top), transparent 72%);
122
+ color: var(--ink-strong);
123
+ font-family: var(--font-sans);
124
+ font-size: 14px;
125
+ -webkit-font-smoothing: antialiased;
126
+ -moz-osx-font-smoothing: grayscale;
127
+ text-rendering: optimizeLegibility;
128
+ }
129
+
130
+ .hidden {
131
+ display: none !important;
132
+ }
133
+
134
+ .sr-only {
135
+ position: absolute;
136
+ width: 1px;
137
+ height: 1px;
138
+ padding: 0;
139
+ margin: -1px;
140
+ overflow: hidden;
141
+ clip: rect(0, 0, 0, 0);
142
+ white-space: nowrap;
143
+ border: 0;
144
+ }
145
+
146
+ .app-frame {
147
+ max-width: 1580px;
148
+ min-height: 100dvh;
149
+ margin: 0 auto;
150
+ padding: 9px 18px 11px;
151
+ display: flex;
152
+ flex-direction: column;
153
+ gap: 8px;
154
+ }
155
+
156
+ /* 1. Precision Glass Top Navigation Bar */
157
+ .top-bar {
158
+ position: relative;
159
+ background: var(--bg-card);
160
+ backdrop-filter: blur(16px);
161
+ -webkit-backdrop-filter: blur(16px);
162
+ border: 1px solid var(--border-subtle);
163
+ border-radius: 15px;
164
+ padding: 7px 14px;
165
+ box-shadow: var(--shadow-bar);
166
+ display: flex;
167
+ align-items: center;
168
+ justify-content: space-between;
169
+ gap: 10px;
170
+ flex-wrap: nowrap;
171
+ z-index: 30;
172
+ }
173
+
174
+ .brand-lockup {
175
+ display: flex;
176
+ align-items: center;
177
+ gap: 8px;
178
+ flex-shrink: 0;
179
+ }
180
+
181
+ .brand-wordmark {
182
+ height: 20px;
183
+ width: auto;
184
+ display: block;
185
+ object-fit: contain;
186
+ }
187
+
188
+ body.theme-dark .wordmark-for-light {
189
+ display: none;
190
+ }
191
+
192
+ body.theme-light .wordmark-for-dark {
193
+ display: none;
194
+ }
195
+
196
+ .brand-variant-tag {
197
+ font-family: var(--font-mono);
198
+ font-size: 10.5px;
199
+ font-weight: 600;
200
+ letter-spacing: 0.04em;
201
+ color: var(--blue-accent-ink);
202
+ background: var(--blue-tint);
203
+ border: 1px solid var(--border-subtle);
204
+ padding: 2px 7px;
205
+ border-radius: 6px;
206
+ }
207
+
208
+ .preset-strip {
209
+ display: flex;
210
+ align-items: center;
211
+ gap: 3px;
212
+ background: var(--bg-pill);
213
+ padding: 3.5px;
214
+ border-radius: 11px;
215
+ border: 1px solid var(--border-subtle);
216
+ flex-wrap: nowrap;
217
+ min-width: 0;
218
+ }
219
+
220
+ #drug-preset-pills,
221
+ #crispr-preset-pills {
222
+ display: inline-flex;
223
+ align-items: center;
224
+ gap: 2px;
225
+ }
226
+
227
+ .preset-group-label {
228
+ font-family: var(--font-mono);
229
+ font-size: 9.5px;
230
+ font-weight: 600;
231
+ text-transform: uppercase;
232
+ letter-spacing: 0.06em;
233
+ color: var(--ink-muted);
234
+ padding: 0 5px 0 6px;
235
+ white-space: nowrap;
236
+ }
237
+
238
+ .preset-divider {
239
+ width: 1px;
240
+ height: 16px;
241
+ background: var(--border-strong);
242
+ margin: 0 3px;
243
+ flex-shrink: 0;
244
+ }
245
+
246
+ .preset-pill {
247
+ appearance: none;
248
+ border: 1px solid transparent;
249
+ background: transparent;
250
+ color: var(--ink-body);
251
+ font-family: var(--font-display);
252
+ font-size: 12px;
253
+ font-weight: 600;
254
+ padding: 5px 10px;
255
+ border-radius: 8px;
256
+ cursor: pointer;
257
+ display: inline-flex;
258
+ align-items: center;
259
+ gap: 5px;
260
+ white-space: nowrap;
261
+ transition: background 140ms ease, color 140ms ease, border-color 140ms ease, box-shadow 140ms ease;
262
+ }
263
+
264
+ .preset-pill:hover {
265
+ color: var(--ink-strong);
266
+ background: var(--bg-pill-hover);
267
+ }
268
+
269
+ .preset-pill.active {
270
+ background: var(--bg-pill-active);
271
+ color: var(--blue-accent-ink);
272
+ border-color: var(--border-strong);
273
+ box-shadow: var(--shadow-active-pill);
274
+ }
275
+
276
+ .run-controls {
277
+ display: flex;
278
+ align-items: center;
279
+ gap: 7px;
280
+ flex-shrink: 0;
281
+ }
282
+
283
+ .theme-toggle-btn {
284
+ appearance: none;
285
+ border: 1px solid var(--border-strong);
286
+ background: var(--bg-pill);
287
+ color: var(--ink-body);
288
+ font-family: var(--font-display);
289
+ font-size: 12px;
290
+ font-weight: 600;
291
+ padding: 6px 11px;
292
+ border-radius: 9px;
293
+ cursor: pointer;
294
+ display: inline-flex;
295
+ align-items: center;
296
+ gap: 6px;
297
+ transition: background 140ms ease, color 140ms ease, border-color 140ms ease;
298
+ }
299
+
300
+ .theme-toggle-btn:hover {
301
+ background: var(--bg-pill-hover);
302
+ color: var(--ink-strong);
303
+ }
304
+
305
+ .theme-icon {
306
+ width: 14px;
307
+ height: 14px;
308
+ display: block;
309
+ }
310
+
311
+ body.theme-dark .icon-moon {
312
+ display: none;
313
+ }
314
+
315
+ body.theme-light .icon-sun {
316
+ display: none;
317
+ }
318
+
319
+ .customize-toggle-btn {
320
+ appearance: none;
321
+ border: 1px solid var(--border-strong);
322
+ background: var(--bg-pill);
323
+ color: var(--ink-body);
324
+ font-family: var(--font-display);
325
+ font-size: 12px;
326
+ font-weight: 600;
327
+ padding: 6px 12px;
328
+ border-radius: 9px;
329
+ cursor: pointer;
330
+ transition: background 140ms ease, color 140ms ease, border-color 140ms ease;
331
+ }
332
+
333
+ .customize-toggle-btn:hover,
334
+ .customize-toggle-btn.open {
335
+ background: var(--bg-pill-hover);
336
+ color: var(--ink-strong);
337
+ }
338
+
339
+ .reset-btn {
340
+ appearance: none;
341
+ border: 1px solid var(--border-strong);
342
+ background: var(--bg-pill);
343
+ color: var(--ink-muted);
344
+ font-family: var(--font-display);
345
+ font-size: 12px;
346
+ font-weight: 600;
347
+ padding: 6.5px 11px;
348
+ border-radius: 9px;
349
+ cursor: pointer;
350
+ display: inline-flex;
351
+ align-items: center;
352
+ gap: 5px;
353
+ transition: background 140ms ease, color 140ms ease, border-color 140ms ease;
354
+ }
355
+
356
+ .reset-btn.can-reset {
357
+ color: var(--ink-strong);
358
+ }
359
+
360
+ .reset-btn:hover {
361
+ background: var(--bg-pill-hover);
362
+ color: var(--ink-strong);
363
+ }
364
+
365
+ .reset-icon {
366
+ width: 13.5px;
367
+ height: 13.5px;
368
+ display: block;
369
+ }
370
+
371
+ .run-cta-btn {
372
+ appearance: none;
373
+ border: 1px solid rgba(255, 255, 255, 0.16);
374
+ background: linear-gradient(180deg, var(--blue-primary) 0%, #1956cc 100%);
375
+ color: #ffffff;
376
+ font-family: var(--font-display);
377
+ font-size: 12.5px;
378
+ font-weight: 600;
379
+ letter-spacing: 0.01em;
380
+ padding: 7.5px 16px;
381
+ border-radius: 9px;
382
+ cursor: pointer;
383
+ white-space: nowrap;
384
+ box-shadow: 0 4px 14px rgba(43, 116, 255, 0.36), inset 0 1px 0 rgba(255, 255, 255, 0.24);
385
+ transition: transform 120ms ease, box-shadow 140ms ease, filter 140ms ease;
386
+ min-width: 140px;
387
+ text-align: center;
388
+ }
389
+
390
+ .run-cta-btn:hover:not(:disabled) {
391
+ filter: brightness(1.07);
392
+ box-shadow: 0 6px 20px rgba(43, 116, 255, 0.46), inset 0 1px 0 rgba(255, 255, 255, 0.3);
393
+ }
394
+
395
+ .run-cta-btn:active:not(:disabled) {
396
+ transform: translateY(1px);
397
+ }
398
+
399
+ .run-cta-btn:disabled {
400
+ background: #334155;
401
+ border-color: transparent;
402
+ box-shadow: none;
403
+ cursor: wait;
404
+ }
405
+
406
+ /* Floating Customize Drawer */
407
+ .customize-popover {
408
+ position: absolute;
409
+ top: calc(100% + 8px);
410
+ right: 16px;
411
+ width: min(650px, calc(100vw - 48px));
412
+ background: var(--bg-card-solid);
413
+ border: 1px solid var(--border-strong);
414
+ border-radius: 16px;
415
+ box-shadow: var(--shadow-popover);
416
+ padding: 18px 20px;
417
+ z-index: 40;
418
+ display: flex;
419
+ flex-direction: column;
420
+ gap: 14px;
421
+ }
422
+
423
+ .popover-top {
424
+ display: flex;
425
+ align-items: center;
426
+ justify-content: space-between;
427
+ gap: 12px;
428
+ }
429
+
430
+ .popover-tabs {
431
+ display: inline-flex;
432
+ background: var(--bg-pill);
433
+ padding: 3px;
434
+ border-radius: 9px;
435
+ border: 1px solid var(--border-subtle);
436
+ }
437
+
438
+ .pop-tab-btn {
439
+ appearance: none;
440
+ border: none;
441
+ background: transparent;
442
+ font-family: var(--font-display);
443
+ font-size: 12px;
444
+ font-weight: 600;
445
+ color: var(--ink-muted);
446
+ padding: 5px 12px;
447
+ border-radius: 7px;
448
+ cursor: pointer;
449
+ }
450
+
451
+ .pop-tab-btn.active {
452
+ background: var(--bg-pill-active);
453
+ color: var(--blue-accent-ink);
454
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.14);
455
+ }
456
+
457
+ .popover-close-btn {
458
+ appearance: none;
459
+ border: 1px solid var(--border-subtle);
460
+ background: var(--bg-pill);
461
+ color: var(--ink-body);
462
+ font-family: var(--font-display);
463
+ font-size: 12px;
464
+ font-weight: 600;
465
+ padding: 5px 11px;
466
+ border-radius: 7px;
467
+ cursor: pointer;
468
+ }
469
+
470
+ .popover-grid {
471
+ display: grid;
472
+ grid-template-columns: 204px minmax(0, 1fr);
473
+ gap: 16px;
474
+ align-items: center;
475
+ }
476
+
477
+ .mini-mol-box {
478
+ height: 156px;
479
+ border-radius: 12px;
480
+ border: 1px solid var(--border-subtle);
481
+ background: var(--bg-input);
482
+ position: relative;
483
+ cursor: grab;
484
+ overflow: hidden;
485
+ }
486
+
487
+ .mini-mol-canvas {
488
+ width: 100%;
489
+ height: 100%;
490
+ display: block;
491
+ }
492
+
493
+ .popover-fields {
494
+ display: flex;
495
+ flex-direction: column;
496
+ gap: 10px;
497
+ }
498
+
499
+ .pop-row {
500
+ display: flex;
501
+ align-items: center;
502
+ justify-content: space-between;
503
+ gap: 8px;
504
+ font-size: 12px;
505
+ font-weight: 500;
506
+ color: var(--ink-body);
507
+ }
508
+
509
+ .pop-mono {
510
+ font-family: var(--font-mono);
511
+ font-size: 11.5px;
512
+ color: var(--ink-strong);
513
+ }
514
+
515
+ .pop-input {
516
+ width: 100%;
517
+ background: var(--bg-input);
518
+ border: 1px solid var(--border-strong);
519
+ border-radius: 8px;
520
+ padding: 7px 10px;
521
+ font-family: var(--font-mono);
522
+ font-size: 12px;
523
+ color: var(--ink-strong);
524
+ }
525
+
526
+ .pop-btn-secondary {
527
+ appearance: none;
528
+ border: 1px solid var(--border-strong);
529
+ background: var(--bg-pill);
530
+ color: var(--ink-strong);
531
+ font-family: var(--font-display);
532
+ font-size: 11.5px;
533
+ font-weight: 600;
534
+ padding: 5px 10px;
535
+ border-radius: 7px;
536
+ cursor: pointer;
537
+ }
538
+
539
+ .pop-btn-secondary:hover {
540
+ background: var(--bg-pill-hover);
541
+ }
542
+
543
+ .pop-slider {
544
+ -webkit-appearance: none;
545
+ appearance: none;
546
+ width: 100%;
547
+ height: 6px;
548
+ border-radius: 999px;
549
+ background: var(--bar-track-fill);
550
+ border: 1px solid var(--border-subtle);
551
+ outline: none;
552
+ cursor: pointer;
553
+ }
554
+
555
+ .pop-slider::-webkit-slider-thumb {
556
+ -webkit-appearance: none;
557
+ appearance: none;
558
+ width: 15px;
559
+ height: 15px;
560
+ border-radius: 50%;
561
+ background: var(--blue-primary);
562
+ border: 2px solid #ffffff;
563
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
564
+ cursor: pointer;
565
+ }
566
+
567
+ .pop-slider::-moz-range-thumb {
568
+ width: 15px;
569
+ height: 15px;
570
+ border-radius: 50%;
571
+ background: var(--blue-primary);
572
+ border: 2px solid #ffffff;
573
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
574
+ cursor: pointer;
575
+ }
576
+
577
+ .pop-gene-chips {
578
+ display: flex;
579
+ flex-wrap: wrap;
580
+ gap: 5px;
581
+ }
582
+
583
+ .pop-gene-chip {
584
+ appearance: none;
585
+ border: 1px solid var(--border-subtle);
586
+ background: var(--bg-pill);
587
+ color: var(--ink-body);
588
+ font-family: var(--font-mono);
589
+ font-size: 11px;
590
+ padding: 3px 8px;
591
+ border-radius: 6px;
592
+ cursor: pointer;
593
+ }
594
+
595
+ .pop-gene-chip.active,
596
+ .pop-gene-chip:hover {
597
+ background: var(--blue-tint);
598
+ color: var(--blue-accent-ink);
599
+ border-color: var(--border-strong);
600
+ }
601
+
602
+ /* 2. Hero Illustration Stage (Responsive to Laptop Screen Height) */
603
+ .hero-stage-card {
604
+ position: relative;
605
+ flex: 1 1 auto;
606
+ height: clamp(284px, calc(100dvh - 330px), 540px);
607
+ min-height: 284px;
608
+ background: radial-gradient(
609
+ ellipse 78% 72% at 50% 47%,
610
+ var(--bg-stage-center) 0%,
611
+ var(--bg-stage-mid) 62%,
612
+ var(--bg-stage-edge) 100%
613
+ );
614
+ border: 1px solid var(--border-subtle);
615
+ border-radius: 20px;
616
+ box-shadow: var(--shadow-stage);
617
+ overflow: hidden;
618
+ display: flex;
619
+ flex-direction: column;
620
+ }
621
+
622
+ .hero-canvas-wrap {
623
+ position: relative;
624
+ flex: 1 1 auto;
625
+ min-height: 284px;
626
+ width: 100%;
627
+ user-select: none;
628
+ }
629
+
630
+ .hero-canvas {
631
+ position: absolute;
632
+ inset: 0;
633
+ width: 100%;
634
+ height: 100%;
635
+ display: block;
636
+ }
637
+
638
+ /* 3. Precision Bottom Equalizer Strip */
639
+ .bottom-strip {
640
+ position: relative;
641
+ flex: 0 0 auto;
642
+ background: var(--bg-card);
643
+ backdrop-filter: blur(16px);
644
+ -webkit-backdrop-filter: blur(16px);
645
+ border: 1px solid var(--border-subtle);
646
+ border-radius: 16px;
647
+ box-shadow: var(--shadow-bar);
648
+ padding: 11px 18px 12px;
649
+ }
650
+
651
+ .error-inline {
652
+ position: absolute;
653
+ top: 10px;
654
+ right: 18px;
655
+ background: var(--down-tint);
656
+ border: 1px solid rgba(244, 63, 94, 0.32);
657
+ padding: 3px 10px;
658
+ border-radius: 999px;
659
+ font-size: 12px;
660
+ font-weight: 500;
661
+ color: var(--down-ink);
662
+ z-index: 5;
663
+ }
664
+
665
+ .outcome-strip {
666
+ display: flex;
667
+ flex-direction: column;
668
+ gap: 8px;
669
+ }
670
+
671
+ .outcome-header-block {
672
+ display: flex;
673
+ flex-direction: column;
674
+ gap: 3px;
675
+ }
676
+
677
+ .outcome-headline {
678
+ margin: 0;
679
+ font-family: var(--font-display);
680
+ font-size: 15px;
681
+ line-height: 1.32;
682
+ font-weight: 600;
683
+ letter-spacing: -0.012em;
684
+ color: var(--ink-strong);
685
+ white-space: normal;
686
+ overflow-wrap: break-word;
687
+ }
688
+
689
+ .outcome-headline.muted-state {
690
+ color: var(--ink-muted);
691
+ font-weight: 500;
692
+ }
693
+
694
+ .outcome-meta-line {
695
+ display: flex;
696
+ align-items: center;
697
+ justify-content: space-between;
698
+ gap: 12px;
699
+ flex-wrap: wrap;
700
+ }
701
+
702
+ .outcome-sub {
703
+ font-family: var(--font-mono);
704
+ font-size: 11px;
705
+ color: var(--ink-muted);
706
+ white-space: nowrap;
707
+ }
708
+
709
+ .outcome-badges {
710
+ display: flex;
711
+ align-items: center;
712
+ gap: 7px;
713
+ flex-shrink: 0;
714
+ }
715
+
716
+ .outcome-action-btn {
717
+ appearance: none;
718
+ height: 23px;
719
+ border: 1px solid var(--border-strong);
720
+ background: var(--bg-pill);
721
+ color: var(--ink-body);
722
+ font-family: var(--font-mono);
723
+ font-size: 11px;
724
+ font-weight: 600;
725
+ padding: 0 9px;
726
+ border-radius: 999px;
727
+ cursor: pointer;
728
+ display: inline-flex;
729
+ align-items: center;
730
+ gap: 4px;
731
+ white-space: nowrap;
732
+ transition: background 120ms ease, color 120ms ease, border-color 120ms ease;
733
+ }
734
+
735
+ .outcome-action-btn:hover {
736
+ background: var(--bg-pill-hover);
737
+ color: var(--ink-strong);
738
+ border-color: var(--blue-accent-ink);
739
+ }
740
+
741
+ .pill-stat-up,
742
+ .pill-stat-down {
743
+ height: 24px;
744
+ display: inline-flex;
745
+ align-items: center;
746
+ font-family: var(--font-mono);
747
+ font-size: 11.5px;
748
+ font-weight: 600;
749
+ padding: 0 10px;
750
+ border-radius: 999px;
751
+ white-space: nowrap;
752
+ }
753
+
754
+ .pill-stat-up {
755
+ color: var(--up-ink);
756
+ background: var(--up-tint);
757
+ border: 1px solid rgba(16, 185, 129, 0.22);
758
+ }
759
+
760
+ .pill-stat-down {
761
+ color: var(--down-ink);
762
+ background: var(--down-tint);
763
+ border: 1px solid rgba(244, 63, 94, 0.22);
764
+ }
765
+
766
+ .pill-stat-up.pill-stat-muted,
767
+ .pill-stat-down.pill-stat-muted {
768
+ color: var(--ink-muted);
769
+ background: var(--bar-track-fill);
770
+ border-color: var(--border-subtle);
771
+ }
772
+
773
+ .bars-two-col {
774
+ display: grid;
775
+ grid-template-columns: 1fr 1fr;
776
+ gap: 28px;
777
+ }
778
+
779
+ .bars-column {
780
+ display: flex;
781
+ flex-direction: column;
782
+ gap: 4px;
783
+ }
784
+
785
+ .bars-col-label {
786
+ height: 18px;
787
+ display: flex;
788
+ align-items: center;
789
+ font-family: var(--font-mono);
790
+ font-size: 10.5px;
791
+ font-weight: 700;
792
+ letter-spacing: 0.05em;
793
+ text-transform: uppercase;
794
+ padding: 0 8px 2px;
795
+ }
796
+
797
+ .bars-col-label.up {
798
+ color: var(--up-ink);
799
+ }
800
+
801
+ .bars-col-label.down {
802
+ color: var(--down-ink);
803
+ }
804
+
805
+ #bars-up-list,
806
+ #bars-down-list {
807
+ display: flex;
808
+ flex-direction: column;
809
+ gap: 3px;
810
+ }
811
+
812
+ .bar-row {
813
+ appearance: none;
814
+ border: 1px solid transparent;
815
+ background: transparent;
816
+ width: 100%;
817
+ height: 25px;
818
+ padding: 0 8px;
819
+ border-radius: 7px;
820
+ display: grid;
821
+ grid-template-columns: 82px 44px 176px minmax(0, 1fr) 114px;
822
+ align-items: center;
823
+ gap: 10px;
824
+ cursor: pointer;
825
+ text-align: left;
826
+ transition: background 120ms ease, border-color 120ms ease;
827
+ }
828
+
829
+ .bar-row.empty-slot {
830
+ cursor: default;
831
+ pointer-events: none;
832
+ }
833
+
834
+ .bar-row:not(.empty-slot):hover,
835
+ .bar-row.focused {
836
+ background: var(--row-hover-bg);
837
+ border-color: var(--border-subtle);
838
+ }
839
+
840
+ .bar-sym {
841
+ font-family: var(--font-mono);
842
+ font-size: 12px;
843
+ font-weight: 700;
844
+ color: var(--ink-strong);
845
+ white-space: nowrap;
846
+ }
847
+
848
+ .bar-sym.empty {
849
+ color: var(--ink-muted);
850
+ opacity: 0.44;
851
+ font-weight: 500;
852
+ }
853
+
854
+ .bar-loc-pill {
855
+ font-family: var(--font-mono);
856
+ font-size: 9.5px;
857
+ font-weight: 600;
858
+ letter-spacing: 0.04em;
859
+ text-transform: uppercase;
860
+ text-align: center;
861
+ color: var(--loc-badge-ink);
862
+ background: var(--loc-badge-bg);
863
+ padding: 2px 5px;
864
+ border-radius: 5px;
865
+ }
866
+
867
+ .bar-loc-pill.empty {
868
+ opacity: 0.42;
869
+ }
870
+
871
+ .bar-role {
872
+ font-size: 12px;
873
+ color: var(--ink-muted);
874
+ white-space: nowrap;
875
+ overflow: hidden;
876
+ text-overflow: ellipsis;
877
+ }
878
+
879
+ .bar-role-placeholder {
880
+ display: block;
881
+ width: 58%;
882
+ height: 5px;
883
+ border-radius: 999px;
884
+ background: var(--bar-track-fill);
885
+ opacity: 0.68;
886
+ }
887
+
888
+ .bar-svg {
889
+ width: 100%;
890
+ height: 9px;
891
+ display: block;
892
+ }
893
+
894
+ .bar-track {
895
+ fill: var(--bar-track-fill);
896
+ }
897
+
898
+ .bar-fill-up {
899
+ fill: var(--up-bright);
900
+ }
901
+
902
+ .bar-fill-down {
903
+ fill: var(--down-bright);
904
+ }
905
+
906
+ .bar-delta {
907
+ font-family: var(--font-mono);
908
+ font-size: 12px;
909
+ font-weight: 700;
910
+ text-align: right;
911
+ white-space: nowrap;
912
+ display: inline-flex;
913
+ align-items: baseline;
914
+ justify-content: flex-end;
915
+ gap: 5px;
916
+ }
917
+
918
+ .bar-delta-sub {
919
+ font-size: 10.5px;
920
+ font-weight: 500;
921
+ color: var(--ink-muted);
922
+ opacity: 0.78;
923
+ }
924
+
925
+ .bar-delta.up {
926
+ color: var(--up-ink);
927
+ }
928
+
929
+ .bar-delta.down {
930
+ color: var(--down-ink);
931
+ }
932
+
933
+ .bar-delta.empty {
934
+ color: var(--ink-muted);
935
+ opacity: 0.42;
936
+ font-weight: 500;
937
+ }
938
+
939
+ /* Raw Prompt & Model Output Inspector Modal */
940
+ .prompt-modal-backdrop {
941
+ position: fixed;
942
+ inset: 0;
943
+ background: rgba(3, 7, 18, 0.72);
944
+ backdrop-filter: blur(6px);
945
+ -webkit-backdrop-filter: blur(6px);
946
+ display: flex;
947
+ align-items: center;
948
+ justify-content: center;
949
+ padding: 20px;
950
+ z-index: 90;
951
+ }
952
+
953
+ .prompt-modal-card {
954
+ width: min(880px, 100%);
955
+ max-height: min(82dvh, 720px);
956
+ background: var(--bg-card-solid);
957
+ border: 1px solid var(--border-strong);
958
+ border-radius: 16px;
959
+ box-shadow: var(--shadow-popover);
960
+ display: flex;
961
+ flex-direction: column;
962
+ overflow: hidden;
963
+ }
964
+
965
+ .prompt-modal-header {
966
+ padding: 14px 18px;
967
+ border-bottom: 1px solid var(--border-subtle);
968
+ display: flex;
969
+ align-items: center;
970
+ justify-content: space-between;
971
+ gap: 12px;
972
+ }
973
+
974
+ .prompt-modal-title {
975
+ margin: 0;
976
+ font-family: var(--font-display);
977
+ font-size: 14.5px;
978
+ font-weight: 600;
979
+ color: var(--ink-strong);
980
+ }
981
+
982
+ .prompt-modal-sub {
983
+ margin: 2px 0 0;
984
+ font-family: var(--font-mono);
985
+ font-size: 11px;
986
+ color: var(--ink-muted);
987
+ }
988
+
989
+ .prompt-modal-actions {
990
+ display: flex;
991
+ align-items: center;
992
+ gap: 8px;
993
+ flex-shrink: 0;
994
+ }
995
+
996
+ .prompt-modal-body {
997
+ padding: 14px 18px 18px;
998
+ overflow-y: auto;
999
+ display: flex;
1000
+ flex-direction: column;
1001
+ gap: 10px;
1002
+ }
1003
+
1004
+ .prompt-section-label {
1005
+ font-family: var(--font-mono);
1006
+ font-size: 10.5px;
1007
+ font-weight: 700;
1008
+ letter-spacing: 0.04em;
1009
+ text-transform: uppercase;
1010
+ color: var(--blue-accent-ink);
1011
+ }
1012
+
1013
+ .prompt-code-box {
1014
+ margin: 0;
1015
+ padding: 12px 14px;
1016
+ background: var(--bg-input);
1017
+ border: 1px solid var(--border-subtle);
1018
+ border-radius: 10px;
1019
+ font-family: var(--font-mono);
1020
+ font-size: 11.5px;
1021
+ line-height: 1.5;
1022
+ color: var(--ink-body);
1023
+ white-space: pre-wrap;
1024
+ word-break: break-word;
1025
+ max-height: 290px;
1026
+ overflow-y: auto;
1027
+ }
1028
+
1029
+ .prompt-code-box-compact {
1030
+ max-height: 150px;
1031
+ }
1032
+
1033
+ @media (max-width: 1320px) {
1034
+ .preset-group-label {
1035
+ display: none;
1036
+ }
1037
+
1038
+ .preset-pill {
1039
+ padding: 4.5px 8.5px;
1040
+ font-size: 11.5px;
1041
+ }
1042
+ }
1043
+
1044
+ @media (max-width: 1120px) {
1045
+ .top-bar {
1046
+ flex-wrap: wrap;
1047
+ }
1048
+
1049
+ .preset-strip {
1050
+ flex-wrap: wrap;
1051
+ }
1052
+
1053
+ .hero-stage-card {
1054
+ height: auto;
1055
+ min-height: 360px;
1056
+ }
1057
+
1058
+ .bars-two-col {
1059
+ grid-template-columns: 1fr;
1060
+ gap: 14px;
1061
+ }
1062
+
1063
+ .popover-grid {
1064
+ grid-template-columns: 1fr;
1065
+ }
1066
+
1067
+ .bar-row {
1068
+ grid-template-columns: 78px 42px 140px minmax(0, 1fr) 102px;
1069
+ }
1070
+ }