File size: 6,901 Bytes
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
 
 
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
 
 
 
 
aa991fc
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
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
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
#!/usr/bin/env python
"""Assemble one capture into the HuggingFace staging tree.

    staging/data/<PxCy>/videos/cam00.mp4 .. cam31.mp4   hardlink to frameset-videos/NN.mp4
    staging/data/<PxCy>/cameras.json                    copy of the capture calibration
    staging/data/<PxCy>/smplx.npz                       written by consolidate_smplx.py
    staging/data/<PxCy>/preview.jpg                     written by make_previews.py
    staging/data/<PxCy>/capture.json                    machine-readable capture card

Videos are HARDLINKED (same filesystem, /mnt/sdb) so staging costs ~0 bytes and the
source capture dir is never modified. Falls back to symlink, then copy.

The source `frameset-videos/` must already be extracted (`7z x frameset-videos.7z`);
--extract will do it if the directory is missing.

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

import argparse
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path

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

DATASET_ROOT = Path("/mnt/sdb/degas_project/DEGAS_DATASET")

# The published set is 10 captures. C1 = train, C2 = test.
# P1..P4 ship both sessions; P5/P6 are CROSS-REENACT DRIVING ONLY, so only their C2 is
# published. P5C1 does not exist on disk at all; P6C1 exists but is deliberately excluded.
INCLUDED = ["P1C1", "P1C2", "P2C1", "P2C2", "P3C1", "P3C2",
            "P4C1", "P4C2", "P5C2", "P6C2"]
EXCLUDED = {
    "P5C1": "does not exist",
    "P6C1": "excluded on purpose: P5/P6 contribute cross-reenact driving (C2) only",
}


def link_or_copy(src: Path, dst: Path) -> str:
    if dst.exists() or dst.is_symlink():
        dst.unlink()
    dst.parent.mkdir(parents=True, exist_ok=True)
    try:
        os.link(src, dst)
        return "hardlink"
    except OSError:
        try:
            dst.symlink_to(src)
            return "symlink"
        except OSError:
            shutil.copy2(src, dst)
            return "copy"


def probe_video(path: Path) -> dict:
    out = subprocess.run(
        ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
         "stream=width,height,nb_frames,r_frame_rate,codec_name,pix_fmt",
         "-of", "json", str(path)],
        capture_output=True, text=True, check=True).stdout
    s = json.loads(out)["streams"][0]
    num, den = s["r_frame_rate"].split("/")
    return {"width": int(s["width"]), "height": int(s["height"]),
            "n_frames": int(s["nb_frames"]), "fps": round(int(num) / int(den), 4),
            "codec": s["codec_name"], "pix_fmt": s["pix_fmt"]}


def stage(capture: str, dataset_root: Path, staging: Path, extract: bool = False,
          force: bool = False) -> dict:
    if capture in EXCLUDED and not force:
        raise SystemExit(
            f"{capture} is NOT part of DREAMS-AVATAR: {EXCLUDED[capture]}.\n"
            f"published captures: {', '.join(INCLUDED)}   (--force to override)")
    if capture not in INCLUDED and not force:
        raise SystemExit(f"{capture} is not in the published set "
                         f"({', '.join(INCLUDED)}); use --force to add it anyway")
    src = dataset_root / capture
    if not src.is_dir():
        raise SystemExit(f"no such capture: {src}")

    vdir = src / "frameset-videos"
    if not vdir.is_dir() or not list(vdir.glob("*.mp4")):
        if not extract:
            raise SystemExit(f"{vdir} empty; re-run with --extract (runs 7z x)")
        arc = src / "frameset-videos.7z"
        print(f"[stage] extracting {arc} ...", flush=True)
        subprocess.run(["7z", "x", "-y", f"-o{src}", str(arc)], check=True,
                       stdout=subprocess.DEVNULL)

    mp4s = sorted(vdir.glob("*.mp4"))
    dst = staging / "data" / capture
    mode = None
    total = 0
    for m in mp4s:
        cam = int(m.stem)
        mode = link_or_copy(m, dst / "videos" / f"cam{cam:02d}.mp4")
        total += m.stat().st_size
    print(f"[stage] {capture}: {len(mp4s)} videos via {mode} "
          f"({total / 2**30:.2f} GiB)", flush=True)

    cams_src = src / "cameras.json"
    shutil.copy2(cams_src, dst / "cameras.json")
    cams = json.loads(cams_src.read_text())
    n_rigs = len(cams["rigs"])

    v0 = probe_video(mp4s[0])
    assert v0["width"] % 2 == 0
    card = {
        "capture": capture,
        "subject": capture[:2],
        "session": capture[2:],
        "role": ("train" if capture.endswith("C1") else
                 ("cross_reenact_driving" if capture[:2] in ("P5", "P6") else "test")),
        "n_cams": len(mp4s),
        "n_rigs_in_calibration": n_rigs,
        "video": {**v0,
                  "layout": "side-by-side: LEFT half = RGB, RIGHT half = alpha matte",
                  "rgb_width": v0["width"] // 2},
        "video_bytes": total,
        "frame_convention": {
            "offset_d": VIDEO_FRAME_OFFSET,
            "rule": "video frame index == smplx frame index == GT frame index (d=0)",
            "smplx_frame": "0-based frame id, stored in smplx.npz['frames']",
            "video_frame": "the same number, 0-based index into camNN.mp4",
            "measured": "d is measured per capture by verify_alignment.py, not assumed",
        },
        "camera_convention": {
            "K": "[[fx,0,cx],[0,fy,cy],[0,0,1]] from rigs[i].cameras[0]",
            "R_w2c": "R @ diag(1,-1,-1)",
            "t_w2c": "-R @ c",
            "note": "cameras.json world is Y-down; the world_flip puts the fit in the "
                    "same Y-up world as the DEGAS GT",
        },
    }
    smplx_npz = dst / "smplx.npz"
    if smplx_npz.exists():
        import numpy as np
        z = np.load(smplx_npz, allow_pickle=False)
        card["n_frames"] = int(len(z["frames"]))
        card["frame_range"] = [int(z["frames"][0]), int(z["frames"][-1])]
        card["smplx_kwargs"] = json.loads(str(z["smplx_kwargs"]))
    (dst / "capture.json").write_text(json.dumps(card, indent=2) + "\n")
    print(f"[stage] wrote {dst / 'capture.json'}", flush=True)
    return card


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("capture")
    ap.add_argument("--dataset-root", type=Path, default=DATASET_ROOT)
    ap.add_argument("--staging", type=Path, required=True)
    ap.add_argument("--extract", action="store_true", help="7z x frameset-videos.7z if missing")
    ap.add_argument("--force", action="store_true",
                    help="stage a capture outside the published 10 (P5C1/P6C1 are excluded)")
    a = ap.parse_args()
    print(json.dumps(stage(a.capture, a.dataset_root, a.staging, a.extract, a.force)))
    return 0


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