"""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} POST /api/used?s=&via= the page says a visitor saw a prediction they asked for (counted as one run) 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 re import sys import threading import urllib.parse import urllib.request from collections import OrderedDict 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 # ---- Anonymous use counts (udgam/CLAUDE.md: every Space and in-browser use is counted; same rules as udgam_count.py) ---- # mcp.udgamlabs.com/count gets one "load" per visitor tab (from "server": this Space already holds the model) and one # "run" per prediction a visitor asks for; Hugging Face gets one HEAD of config.json on that first load, so each visitor # shows once in the model's download count. Never the genes, the cells, the IP address or the tab id are sent. The tab id # (?s=) is a random string the page makes per tab; it is kept in memory only (the last 20,000). via=site when the page is # embedded on udgamlabs.com, via=web on the Space; no id at all means a script calling the API (each call is a visit). # A private test copy sets UDGAM_COUNT_TEST=1: its counts carry "test": true and it sends Hugging Face nothing. COUNT_URL = os.environ.get("UDGAM_COUNT_URL", "https://mcp.udgamlabs.com/count") # override only for local tests COUNTED_FILE = f"https://huggingface.co/{MODEL_REPO}/resolve/main/config.json" _UA = "udgamlabs-space" # Cloudflare refuses Python's default user-agent _TEST = os.environ.get("UDGAM_COUNT_TEST") == "1" _SEEN = OrderedDict() _SEEN_LOCK = threading.Lock() _SID = re.compile(r"^[a-z0-9]{6,16}$") def _bg(fn): threading.Thread(target=fn, daemon=True).start() def _post(body): if _TEST: body = {**body, "test": True} data = json.dumps(body).encode() def send(): try: urllib.request.urlopen(urllib.request.Request(COUNT_URL, data=data, method="POST", headers={"content-type": "text/plain", "user-agent": _UA}), timeout=5) except Exception: pass _bg(send) def _head_counted_file(): if _TEST: return def send(): try: urllib.request.urlopen(urllib.request.Request(COUNTED_FILE, method="HEAD", headers={"user-agent": _UA}), timeout=10) except Exception: pass _bg(send) def _visit(q): """(channel, first) for this request; first is True on a tab's first request, or on every call without a tab id.""" via = q.get("via", [""])[0] sid = q.get("s", [""])[0] if not _SID.match(sid): return "space-api", True ch = "site" if via == "site" else "space-web" with _SEEN_LOCK: if sid in _SEEN: return ch, False _SEEN[sid] = True while len(_SEEN) > 20000: _SEEN.popitem(last=False) return ch, True def count_use(q, run=None): """Count a visit (once per tab) and, if run is True or False, one run with that outcome. Never raises.""" try: ch, first = _visit(q) if first: _post({"model": NAME_SLUG, "lang": "en", "action": "load", "outcome": "ok", "channel": ch, "from": "server"}) _head_counted_file() if run is not None: _post({"model": NAME_SLUG, "lang": "en", "action": "run", "outcome": "ok" if run else "error", "channel": ch}) except Exception: pass # counting must never break a request 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)) count_use(q, True) except Exception as ex: self._json(400, {"error": str(ex)}) count_use(q, False) 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()