baseball-engine / tools /setup_full_worker.py
github-actions[bot]
Automated Deploy: a19ede424a80b7b8d7f6978585141d1bb45de69c
326d3cc
Raw History Blame Contribute Delete
5.04 kB
"""Explicit Colab/Linux Python 3.11 candidate setup; never executed inside inference."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import hashlib
SAM_REVISION="b5c765a0d89d789985e186d396315e7590887b94"
MS_REVISION="aef4e46c31bc7b2462065354054f968f91e54be1"
ROOT=Path(__file__).resolve().parents[1]
def run(*command,env=None):subprocess.run(list(map(str,command)),check=True,env=env)
def clone(url,revision,path):
if not (path/".git").exists():
path.mkdir(parents=True,exist_ok=True);run("git","init",path);run("git","-C",path,"remote","add","origin",url)
run("git","-C",path,"fetch","--depth=1","origin",revision)
run("git","-C",path,"checkout","--detach",revision)
actual=subprocess.check_output(["git","-C",str(path),"rev-parse","HEAD"],text=True).strip()
if actual!=revision:raise ValueError("Source revision mismatch")
def checksum(path):
h=hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda:f.read(1024*1024),b""):h.update(chunk)
return h.hexdigest()
def main():
p=argparse.ArgumentParser();p.add_argument("--workspace",required=True);p.add_argument("--download-models",action="store_true")
p.add_argument("--hf-revision",help="Full accessible model commit; omitted resolves and records once")
args=p.parse_args();workspace=Path(args.workspace).resolve();workspace.mkdir(parents=True,exist_ok=True)
status={"status":"candidate","profile":"linux_python311_cuda128_fp32","source_revisions":{"sam":SAM_REVISION,"mstcn":MS_REVISION}}
try:
if not sys.platform.startswith("linux"):raise ValueError("This candidate installer targets Colab Linux")
run(sys.executable,"-m","pip","install","uv==0.9.10")
env=dict(os.environ);env["UV_PYTHON_INSTALL_DIR"]=str(workspace/"python-runtimes")
run(sys.executable,"-m","uv","python","install","3.11",env=env)
runtime=workspace/".runtime-full";worker=runtime/"bin/python"
if not worker.exists():run(sys.executable,"-m","uv","venv","--python","3.11","--seed",runtime,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","opensim==4.6")
run(worker,"-m","pip","install","onnxruntime-gpu[cuda,cudnn]==1.26.0","requests==2.32.5","tqdm==4.67.1")
run(worker,"-m","pip","install","--no-deps","rtmlib==0.0.16")
run(worker,"-m","pip","install","git+https://github.com/facebookresearch/detectron2.git@a1ce2f9","--no-build-isolation","--no-deps")
sam=workspace/"source-sam";ms=workspace/"source-mstcn"
clone("https://github.com/facebookresearch/sam-3d-body.git",SAM_REVISION,sam)
clone("https://github.com/sj-li/MS-TCN2.git",MS_REVISION,ms)
status.update({"worker_python":str(worker),"sam_repo":str(sam),"mstcn_repo":str(ms)})
freeze=subprocess.check_output([str(worker),"-m","pip","freeze","--all"],text=True).splitlines()
status["resolved_packages"]=freeze
if args.download_models:
# Uses normal HF_TOKEN / cached provider login. Credentials never enter
# arguments, this status record or project configuration.
helper=workspace/"download_sam.py"
helper.write_text('''import json,sys\nfrom huggingface_hub import HfApi,snapshot_download\nrepo="facebook/sam-3d-body-vith"\nrevision=sys.argv[1] or HfApi().model_info(repo).sha\npath=snapshot_download(repo_id=repo,revision=revision,allow_patterns=["model.ckpt","model_config.yaml","assets/*"])\nprint(json.dumps({"revision":revision,"path":path}))\n''')
completed=subprocess.run([str(worker),str(helper),args.hf_revision or ""],capture_output=True,text=True)
helper.unlink()
if completed.returncode:raise RuntimeError("SAM provider download unavailable; authenticate and request normal provider access")
record=json.loads(completed.stdout.splitlines()[-1]);snapshot=Path(record["path"])
paths={"sam_checkpoint":snapshot/"model.ckpt","sam_config":snapshot/"model_config.yaml","mhr_path":snapshot/"assets/mhr_model.pt"}
if not all(v.is_file() for v in paths.values()):raise ValueError("Provider snapshot missing expected assets")
status.update({k:str(v) for k,v in paths.items()});status["hf_revision"]=record["revision"]
status["artifact_hashes"]={k:checksum(v) for k,v in paths.items()}
status["status"]="installed_requires_preflight"
except Exception as error:
status["status"]="unavailable";status["reason"]=str(error)[:250]
(workspace/"full-worker.json").write_text(json.dumps(status,indent=2))
print(json.dumps({"status":status["status"],"record":str(workspace/"full-worker.json"),"reason":status.get("reason")}))
return 0 if status["status"]=="installed_requires_preflight" else 1
if __name__=="__main__":sys.exit(main())