Download app.py from udgamlabs/biocell: direct link, hf CLI and curl.
- Browser
- Download file 8.29 kB
-
https://huggingface.co/spaces/udgamlabs/biocell/resolve/main/app.py
- Command line
-
hf download hf://spaces/udgamlabs/biocell/app.py
-
curl -L -o app.py https://huggingface.co/spaces/udgamlabs/biocell/resolve/main/app.py
8.29 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} | |
| 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("<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) | |
| try: | |
| res = vc.perturb(line, genes, modality=mod, n_cells=N_CELLS, top_k=TOP_K) | |
| self._json(200, to_payload(vc, res)) | |
| except Exception as ex: | |
| self._json(400, {"error": str(ex)}) | |
| 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) | |
| 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)) | |
| 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() | |