File size: 9,466 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 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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | """Package the standalone SCALE4D example source for Hugging Face."""
from __future__ import annotations
import argparse
import ast
import gzip
import hashlib
import io
import json
import shutil
import tarfile
from pathlib import Path
SOURCE_FILES = (
"demo/__init__.py",
"d4rt_scripts/__init__.py",
"d4rt_scripts/demo/__init__.py",
"d4rt_scripts/demo/scale4d_inference.py",
"d4rt_scripts/demo/scale4d_view_count.py",
"d4rt_scripts/demo/scale4d_camera_ablation.py",
"d4rt_scripts/export_scale4d_examples.py",
"d4rt_scripts/export_scale4d.py",
"d4rt_scripts/upload_scale4d_view_count.py",
"evaluation/__init__.py",
"evaluation/scale4d.py",
"evaluation/scale4d_inputs.py",
"evaluation/scale4d_view_count.py",
"evaluation/ucpe_checkpoint.py",
"evaluation/ucpe_inference.py",
"evaluation/ucpe_inputs.py",
"evaluation/ucpe_scores.py",
"nets/__init__.py",
"nets/attention.py",
"nets/scale4d.py",
"docs/scale4d.md",
"docs/scale4d_view_count.md",
"docs/scale4d_camera_ablation.md",
"tests/test_scale4d_inference.py",
"tests/test_ucpe_eval.py",
"tests/test_scale4d_camera_ablation.py",
"tests/test_scale4d_view_count.py",
"tests/test_scale4d_viewer_bundle.py",
"tests/scale4d_sandbox_harness.py",
)
MODEL_REVISION = "069f22ba021e3c23c7e4831ff4385927978eac63"
ARCHIVE = "infd4rt_scale4d_examples.tar.gz"
PACKAGE_CONFIG = """[build-system]
requires = ["setuptools>=69", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "infd4rt-scale4d-examples"
version = "0.1.0"
description = "Standalone SCALE4D inference and interactive example viewers"
readme = "README.md"
requires-python = ">=3.10"
dependencies = ["numpy", "Pillow", "huggingface-hub"]
[project.optional-dependencies]
model = ["torch>=2.6", "opencv-python", "timm>=1.0", "safetensors"]
flash = ["flash-attn"]
dev = ["pytest", "ruff"]
[project.scripts]
scale4d-viewer = "demo.scale4d_view_count.__main__:main"
scale4d-infer = "d4rt_scripts.demo.scale4d_inference:main"
scale4d-view-count = "d4rt_scripts.demo.scale4d_view_count:main"
scale4d-camera-ablation = "d4rt_scripts.demo.scale4d_camera_ablation:main"
[tool.setuptools.packages.find]
where = ["."]
include = ["demo*", "d4rt_scripts*", "evaluation*", "nets*"]
[tool.setuptools.package-data]
"demo.scale4d_view_count" = ["*.html", "*.js"]
"nets.ucpe_cd50" = ["model_config*.json"]
"nets.ucpe_cd50_stable" = ["model_config*.json"]
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
[tool.ruff]
line-length = 88
target-version = "py310"
"""
def file_record(root: Path, path: Path) -> dict:
payload = path.read_bytes()
return {
"path": path.relative_to(root).as_posix(),
"bytes": len(payload),
"sha256": hashlib.sha256(payload).hexdigest(),
}
def source_readme(data_revision: str) -> str:
return f"""# Standalone SCALE4D example source
This source bundle contains the shared HTML/WebGL viewer, its sandbox-compatible
embedded-data loader, 1–10-view inference, camera-conditioning ON/OFF inference,
metric scoring, the 140k model implementation/config, and regression tests.
It is exported from the corresponding files in `infd4rt`.
The example data is pinned to `facebook/SCALE4D` revision `{data_revision}`:
* `examples/view_count/`: frozen 1–10-view PStudio/Show3D results.
* `examples/camera_conditioning/`: ten matched three-view ON/OFF candidates;
original calibrated inputs for the two featured examples are included.
The model API uses the frozen 140k weight release at revision `{MODEL_REVISION}`.
The weights are downloaded from the model repository when running inference.
Hugging Face authentication is required while the repository is private.
## Install and view
Unpack `infd4rt_scale4d_examples.tar.gz`, then use a separate environment:
```bash
cd scale4d_examples
python -m venv .venv
.venv/bin/python -m pip install -e .
.venv/bin/python -m demo.scale4d_view_count download \\
--prefix examples/camera_conditioning --revision {data_revision} \\
--output downloads --viewer-only
.venv/bin/python -m demo.scale4d_view_count serve \\
--directory downloads/examples/camera_conditioning/viewer --port 8000
```
Open `http://127.0.0.1:8000/`, or open the downloaded `index.html` directly.
The HTML embeds all scene data and RGB videos and reads them without `fetch()`.
The renderer was tested in an opaque-origin sandbox with network access blocked.
## Download inputs and run inference
Install a PyTorch build appropriate for your GPU, then install the model extras:
```bash
.venv/bin/python -m pip install -e '.[model,dev]'
.venv/bin/python -m demo.scale4d_view_count download \\
--prefix examples/camera_conditioning --revision {data_revision} \\
--output downloads
.venv/bin/python -m d4rt_scripts.demo.scale4d_camera_ablation \\
--input downloads/examples/camera_conditioning/inputs/pstudio.npz \\
--labels downloads/examples/camera_conditioning/labels/pstudio.npz \\
--views 3 --output /tmp/scale4d_camera_pair --device cuda:0
```
For the view-count experiment, download `examples/view_count` with the same
command and run `d4rt_scripts.demo.scale4d_view_count` on its calibrated input.
The extra views reuse decoder embedding rows; encoder weights remain shared.
## Rebuild and test
```bash
.venv/bin/python -m demo.scale4d_view_count build \\
--assets downloads/examples/camera_conditioning/viewer \\
--output /tmp/scale4d_camera_viewer.html
.venv/bin/python -m pytest -q
```
Read `docs/scale4d_camera_ablation.md` and `docs/scale4d_view_count.md` for scoring,
camera-order, coordinate, and context-point conventions. `source_manifest.json`
records every source file's byte size and SHA-256. Copyright headers are retained.
"""
def export_source(repo: Path, output: Path, data_revision: str) -> dict:
if output.exists():
raise FileExistsError(output)
source = output / "source"
source.mkdir(parents=True)
names = set(SOURCE_FILES)
for directory in (
"demo/scale4d_view_count",
"nets/ucpe_cd50",
"nets/ucpe_cd50_stable",
):
for path in (repo / directory).glob("*.py"):
names.add(path.relative_to(repo).as_posix())
if directory.startswith("nets/"):
for path in (repo / directory).glob("model_config*.json"):
names.add(path.relative_to(repo).as_posix())
else:
names.update(
f"{directory}/{name}" for name in ("template.html", "viewer.js")
)
for name in sorted(names):
destination = source / name
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(repo / name, destination)
if destination.suffix == ".py":
ast.parse(destination.read_text(), filename=name)
readme = source_readme(data_revision)
(source / "pyproject.toml").write_text(PACKAGE_CONFIG)
(source / "README.md").write_text(readme)
records = [
file_record(source, path)
for path in sorted(source.rglob("*"))
if path.is_file()
]
for path in source.rglob("*.py"):
for node in ast.walk(ast.parse(path.read_text())):
if isinstance(node, ast.ImportFrom) and node.module:
module = node.module
if module.split(".")[0] in (
"demo",
"d4rt_scripts",
"evaluation",
"nets",
):
target = source.joinpath(*module.split("."))
if (
not target.with_suffix(".py").is_file()
and not (target / "__init__.py").is_file()
):
raise ValueError(f"Missing source dependency: {module}")
manifest = {
"format_version": 1,
"title": "SCALE4D standalone example source",
"data_revision": data_revision,
"model_revision": MODEL_REVISION,
"source_files": records,
}
(source / "source_manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
with (
(output / ARCHIVE).open("wb") as handle,
gzip.GzipFile(fileobj=handle, mode="wb", mtime=0) as compressed,
tarfile.open(fileobj=compressed, mode="w") as archive,
):
for path in sorted(source.rglob("*")):
if not path.is_file():
continue
payload = path.read_bytes()
entry = tarfile.TarInfo(
"scale4d_examples/" + path.relative_to(source).as_posix()
)
entry.size = len(payload)
entry.mode = 0o644
archive.addfile(entry, io.BytesIO(payload))
(output / "README.md").write_text(readme)
manifest["archive"] = file_record(output, output / ARCHIVE)
(output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
return manifest
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--data-revision", required=True)
args = parser.parse_args()
result = export_source(
Path(__file__).resolve().parents[1], args.output, args.data_revision
)
print(
json.dumps(
{"source_files": len(result["source_files"]), "archive": result["archive"]}
)
)
if __name__ == "__main__":
main()
|