File size: 4,484 Bytes
aa991fc
 
 
 
 
 
 
 
 
 
 
 
358e603
 
aa991fc
 
 
 
 
01eab39
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
 
 
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
aa991fc
 
 
 
 
01eab39
 
 
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Rebuild `previews/metadata.jsonl` -- the table the HF dataset viewer renders.

One row per (capture x sampled frame). The `file_name` column is resolved by the
`imagefolder` builder into an `image` feature, so Data Studio shows a browsable
thumbnail of every QC contact sheet next to its metadata.

Columns
    file_name      -> image     32-view QC contact sheet [raw | omni-600 | SMPL-X]
    capture                     PxCy
    subject / session           Px / Cy
    role                        train (C1) / test (C2) / cross_reenact_driving (P5,P6 C2)
    frame                       frame id (0-based)
    video_frame                 the same number: d=0, video index == smplx index
    n_cams                      cameras in the capture
    n_frames                    fitted frames in the capture
    n_views_fit                 views actually used by the fit at this frame
    n_face_views                views with an accepted MediaPipe face at this frame
    stages                      fit schedule at this frame (A+B+C+F cold / W warm)
    joint_span_y_m              vertical extent of the SMPL-X joints (sanity number, not height)
    videos / smplx / cameras    repo-relative paths to the full-res assets

Run after every capture is staged; it rescans the whole staging tree.

Usage:
    python build_metadata.py --staging /mnt/sdb/degas_project/DREAMS-AVATAR-hf/staging
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from load_capture import VIDEO_FRAME_OFFSET  # noqa: E402  single source of truth for d


def build(staging: Path) -> dict:
    prev_dir = staging / "previews"
    data_dir = staging / "data"
    captures = sorted(p.name for p in data_dir.iterdir() if p.is_dir()) if data_dir.is_dir() else []
    if not captures:
        raise SystemExit(f"no captures under {data_dir}")

    rows = []
    for cap in captures:
        d = data_dir / cap
        card = json.loads((d / "capture.json").read_text())
        z = np.load(d / "smplx.npz", allow_pickle=False)
        frames = z["frames"].astype(int)
        idx_of = {int(f): i for i, f in enumerate(frames)}
        joints = z["joints"]
        n_views = z["n_views"]
        n_face = z["n_face_views"]
        stages = z["stages"]

        imgs = sorted(prev_dir.glob(f"{cap}_f*.jpg"))
        for img in imgs:
            fr = int(img.stem.split("_f")[1])
            i = idx_of.get(fr)
            if i is None:
                print(f"[metadata] WARN {img.name}: frame {fr} not in smplx.npz", file=sys.stderr)
                continue
            j = joints[i]
            rows.append({
                "file_name": img.name,
                "capture": cap,
                "subject": card["subject"],
                "session": card["session"],
                "role": card.get("role", ""),
                "frame": fr,
                "video_frame": fr + VIDEO_FRAME_OFFSET,
                "n_cams": int(card["n_cams"]),
                "n_frames": int(card.get("n_frames", len(frames))),
                "n_views_fit": int(n_views[i]),
                "n_face_views": int(n_face[i]),
                "stages": str(stages[i]),
                # vertical extent of the SMPL-X joints. A cheap "did the fit explode"
                # number, NOT body height: it grows when the arms go above the head.
                "joint_span_y_m": round(float(j[:, 1].max() - j[:, 1].min()), 4),
                "videos": f"data/{cap}/videos",
                "smplx": f"data/{cap}/smplx.npz",
                "cameras": f"data/{cap}/cameras.json",
            })

    rows.sort(key=lambda r: (r["capture"], r["frame"]))
    prev_dir.mkdir(parents=True, exist_ok=True)
    out = prev_dir / "metadata.jsonl"
    with out.open("w") as fh:
        for r in rows:
            fh.write(json.dumps(r) + "\n")
    print(f"[metadata] {out}: {len(rows)} rows over {len(captures)} captures "
          f"({', '.join(captures)})", flush=True)
    return {"rows": len(rows), "captures": captures, "path": str(out)}


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--staging", type=Path, required=True)
    a = ap.parse_args()
    print(json.dumps(build(a.staging)))
    return 0


if __name__ == "__main__":
    sys.exit(main())