Spaces:
Running

biocell / app.py
jiteshkprasad's picture
BioCell simulator: count use like the other Udgam Labs Spaces (one visit per tab with one HEAD of config.json; one run per prediction asked for; nothing the visitor enters is sent). Founder go 1 Dec 2026
adf814b verified
Raw History Blame Contribute Delete
12.4 kB
"""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("<svg ", '<svg class="lockup" role="img" aria-label="Udgam Labs" ', 1)
lockup = lockup.replace('width="395.02" height="69.5"', "")
return (html.replace("{{LOCKUP}}", lockup)
.replace("{{MODEL_NAME}}", MODEL_NAME)
.replace("{{MODEL_PAGE}}", MODEL_PAGE)
.replace("{{NAME_SLUG}}", NAME_SLUG)).encode("utf-8")
def make_handler(vc):
page = load_page()
class H(BaseHTTPRequestHandler):
def log_message(self, fmt, *a):
pass
def _send(self, code, body, ctype, extra=None):
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
for k, v in (extra or {}).items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(body)
def _json(self, code, obj):
self._send(code, json.dumps(obj).encode("utf-8"), "application/json; charset=utf-8")
def do_GET(self):
u = urllib.parse.urlparse(self.path)
p = u.path
if p in ("/", "/index.html"):
body = load_page() if os.environ.get("DEV_RELOAD") else page
self._send(200, body, "text/html; charset=utf-8", {"Cache-Control": "no-cache"})
elif p == "/api/search":
q = urllib.parse.parse_qs(u.query).get("q", [""])[0]
self._json(200, vc.search_genes(q, limit=12))
elif p == "/api/perturb":
line, genes, mod = parse_query(u)
q = urllib.parse.parse_qs(u.query)
# The page asks ahead (cards it may show) and says /api/used when a visitor sees one, so a request
# from the page counts only the visit; a script's request is its own run.
page_req = bool(_SID.match(q.get("s", [""])[0]))
try:
res = vc.perturb(line, genes, modality=mod, n_cells=N_CELLS, top_k=TOP_K)
self._json(200, to_payload(vc, res))
count_use(q, None if page_req else True)
except Exception as ex:
self._json(400, {"error": str(ex)})
count_use(q, None if page_req else False)
elif p == "/api/export_csv":
line, genes, mod = parse_query(u)
try:
res = vc.perturb(line, genes, modality=mod, n_cells=N_CELLS, top_k=TOP_K)
buf = io.StringIO()
w = csv.writer(buf)
w.writerow(["gene", "role", "ctrl_mean_log1p", "pred_mean_log1p", "delta_log1p"])
cm = res["ctrl_cells"].mean(axis=0)
pm = res["pred_cells"].mean(axis=0)
dl = res["delta_all"]
for i in sorted(range(len(vc.hvg_syms)), key=lambda j: -abs(float(dl[j]))):
sym = vc.hvg_syms[i]
w.writerow([sym, vc.gene_info.get(sym, {}).get("short", ""),
f"{cm[i]:.4f}", f"{pm[i]:.4f}", f"{dl[i]:.4f}"])
fname = f'{NAME_SLUG}_{res["cell_line"]}_{"_".join(res["genes"])}_{res["modality"]}.csv'
self._send(200, buf.getvalue().encode("utf-8"), "text/csv; charset=utf-8",
{"Content-Disposition": f'attachment; filename="{fname}"'})
except Exception as ex:
self._json(400, {"error": str(ex)})
elif p == "/api/sample_csv":
X = vc.line_data["rpe1"]["ctrl_cells"][:16]
buf = io.StringIO()
w = csv.writer(buf)
w.writerow(["cell_id"] + vc.hvg_syms)
for i in range(len(X)):
w.writerow([f"sample_cell_{i + 1}"] + [f"{v:.3f}" for v in X[i]])
self._send(200, buf.getvalue().encode("utf-8"), "text/csv; charset=utf-8",
{"Content-Disposition": f'attachment; filename="{NAME_SLUG}_sample_control_cells.csv"'})
elif p == "/healthz":
self._json(200, {"ok": True, "models": len(vc.models)})
elif p == "/favicon.ico":
self.send_response(204)
self.end_headers()
else:
self._json(404, {"error": "Not found"})
def do_POST(self):
u = urllib.parse.urlparse(self.path)
q = urllib.parse.parse_qs(u.query)
if u.path == "/api/used":
count_use(q, True)
self.send_response(204)
self.end_headers()
return
if u.path != "/api/perturb_csv":
self._json(404, {"error": "Not found"})
return
try:
nbytes = int(self.headers.get("Content-Length", "0"))
if nbytes > 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()