"""Install isolated SAM event inference, or reuse an existing full-worker record. No OpenSim, anatomy checks, temporal fitting, MS-TCN or segmentation models. Model acquisition uses normal HF_TOKEN/provider access, outside inference. """ import argparse import json import os from pathlib import Path import subprocess import sys from tools.setup_full_worker import ROOT, SAM_REVISION, clone, checksum, run def main(): parser = argparse.ArgumentParser() parser.add_argument("--workspace", required=True) parser.add_argument("--reuse-record") args = parser.parse_args() workspace = Path(args.workspace).resolve(); workspace.mkdir(parents=True, exist_ok=True) destination = workspace/"sam-api-worker.json" try: if args.reuse_record: old = json.loads(Path(args.reuse_record).read_text()) keys = ("worker_python", "sam_repo", "sam_checkpoint", "sam_config", "mhr_path") record = {k: old[k] for k in keys} if not all(Path(value).exists() for value in record.values()): raise ValueError("Existing SAM record has missing files") else: if not sys.platform.startswith("linux"): raise ValueError("SAM setup requires Linux with NVIDIA GPU") run(sys.executable, "-m", "pip", "install", "uv==0.9.10") env = dict(os.environ, UV_PYTHON_INSTALL_DIR=str(workspace/"python-runtimes")) run(sys.executable, "-m", "uv", "python", "install", "3.11", env=env) worker = workspace/".runtime-sam-api/bin/python" if not worker.exists(): run(sys.executable, "-m", "uv", "venv", "--python", "3.11", "--seed", worker.parent.parent, env=env) run(worker, "-m", "pip", "install", "torch==2.9.1", "torchvision==0.24.1", "--index-url", "https://download.pytorch.org/whl/cu128") run(worker, "-m", "pip", "install", "-r", ROOT/"requirements-core.txt", "-r", ROOT/"requirements-sam.txt") run(worker, "-m", "pip", "install", "git+https://github.com/facebookresearch/detectron2.git@a1ce2f9", "--no-build-isolation", "--no-deps") sam = workspace/"source-sam" clone("https://github.com/facebookresearch/sam-3d-body.git", SAM_REVISION, sam) # Read credentials only through normal provider authentication. No # token is put in CLI arguments, result files or download errors. script = 'from huggingface_hub import HfApi,snapshot_download; import json; repo="facebook/sam-3d-body-vith"; rev=HfApi().model_info(repo).sha; p=snapshot_download(repo,revision=rev,allow_patterns=["model.ckpt","model_config.yaml","assets/*"]); print(json.dumps({"path":p,"revision":rev}))' download = subprocess.run([str(worker), "-c", script], text=True, capture_output=True) if download.returncode: raise RuntimeError("SAM model access unavailable; approved provider access and HF_TOKEN are required") model = json.loads(download.stdout.splitlines()[-1]); snapshot = Path(model["path"]) record = {"worker_python": str(worker), "sam_repo": str(sam), "sam_checkpoint": str(snapshot/"model.ckpt"), "sam_config": str(snapshot/"model_config.yaml"), "mhr_path": str(snapshot/"assets/mhr_model.pt"), "hf_revision": model["revision"]} revision = subprocess.check_output(["git", "-C", record["sam_repo"], "rev-parse", "HEAD"], text=True).strip() if revision != SAM_REVISION: raise ValueError("SAM source does not match pinned adapter revision") record["artifact_hashes"] = {k: checksum(Path(record[k])) for k in ("sam_checkpoint", "sam_config", "mhr_path")} record.update(status="installed_requires_inference", source_revision=revision, scope="sparse_body_only_event_windows; no anatomy or temporal fitting") destination.write_text(json.dumps(record, indent=2)+"\n") print("SAM configured:", destination, flush=True) return 0 except Exception as error: destination.write_text(json.dumps({"status": "unavailable", "reason": str(error)[:300]}, indent=2)+"\n") print("SAM setup failed:", str(error)[:300], flush=True) return 1 if __name__ == "__main__": raise SystemExit(main())