"""Bundle bootstrap for the U_PAIR_2c EAGLE runner (stdlib only; imported before numpy / torch). A model bundle is a folder with bundle.json version, components, thresholds, runner arguments, checksums of the sources models/ every network / classifier file at the path it had relative to the research root runtime/code/ the runner code (byte-identical copies of the research code) at the same relative paths runtime/eagle_runner.py, runtime/bundle_boot.py The research code locates everything from ONE absolute root path (a literal in a few modules / one JSON config). use_bundle() "renders" runtime/code into a private cache folder with that literal replaced by the cache folder, and links every file of models/ into the same folder, so that every path the code computes lands inside the bundle. Nothing outside the bundle and the cache folder is needed (the research root does not have to exist). The rendered copy is reused while the bundle path and the code checksums are unchanged. """ from __future__ import annotations import hashlib import json import os import shutil import sys import tempfile from pathlib import Path TEXT_EXT = {".py", ".json", ".txt", ".cfg", ".yaml", ".yml", ".sh"} ENV_FIXED = {"C2_ZERO_OUTSIDE": "1", "C2_EXCLUDE_MALFORMED": "1", "OPENBLAS_NUM_THREADS": "1", "TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD": "1"} def _sha(p: Path) -> str: h = hashlib.sha256() with open(p, "rb") as f: for b in iter(lambda: f.read(1 << 20), b""): h.update(b) return h.hexdigest() def bundle_dir_from(argv: list[str]) -> str | None: """--bundle DIR (removed from argv) or $EAGLE_UPAIR_BUNDLE; None = research paths (the default).""" if "--bundle" in argv: i = argv.index("--bundle") d = argv[i + 1] del argv[i:i + 2] return d for a in list(argv): if a.startswith("--bundle="): argv.remove(a) return a.split("=", 1)[1] return os.environ.get("EAGLE_UPAIR_BUNDLE") or None def _cache_root(bundle: Path, meta: dict) -> Path: base = os.environ.get("EAGLE_UPAIR_CACHE") if base: root = Path(base).expanduser() else: xdg = os.environ.get("XDG_CACHE_HOME") root = (Path(xdg) if xdg else Path.home() / ".cache") / "eagleseg" / "bundles" key = hashlib.sha1(f"{bundle}|{meta['version']}|{meta['code']['tree_sha256']}|{json.dumps(meta.get('render_stubs'), sort_keys=True)}".encode()).hexdigest()[:16] return root / f"{meta['version']}_{key}" def _render(bundle: Path, meta: dict, dst: Path) -> None: src_root = meta["code"]["root_literal"] code = bundle / "runtime" / "code" models = bundle / "models" tmp = Path(tempfile.mkdtemp(prefix=".render_", dir=str(dst.parent))) try: new = str(dst) for p in sorted(code.rglob("*")): if p.is_dir(): continue rel = p.relative_to(code) q = tmp / rel q.parent.mkdir(parents=True, exist_ok=True) if p.suffix in TEXT_EXT: txt = p.read_text(encoding="utf-8") q.write_text(txt.replace(src_root, new), encoding="utf-8") else: shutil.copyfile(p, q) for p in sorted(models.rglob("*")): if p.is_dir(): continue rel = p.relative_to(models) q = tmp / rel q.parent.mkdir(parents=True, exist_ok=True) if q.exists(): raise RuntimeError(f"bundle layout error: {rel} is both code and model") os.symlink(str(p.resolve()), q) for rel, content in (meta.get("render_stubs") or {}).items(): # stand-ins for research data files that were left out of the bundle (read at import by code that never uses them # at inference, e.g. a scoring filter); see bundle.json "sanitized" q = tmp / rel if not q.exists(): q.parent.mkdir(parents=True, exist_ok=True) q.write_text(json.dumps(content)) stamp = {"bundle": str(bundle), "version": meta["version"], "tree_sha256": meta["code"]["tree_sha256"], "root": str(dst)} (tmp / ".bundle_render.json").write_text(json.dumps(stamp, indent=1)) try: os.rename(tmp, dst) except OSError: if not _valid(dst, bundle, meta): # another process won the race with a valid copy -> use it raise shutil.rmtree(tmp, ignore_errors=True) except BaseException: shutil.rmtree(tmp, ignore_errors=True) raise def _valid(dst: Path, bundle: Path, meta: dict) -> bool: try: st = json.loads((dst / ".bundle_render.json").read_text()) except (OSError, ValueError): return False return st.get("bundle") == str(bundle) and st.get("tree_sha256") == meta["code"]["tree_sha256"] and st.get("root") == str(dst) def use_bundle(bundle_dir: str) -> dict: """Make this process load the model ONLY from the bundle. Returns {'root': rendered root, 'meta': bundle.json, ...}.""" bundle = Path(bundle_dir).expanduser().resolve() mf = bundle / "bundle.json" if not mf.is_file(): raise SystemExit(f"ERROR not a model bundle (no bundle.json): {bundle}") meta = json.loads(mf.read_text()) if any(c in str(bundle) for c in "\"'\\\n"): raise SystemExit(f"ERROR the bundle path must not contain quotes or backslashes: {bundle}") dst = _cache_root(bundle, meta) dst.parent.mkdir(parents=True, exist_ok=True) if not _valid(dst, bundle, meta): if dst.exists(): shutil.rmtree(dst, ignore_errors=True) _render(bundle, meta, dst) root = str(dst) # environment the research job scripts set (nnU-Net folders, numerics switches), all inside the rendered root os.environ.update({"nnUNet_raw": f"{root}/nnunet_raw", "nnUNet_preprocessed": f"{root}/nnunet_preprocessed", "nnUNet_results": f"{root}/whisper_results", **ENV_FIXED}) os.environ.setdefault("OMP_NUM_THREADS", "2") os.environ.pop("BRAVE_NEW_DAY", None) # optional research-workspace pointer read by some nnU-Net trainer modules os.environ["EAGLE_UPAIR_BUNDLE"] = str(bundle) os.environ["EAGLE_UPAIR_ROOT"] = root # import path: the bundle's code first (nnunetv2 copy, project modules) -- same entries as the research PYTHONPATH for p in reversed(meta["code"]["sys_path"]): sys.path.insert(0, f"{root}/{p}") pp = [f"{root}/{p}" for p in meta["code"]["sys_path"]] old = [x for x in os.environ.get("PYTHONPATH", "").split(os.pathsep) if x] os.environ["PYTHONPATH"] = os.pathsep.join(pp + [x for x in old if x not in pp]) # child processes see the same order os.environ["FASTCASCADE_DIR"] = f"{root}/{meta['code']['fastcascade']}" return {"bundle": str(bundle), "root": root, "meta": meta} def runner_args(info: dict, argv: list[str]) -> list[str]: """argv + the ship model's runner arguments (profile, classifier dirs, union gates) unless the caller gave a profile.""" if "--serve" in argv and "--work_dir" not in argv: # the server's own work folder (it records the model files it was started with) belongs to this bundle copy, not to a # machine-wide /tmp folder shared with other model copies argv = argv + ["--work_dir", f"{info['root']}/.server_work"] if "--profile" in argv: return argv return argv + [a.replace("{root}", info["root"]) for a in info["meta"]["runner_args"]] def verify(bundle_dir: str, quick: bool = False) -> int: """Check every file listed in BUNDLE.sha256 (quick: sizes only). Returns the number of problems.""" bundle = Path(bundle_dir).expanduser().resolve() bad = 0 for line in open(bundle / "BUNDLE.sha256"): if not line.strip(): continue h, rel = line.rstrip("\n").split(" ", 1) p = bundle / rel if not p.is_file(): print(f"MISSING {rel}"); bad += 1; continue if not quick and _sha(p) != h: print(f"CHECKSUM {rel}"); bad += 1 print("bundle OK" if not bad else f"bundle has {bad} problem(s)") return bad