File size: 11,541 Bytes
358e603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad187e
 
 
 
 
 
 
358e603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad187e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358e603
9ad187e
358e603
 
 
 
 
9ad187e
 
 
 
 
 
358e603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad187e
 
 
358e603
9ad187e
 
 
 
 
358e603
 
 
 
 
 
 
 
 
9ad187e
 
 
358e603
9ad187e
358e603
9ad187e
 
 
 
 
 
 
 
 
 
 
358e603
 
 
 
 
 
 
 
 
9ad187e
 
 
358e603
 
 
 
 
9ad187e
 
358e603
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Measure the video<->SMPL-X frame offset EMPIRICALLY. Never assume it.

Why this exists
    The DEGAS captures were first tracked assuming `GT frame = video frame + 1`. That
    offset had been measured on a near-static frame, where every candidate looks alike,
    and it was wrong. A one-frame error is nearly invisible in a still overlay but
    poisons every downstream avatar. So the offset is now MEASURED, on motion, before a
    capture is published.

Method (needs no SMPL-X model, only what the dataset ships)
    The discriminating signal is the FAST-MOVING HAND against the ALPHA MATTE.
    A forearm is only ~40-80 px wide, and during a gesture the wrist moves tens of px
    per frame, so a projected wrist lands inside the silhouette at the correct offset and
    outside it one frame away. Slow signals (body centroid) cannot resolve +-1 frame and
    will happily report nonsense with a margin of ~0.01; that weak-signal trap is exactly
    what produced the original wrong +1, so this script refuses to answer when the margin
    is small.

    1. Rank fit frames by projected 2D WRIST SPEED; keep the fastest ones.
    2. Decode a contiguous low-res window of the ALPHA half (right 2048) of each camera.
    3. For each candidate offset d, measure the fraction of hand/wrist joints that land
       on foreground at video frame (fit_frame + d).
    4. Report argmax, plus the margin. A margin below --min-margin is INCONCLUSIVE and
       exits non-zero rather than guessing.

Usage
    # ARGUMENT IS A CAPTURE DIRECTORY (the one holding cameras.json), not a bare name.
    python verify_alignment.py /path/to/staging/data/P2C1 --expect 0
    python verify_alignment.py P2C1 --expect 0     # bare name -> resolved under --staging

    The probe window is chosen AUTOMATICALLY (highest hand motion, cheap: it uses the
    shipped joints, no decoding) unless --start is given. Passing a hand-picked --start
    is how you land on a static stretch and get an unresolvable answer.
