File size: 6,628 Bytes
a45b7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02cbb89
a45b7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e80498
a45b7c9
 
02cbb89
 
 
 
 
 
 
a45b7c9
 
 
 
 
 
 
 
02cbb89
a45b7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02cbb89
 
8e80498
02cbb89
 
 
a45b7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02cbb89
a45b7c9
 
 
 
 
 
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""Build hypothesis spatial codes from existing native or combined geometry caches."""

from __future__ import annotations

import argparse
import gzip
import json
import os
from pathlib import Path
import pickle
import sys
import types

WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
if str(WORKSPACE_ROOT) not in sys.path:
    sys.path.insert(0, str(WORKSPACE_ROOT))

from encoder import adapters  # noqa: E402
from encoder import config as encoder_config  # noqa: E402
from experiments import config, loader  # noqa: E402
from experiments import adapters as format_adapters  # noqa: E402


class CachedDA3Prediction:
    """Attribute container used only to deserialize cached DA3 Prediction objects."""


class CachedAddictDict(dict):
    """Minimal attribute-access dictionary required by cached DA3 metadata."""

    def __getattr__(self, name):
        if name.startswith("__") and name.endswith("__"):
            raise AttributeError(name)
        try:
            return self[name]
        except KeyError as exc:
            raise AttributeError(name) from exc

    def __setattr__(self, name, value):
        self[name] = value


def install_da3_pickle_compatibility() -> None:
    """Provide the exact pickle class when the original DA3 package is unavailable."""
    try:
        __import__("depth_anything_3.specs")
    except ModuleNotFoundError:
        package = types.ModuleType("depth_anything_3")
        package.__path__ = []
        specs = types.ModuleType("depth_anything_3.specs")
        CachedDA3Prediction.__module__ = "depth_anything_3.specs"
        CachedDA3Prediction.__name__ = "Prediction"
        CachedDA3Prediction.__qualname__ = "Prediction"
        specs.Prediction = CachedDA3Prediction
        package.specs = specs
        sys.modules["depth_anything_3"] = package
        sys.modules["depth_anything_3.specs"] = specs
    try:
        __import__("addict.addict")
    except ModuleNotFoundError:
        package = types.ModuleType("addict")
        package.__path__ = []
        module = types.ModuleType("addict.addict")
        CachedAddictDict.__module__ = "addict.addict"
        CachedAddictDict.__name__ = "Dict"
        CachedAddictDict.__qualname__ = "Dict"
        module.Dict = CachedAddictDict
        package.addict = module
        package.Dict = CachedAddictDict
        sys.modules["addict"] = package
        sys.modules["addict.addict"] = module


def configure_single_scene_threads() -> int:
    """Give a direct single-scene run every CPU available to the process."""
    try:
        count = max(1, len(os.sched_getaffinity(0)))
    except AttributeError:
        count = max(1, os.cpu_count() or 1)
    value = str(count)
    for variable in (
        "OMP_NUM_THREADS",
        "MKL_NUM_THREADS",
        "OPENBLAS_NUM_THREADS",
        "NUMEXPR_NUM_THREADS",
        "VSI_KD_WORKERS",
    ):
        os.environ.setdefault(variable, value)
    return count


def load_existing_geometry(scene, depth, input_selection, tracking, frame_count):
    """Read existing caches without ever creating or modifying source caches."""
    combined_path = Path(
        encoder_config.cache_file(scene, depth, input_selection, tracking, frame_count)
    )
    if combined_path.is_file():
        with gzip.open(combined_path, "rb") as stream:
            return adapters.validate(pickle.load(stream))

    da3_path = Path(
        encoder_config.da3_cache_file(scene, depth, input_selection, frame_count)
    )
    sam3_path = Path(
        encoder_config.sam3_cache_file(scene, input_selection, tracking, frame_count)
    )
    missing = [str(path) for path in (da3_path, sam3_path) if not path.is_file()]
    if missing:
        raise FileNotFoundError(
            "required native cache(s) are missing: " + ", ".join(missing)
        )
    install_da3_pickle_compatibility()
    geometry = adapters.adapt(
        encoder_config.MODEL,
        scene=scene,
        root=str(encoder_config.CACHE_ROOT),
        rebuild=False,
        da3_path=str(da3_path),
        sam3_path=str(sam3_path),
    )
    return adapters.validate(geometry)


def run_scene(
    scene,
    hypothesis,
    depth="metric",
    tracking="tracking",
    input_selection="uniform",
    frame_count=64,
    rebuild=False,
    spatial_code_format="explicit",
):
    output = config.spatial_code_path(
        scene,
        hypothesis,
        depth,
        tracking,
        input_selection,
        frame_count,
        spatial_code_format,
    )
    if output.is_file() and not rebuild:
        with output.open(encoding="utf-8") as stream:
            return json.load(stream), "loaded", output
    geometry = load_existing_geometry(
        scene, depth, input_selection, tracking, frame_count
    )
    geometry_math = loader.load_hypothesis(hypothesis)
    code, *_ = format_adapters.build(geometry_math, geometry, spatial_code_format)
    output.parent.mkdir(parents=True, exist_ok=True)
    geometry_math.dump_spatial_code(code, str(output))
    return code, "built", output


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("scene", nargs="?")
    parser.add_argument("--hypothesis")
    parser.add_argument(
        "--depth", default="metric", choices=encoder_config.DEPTH_VARIANTS
    )
    parser.add_argument(
        "--input",
        default="uniform",
        choices=encoder_config.INPUT_SELECTIONS,
        dest="input_selection",
    )
    parser.add_argument(
        "--tracking", default="tracking", choices=encoder_config.TRACKING_MODES
    )
    parser.add_argument("--frames", type=int, default=64)
    parser.add_argument(
        "--format",
        default="explicit",
        choices=config.SPATIAL_CODE_FORMATS,
        dest="spatial_code_format",
    )
    parser.add_argument("--rebuild", action="store_true")
    parser.add_argument("--list", action="store_true", dest="list_only")
    args = parser.parse_args()
    if args.list_only:
        print("\n".join(loader.list_hypotheses()))
        return
    if not args.scene:
        parser.error("scene is required unless --list is used")
    if not args.hypothesis:
        parser.error("--hypothesis is required unless --list is used")
    if args.frames < 1:
        parser.error("--frames must be positive")
    configure_single_scene_threads()
    _, status, path = run_scene(
        args.scene,
        args.hypothesis,
        args.depth,
        args.tracking,
        args.input_selection,
        args.frames,
        args.rebuild,
        args.spatial_code_format,
    )
    print(f"[{args.scene}] {status} -> {path}")


if __name__ == "__main__":
    main()