File size: 2,673 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
"""Export saved EMA teacher bundles to the shared comparison viewer."""

from __future__ import annotations

import argparse
import gzip
import json
import shutil
from pathlib import Path

import numpy as np

from demo.scale4d_view_count.bundle import build_viewer, bundle_path
from demo.scale4d_view_count.export import write_atlas
from demo.scale4d_view_count.teacher import teacher_scene_payload


def read_npz(path: Path) -> dict:
    with np.load(path, allow_pickle=False) as values:
        return {key: values[key] for key in values.files}


def export_scene(bundle: Path, record: dict, output: Path) -> dict:
    inputs = read_npz(bundle_path(bundle, record["input"]))
    labels = read_npz(bundle_path(bundle, record["labels"]))
    predictions = {}
    for model, filename in record["prediction_files"].items():
        values = read_npz(bundle_path(bundle, filename))
        values["metadata"] = json.loads(str(values["metadata_json"].item()))
        predictions[model] = values
    scene = teacher_scene_payload(inputs, labels, predictions, record)
    scene.update(record.get("viewer_settings", {}))
    filename = record["id"] + ".json.gz"
    saved_scene = bundle_path(bundle, "viewer/" + filename)
    if saved_scene.exists():
        saved = json.loads(gzip.decompress(saved_scene.read_bytes()))
        scene["video_grid"] = saved["video_grid"]
        shutil.copy2(bundle_path(bundle, "viewer/" + scene["video"]), output / scene["video"])
    else:
        scene["video_grid"] = write_atlas(inputs["rgbs"], output / scene["video"])
    (output / filename).write_bytes(
        gzip.compress(
            json.dumps(scene, separators=(",", ":"), allow_nan=False).encode(),
            mtime=0,
        )
    )
    return {
        "id": record["id"],
        "dataset": record["dataset"],
        "dataset_label": record["dataset_label"],
        "label": record["label"],
        "data": filename,
    }


def export_bundle(bundle: Path, output: Path) -> Path:
    if output.exists():
        raise FileExistsError(output)
    records = json.loads((bundle / "scene_records.json").read_text())
    output.mkdir(parents=True)
    rows = [export_scene(bundle, record, output) for record in records]
    (output / "scenes.json").write_text(json.dumps(rows, indent=2) + "\n")
    return build_viewer(output, output / "index.html")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--bundle", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    print(export_bundle(args.bundle, args.output))


if __name__ == "__main__":
    main()