"""
from __future__ import annotations

import argparse
import subprocess
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from load_capture import Capture  # noqa: E402


# SMPL-X joint indices that move fastest and sit on THIN geometry, which is what makes
# a one-frame error visible: wrists + both hands' finger joints.
HAND_JOINTS = np.r_[20, 21, np.arange(25, 55)]

DEFAULT_STAGING = Path("/mnt/sdb/degas_project/DREAMS-AVATAR-hf/staging/data")


def resolve_capture_dir(arg: str, staging: Path) -> Path:
    """Accept a real directory OR a bare capture name like 'P2C1'.

    The bare-name form exists because passing 'P3C1' where a path was wanted is an easy
    mistake that fails late and confusingly ('FileNotFoundError: P3C1/cameras.json'),
    which reads like a misalignment rather than a bad argument.
    """
    p = Path(arg)
    if (p / "cameras.json").is_file():
        return p
    cand = staging / arg
    if (cand / "cameras.json").is_file():
        return cand
    raise SystemExit(
        f"no cameras.json found.\n"
        f"  tried: {p / 'cameras.json'}\n"
        f"  tried: {cand / 'cameras.json'}\n"
        f"Pass the capture DIRECTORY (the one containing cameras.json / smplx.npz / "
        f"videos/), or a bare capture name resolvable under --staging.")


def pick_window(cap: Capture, cam: str, frames: list[int], count: int,
                lo: int, hi: int, search_limit: int) -> list[int]:
    """Choose the highest-hand-motion window that is fully decodable.

    Uses only the shipped joints, so it costs no video decoding. Constraints:
      * every probed frame f must satisfy 0 <= f+lo and f+hi <= last frame, so the
        candidate offsets all have a real video frame to look at (captures start at
        frame 0, so a naive window would ask for negative video indices);
      * the window starts within `search_limit` frames of the beginning, to bound how
        much video has to be decoded to reach it.
    """
    first, last = frames[0], frames[-1]
    usable = [f for f in frames if f + lo >= 0 and f + hi <= last]
    if not usable:
        raise SystemExit(f"capture too short for lags {lo}..{hi}")
    count = min(count, len(usable))
    spd = hand_speed(cap, cam, usable)
    k = np.cumsum(np.r_[0.0, spd])
    n_start = len(usable) - count + 1
    limit = max(1, min(n_start, search_limit - (usable[0] - first) + 1))
    tot = k[count:count + limit] - k[:limit]
    i = int(np.argmax(tot))
    return usable[i:i + count]


def decode_alpha_window(video: Path, v_start: int, count: int, src_w: int, src_h: int,
                        scale: float = 0.25) -> tuple[np.ndarray, float]:
    """(n, h, w) uint8 stack of the ALPHA half, downscaled by `scale`.

    `n` is whatever ffmpeg actually produced, which can be fewer than `count` when the
    window runs past the end of the video. The frame size is derived from the source
    dimensions rather than inferred from the byte count, so a short read is detected as a
    short read instead of silently reshaping into the wrong geometry.
    """
    w = int(round(src_w / 2 * scale))
    h = int(round(src_h * scale))
    vf = (f"select='between(n\\,{v_start}\\,{v_start + count - 1})',"
          f"crop=iw/2:ih:iw/2:0,scale={w}:{h},format=gray")
    proc = subprocess.run(
        ["ffmpeg", "-v", "error", "-threads", "1", "-i", str(video),
         "-vf", vf, "-vsync", "0", "-f", "rawvideo", "-pix_fmt", "gray", "-"],
        capture_output=True, check=True)
    buf = np.frombuffer(proc.stdout, np.uint8)
    if len(buf) % (w * h):
        raise RuntimeError(f"{video.name}: raw size {len(buf)} not a multiple of {w}x{h}")
    n = len(buf) // (w * h)
    if n == 0:
        raise RuntimeError(f"{video.name}: decoded 0 frames from {v_start}")
    return buf.reshape(n, h, w), scale


def hand_speed(cap: Capture, cam: str, frames: list[int]) -> np.ndarray:
    """Mean projected 2D speed of the hand joints, px/frame, per fit frame."""
    c = cap.cameras[cam]
    uv = np.stack([c.project(cap.joints(f)[HAND_JOINTS]) for f in frames])
    d = np.linalg.norm(np.diff(uv, axis=0), axis=2).mean(1)
    return np.r_[d[0], d]


def hit_rate(cap: Capture, cam: str, probe: list[int], stack: np.ndarray, scale: float,
             v_first: int, offsets: range) -> dict[int, float]:
    """For each offset d: fraction of hand joints landing on foreground alpha."""
    c = cap.cameras[cam]
    n, h, w = stack.shape
    out = {}
    for d in offsets:
        hits, tot = 0, 0
        for f in probe:
            idx = (f + d) - v_first
            if not (0 <= idx < n):
                continue
            m = stack[idx] > 12
            uv = c.project(cap.joints(f)[HAND_JOINTS]) * scale
            u = np.round(uv[:, 0]).astype(int)
            v = np.round(uv[:, 1]).astype(int)
            ok = (u >= 0) & (u < w) & (v >= 0) & (v < h)
            if not ok.any():
                continue
            hits += int(m[v[ok], u[ok]].sum())
            tot += int(ok.sum())
        out[d] = hits / tot if tot else float("nan")
    return out


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("capture_dir", help="capture DIR (holding cameras.json), or a bare name")
    ap.add_argument("--staging", type=Path, default=DEFAULT_STAGING,
                    help="where a bare capture name is resolved")
    ap.add_argument("--cams", type=int, nargs="*", default=[6, 12])
    ap.add_argument("--start", type=int, default=None,
                    help="force the window start; default = auto-pick highest motion")
    ap.add_argument("--search-limit", type=int, default=600,
                    help="auto-pick searches windows starting within this many frames")
    ap.add_argument("--count", type=int, default=250)
    ap.add_argument("--lags", type=int, nargs=2, default=[-3, 3])
    ap.add_argument("--n-probe", type=int, default=40,
                    help="how many of the fastest-hand frames to score")
    ap.add_argument("--min-margin", type=float, default=0.05,
                    help="required hit-rate gap to the runner-up; below this = INCONCLUSIVE")
    ap.add_argument("--expect", type=int, default=None,
                    help="fail (exit 1) if the measured offset differs from this")
    a = ap.parse_args()

    cdir = resolve_capture_dir(a.capture_dir, a.staging)
    cap = Capture(cdir)
    print(f"{cap}\n  dir: {cdir}")
    lo, hi = a.lags
    all_frames = [int(f) for f in cap.frames]
    cam0 = f"cam{a.cams[0]:02d}"

    if a.start is not None:
        frames = [f for f in all_frames if f >= a.start and f + lo >= 0
                  and f + hi <= all_frames[-1]][:a.count]
        if not frames:
            raise SystemExit(f"--start {a.start} leaves no decodable frames")
    else:
        frames = pick_window(cap, cam0, all_frames, a.count, lo, hi, a.search_limit)
    print(f"window: fit frames {frames[0]}..{frames[-1]} ({len(frames)})"
          f"{'' if a.start is not None else '  [auto-picked: highest hand motion]'}")

    spd = hand_speed(cap, cam0, frames)
    order = np.argsort(-spd)[:a.n_probe]
    probe = sorted(frames[i] for i in order)
    print(f"hand speed in window: median {np.median(spd):.1f} px/frame, "
          f"probe frames use {spd[order].min():.1f}..{spd[order].max():.1f} px/frame")
    if spd[order].min() < 3.0:
        print("WARNING: probe frames are slow; +-1 frame may be unresolvable here")

    v_first = frames[0] + lo
    assert v_first >= 0, f"window start {frames[0]} with lag {lo} needs video frame {v_first}"
    n_dec = min(len(frames) + (hi - lo) + 1, all_frames[-1] - v_first + 1)
    src_w, src_h = cap.card["video"]["width"], cap.card["video"]["height"]
    print(f"decoding alpha window: video frames {v_first}..{v_first + n_dec - 1}")

    per_cam = {}
    for ci in a.cams:
        cam = f"cam{ci:02d}"
        stack, scale = decode_alpha_window(cap.video_dir / f"{cam}.mp4", v_first, n_dec,
                                           src_w, src_h)
        r = hit_rate(cap, cam, probe, stack, scale, v_first, range(lo, hi + 1))
        per_cam[cam] = r
        best = max(r, key=r.get)
        print(f"  {cam} ({stack.shape[2]}x{stack.shape[1]}): "
              + "  ".join(f"d={k:+d}:{v:.3f}" for k, v in sorted(r.items()))
              + f"   -> best d={best:+d}")

    total = {}
    for r in per_cam.values():
        for k, v in r.items():
            total[k] = total.get(k, 0.0) + v / len(per_cam)
    ranked = sorted(total.items(), key=lambda kv: -kv[1])
    best, margin = ranked[0][0], ranked[0][1] - ranked[1][1]
    print("\nhand-on-silhouette hit rate by offset: "
          + "  ".join(f"d={k:+d}:{v:.3f}" for k, v in sorted(total.items())))
    print(f"MEASURED: video_frame = fit_frame + ({best:+d})  "
          f"(margin over d={ranked[1][0]:+d}: {margin:.3f})")

    if margin < a.min_margin:
        print(f"INCONCLUSIVE: margin {margin:.3f} < --min-margin {a.min_margin}. "
              f"This window cannot resolve the offset; do NOT act on it. "
              f"Retry on a higher-motion window or more cameras.")
        return 2
    if a.expect is not None:
        if best != a.expect:
            print(f"FAIL: expected {a.expect:+d}, measured {best:+d}")
            return 1
        print(f"PASS: matches expected {a.expect:+d}")
    return 0


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