File size: 8,238 Bytes
edcc804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""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/<rel>           every network / classifier file at the path it had relative to the research root
    runtime/code/<rel>     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