"""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()