Download examples/visualizer_code/source/demo/scale4d_view_count/bundle.py from facebook/SCALE4D: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/demo/scale4d_view_count/bundle.py
- Command line
-
hf download hf://facebook/SCALE4D/examples/visualizer_code/source/demo/scale4d_view_count/bundle.py
-
curl -L -o bundle.py https://huggingface.co/facebook/SCALE4D/resolve/main/examples/visualizer_code/source/demo/scale4d_view_count/bundle.py
5.85 kB
| """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 | |