"""Public simulator for the Udgam Labs virtual-cell model (Hugging Face Docker Space). A Python stdlib web server. It loads the three-copy ensemble once and serves: GET / the page (static/index.html, with the model name filled in) GET /api/perturb?line=&genes=&modality= GET /api/search?q= GET /api/export_csv?line=&genes=&modality= GET /api/sample_csv POST /api/perturb_csv JSON {csv, genes, modality, label} Errors come back as HTTP 400 with {"error": "..."}. Weights: the folder in env MODEL_DIR; if unset, downloaded from the Hugging Face model repo MODEL_REPO. Listens on 0.0.0.0:$PORT (default 7860). """ import csv import io import json import os import sys import urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import numpy as np # ---- The one place the model's name lives (founder picks tonight) ---- MODEL_NAME = "BioCell" NAME_SLUG = "biocell" MODEL_REPO = f"udgamlabs/{NAME_SLUG}" MODEL_PAGE = f"https://udgamlabs.com/models/{NAME_SLUG}" HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "sdk")) from predict import UdgamVirtualCell # noqa: E402 STATIC = os.path.join(HERE, "static") N_CELLS = 64 TOP_K = 12 MAX_UPLOAD = 25 * 1024 * 1024 def resolve_model_dir(): d = os.environ.get("MODEL_DIR") if d: return d from huggingface_hub import snapshot_download return snapshot_download(repo_id=MODEL_REPO) def build_spectrum(vc, res): """About 300 representative points (baseline, change, symbol, role) across all 3,000 genes for the gene map.""" cm = res["ctrl_cells"].mean(axis=0) dl = res["delta_all"] n = len(dl) up_idx = np.argsort(-dl)[:70] dn_idx = np.argsort(dl)[:70] bg_idx = np.linspace(0, n - 1, 160, dtype=np.int64) chosen = sorted(set(up_idx.tolist()) | set(dn_idx.tolist()) | set(bg_idx.tolist())) return [{ "g": vc.hvg_syms[i], "c": round(float(cm[i]), 3), "d": round(float(dl[i]), 4), "r": vc.gene_info.get(vc.hvg_syms[i], {}).get("short", ""), } for i in chosen] def to_payload(vc, res): payload = {k: v for k, v in res.items() if k not in ("pred_cells", "ctrl_cells", "delta_all")} payload["spectrum"] = build_spectrum(vc, res) return payload def parse_query(u): q = urllib.parse.parse_qs(u.query) line = q.get("line", ["rpe1"])[0] genes = [g for g in q.get("genes", ["PSMA3"])[0].split(",") if g.strip()] mod = q.get("modality", ["knockdown"])[0] return line, genes, mod def load_page(): with open(os.path.join(STATIC, "index.html"), encoding="utf-8") as f: html = f.read() with open(os.path.join(STATIC, "lockup.svg"), encoding="utf-8") as f: lockup = f.read().replace('fill="#1C1B18"', 'fill="currentColor"') lockup = lockup.replace(" MAX_UPLOAD: raise ValueError("The file is larger than the 25 MB limit.") data = json.loads(self.rfile.read(nbytes).decode("utf-8")) res = vc.perturb_csv_text( data.get("csv", ""), genes=[g for g in str(data.get("genes", "PSMA3")).split(",") if g.strip()], modality=data.get("modality", "knockdown"), label=str(data.get("label", "Your cells"))[:80], top_k=TOP_K, ) self._json(200, to_payload(vc, res)) except Exception as ex: self._json(400, {"error": str(ex)}) return H def main(): model_dir = resolve_model_dir() vc = UdgamVirtualCell.load(model_dir, device="cpu") port = int(os.environ.get("PORT", "7860")) host = os.environ.get("HOST", "0.0.0.0") print(f"{MODEL_NAME} simulator on http://{host}:{port} ({len(vc.models)} copies, " f"{len(vc.prior_map)} genes, {len(vc.atlas.get('systems', []))} systems)", flush=True) ThreadingHTTPServer((host, port), make_handler(vc)).serve_forever() if __name__ == "__main__": main()