File size: 5,847 Bytes
9c890d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build and verify portable SCALE4D view-count bundles."""

from __future__ import annotations

import base64
import gzip
import hashlib
import json
from pathlib import Path, PurePosixPath

import numpy as np


def bundle_path(root: Path, name: str) -> Path:
    relative = PurePosixPath(name)
    if relative.is_absolute() or ".." in relative.parts or not relative.parts:
        raise ValueError(f"Invalid bundle path: {name}")
    path = root.joinpath(*relative.parts)
    if not path.resolve().is_relative_to(root.resolve()):
        raise ValueError(f"Bundle path escapes its directory: {name}")
    return path


def file_sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def verify_bundle(root: Path) -> dict:
    manifest = json.loads((root / "manifest.json").read_text())
    if manifest.get("format_version") != 1 or not manifest.get("files"):
        raise ValueError("Expected a version-1 bundle manifest with files")
    seen = set()
    for record in manifest["files"]:
        name = record["path"]
        if name in seen or name == "manifest.json":
            raise ValueError(f"Duplicate or recursive manifest entry: {name}")
        seen.add(name)
        path = bundle_path(root, name)
        if (
            not path.is_file()
            or path.stat().st_size != record["bytes"]
            or file_sha256(path) != record["sha256"]
        ):
            raise ValueError(f"Bundle checksum mismatch: {name}")
    return manifest


def validate_scene(scene: dict) -> None:
    frames, queries = scene["frames"], scene["query_count"]
    if (
        scene.get("position_source") not in ("uv_depth", "xyz")
        or frames < 1
        or queries < 1
    ):
        raise ValueError("Expected nonempty metric UV-depth or XYZ tracks")
    expected = scene.get("available_view_counts", list(range(1, 11)))
    if (
        not expected
        or expected != sorted(set(expected))
        or any(type(count) is not int or not 1 <= count <= 10 for count in expected)
    ):
        raise ValueError("Invalid available view counts")
    groups = {}
    for state in scene["states"]:
        mode = state.get("camera", "on")
        if mode not in ("on", "off"):
            raise ValueError("Camera conditioning must be on/off")
        groups.setdefault((state.get("model", "default"), mode), []).append(
            state["views"]
        )
    if not groups or any(counts != expected for counts in groups.values()):
        raise ValueError("Each camera mode must contain its declared 1–10-view counts")
    for label, layer in [("GT", scene["gt"])] + [
        (f"{state.get('camera', 'on')} / {state['views']} views", state)
        for state in scene["states"]
    ]:
        positions = np.asarray(layer["positions"])
        valid = np.asarray(layer["valid"])
        if positions.shape != (queries, frames, 3) or valid.shape != (queries, frames):
            raise ValueError(f"Invalid track dimensions for {label}")
        if not np.isfinite(positions).all():
            raise ValueError(f"Nonfinite positions for {label}")
        if "dense" in layer:
            dense = layer["dense"]
            points = np.asarray(dense["positions"])
            if (
                points.ndim != 3
                or points.shape[1:] != (frames, 3)
                or np.asarray(dense["valid"]).shape != points.shape[:2]
                or np.asarray(dense["colors"]).shape != (len(points), 3)
                or not np.isfinite(points).all()
            ):
                raise ValueError(f"Invalid context dimensions for {label}")
    cameras = len(scene["camera_ids"])
    if np.asarray(scene["intrinsics"]).shape != (cameras, frames, 3, 3) or np.asarray(
        scene["relative_cameras"]
    ).shape != (cameras, frames, 4, 4):
        raise ValueError("Display cameras do not match the frame timeline")


def build_viewer(root: Path, output: Path) -> Path:
    collection = json.loads((root / "scenes.json").read_text())
    if not collection or len({row["id"] for row in collection}) != len(collection):
        raise ValueError("Expected a nonempty collection with unique scene identities")
    assets = {
        "scenes.json": {
            "type": "application/json",
            "data": base64.b64encode(json.dumps(collection).encode()).decode(),
        }
    }
    for row in collection:
        path = bundle_path(root, row["data"])
        payload = path.read_bytes()
        if path.suffix == ".gz":
            payload = gzip.decompress(payload)
        scene = json.loads(payload)
        validate_scene(scene)
        if scene["id"] != row["id"] or scene["dataset"] != row["dataset"]:
            raise ValueError("Scene identity differs from the collection")
        assets[row["data"]] = {
            "type": "application/json",
            "data": base64.b64encode(
                gzip.compress(payload, compresslevel=6, mtime=0)
            ).decode(),
        }
        assets[scene["video"]] = {
            "type": "video/webm",
            "data": base64.b64encode(
                bundle_path(root, scene["video"]).read_bytes()
            ).decode(),
        }
    static = Path(__file__).parent
    inline = json.dumps(assets, separators=(",", ":")).replace("<", "\\u003c")
    html = (
        (static / "template.html")
        .read_text()
        .replace(
            "{{INLINE_ASSETS}}",
            f'<script id="inline-assets" type="application/json">{inline}</script>',
        )
    )
    html = html.replace("{{VIEWER_JS}}", (static / "viewer.js").read_text())
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("x") as handle:
        handle.write(html)
    return output