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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/venv/main/bin/python3
"""
multiview.py β€” synthesize teleop-style 3-camera views for the retargeted
LeRobot v2.1 dataset (method A': keypoint-guided crops), writing the videos
STRAIGHT INTO the dataset's videos/ tree so it slots in on the go.

LOCKED conventions (per user, 2026-07-24):
  observation.images.top         = full egocentric frame, square center-crop -> 224
  observation.images.left_wrist  = zoom crop tracking the human LEFT-hand grasp point
  observation.images.right_wrist = zoom crop tracking the human RIGHT-hand grasp point
  L/R is ANATOMICAL / as-is: rightThumbTip.. -> right_wrist ; leftThumbTip.. -> left_wrist.
  BOTH wrist views are ALWAYS rendered (both viewpoints must be present) β€” each
  crop tracks its hand's grasp point every frame; only when a hand genuinely
  leaves the image does crop_at zero-pad that region. No forced all-black views.

Output matches abc-teleop EXACTLY: 224x224, h264, yuv420p, 30 fps.

Episode E (v2.1) -> EgoDex source (category, file-YYY), reconstructed with the
same ordering to_lerobot_v21.discover() used (sort by category, file index):
  keypoints/intrinsics/pose <- /workspace/ego/<cat>/data/chunk-*/file-YYY.parquet
  frames                    <- /workspace/ego/<cat>/videos/observation.images.camera/chunk-*/file-YYY.mp4
Frames 0..T-1 (T = episode length) are prefix-aligned t=0 β€” verified 1:1 with the
already-shipped observation.images.camera (parquet_rows == video_frames == T).

Resumable (results.jsonl = source of truth, carries per-episode image stats used
by finalize_multiview.py), logged (--log tees to <ds>/multiview.log), pooled.

Usage:
  /venv/main/bin/python3 multiview.py --ds /workspace/retargeted_lerobot \
      --ego /workspace/ego --retgt /workspace/retargeted \
      --workers 48 --log [--limit N] [--categories a,b]
"""
import os, sys, re, io, glob, json, time, argparse, subprocess, signal
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
from scipy.ndimage import map_coordinates, gaussian_filter1d
from PIL import Image
import multiprocessing as mp

# ── constants ────────────────────────────────────────────────────────────────
FW, FH = 1920, 1080          # source frame size
OUT    = 224                 # output view size
FPS    = 30
CHUNK  = 1000
WRIST_CROP = 620             # px window @1080p tracking the grasp point
KEYS = ["observation.images.top",
        "observation.images.left_wrist",
        "observation.images.right_wrist"]
SIDES = {"R": ("rightThumbTip", "rightIndexFingerTip", "rightMiddleFingerTip"),
         "L": ("leftThumbTip",  "leftIndexFingerTip",  "leftMiddleFingerTip")}
# per-clip activity gate for a wrist view
MOTION_MIN   = 0.06          # m of total grasp-path travel to count as "used"
INBOUNDS_MIN = 0.15          # fraction of frames the hand must be inside the frame
CENTER_SIGMA = 2.0           # gaussian smoothing (frames) of the crop-center track

# per-view fixed lens (virtual camera) β€” geometry is content-independent, so the
# barrel+tilt remap coords are precomputed ONCE below and reused every frame.
VIEW = {  # key: (tilt_deg, barrel_k, color_gain, color_bias)
    "observation.images.top":         ( 3.0, 0.00, 1.05,  3.0),
    "observation.images.left_wrist":  ( 5.0, 0.12, 1.08,  5.0),
    "observation.images.right_wrist": (-5.0, 0.12, 0.96, -3.0),
}

DS = EGO = RETGT = ""        # set in main


# ── precomputed remap coords (barrel∘tilt), one (YS,XS) per view ─────────────
def _remap_coords(tilt_deg, barrel_k, n=OUT):
    """Source-sampling coords for output pixel (y,x) after resize->barrel->tilt.
    Pixel flow in make_view is R --barrel--> B --tilt--> final, so we compose:
      final[y,x] = B[y, sx_t(x)] = R[ barrel(sx_t(x), y) ].  Returns (YS, XS)."""
    c = (n - 1) / 2.0
    yy, xx = np.mgrid[0:n, 0:n].astype(np.float64)
    # tilt: horizontal perspective shear, sx depends only on x
    d = np.tan(np.radians(tilt_deg)) * n * 0.5
    Xt = (xx - n / 2) * (1 + d / n * (xx / n - 0.5) * 2) + n / 2      # intermediate x
    Yt = yy                                                            # tilt keeps y
    # barrel evaluated at (Xt, Yt)
    xn = (Xt - c) / c
    yn = (Yt - c) / c
    f = 1 + barrel_k * (xn * xn + yn * yn)
    XS = xn * f * c + c
    YS = yn * f * c + c
    return YS.astype(np.float32), XS.astype(np.float32)

REMAP = {k: _remap_coords(VIEW[k][0], VIEW[k][1]) for k in KEYS}


# ── image ops ────────────────────────────────────────────────────────────────
def square_center(img):
    h, w = img.shape[:2]; s = min(h, w)
    return img[(h - s) // 2:(h - s) // 2 + s, (w - s) // 2:(w - s) // 2 + s]

def crop_at(img, cx, cy, size):
    """Zero-padded square crop centered at (cx,cy). Out-of-frame -> black pixels."""
    h, w = img.shape[:2]; half = size // 2
    x0 = int(round(cx - half)); y0 = int(round(cy - half))
    out = np.zeros((size, size, 3), np.uint8)
    sx0, sy0 = max(0, x0), max(0, y0)
    sx1, sy1 = min(w, x0 + size), min(h, y0 + size)
    if sx1 > sx0 and sy1 > sy0:
        out[sy0 - y0:sy0 - y0 + (sy1 - sy0), sx0 - x0:sx0 - x0 + (sx1 - sx0)] = img[sy0:sy1, sx0:sx1]
    return out

def resize224(img):
    return np.asarray(Image.fromarray(img).resize((OUT, OUT), Image.LANCZOS))

def apply_lens(img224, key, gain, bias):
    ys, xs = REMAP[key]
    out = np.empty_like(img224)
    for c in range(3):
        out[..., c] = map_coordinates(img224[..., c], (ys, xs), order=3, mode="nearest")
    if gain != 1.0 or bias != 0.0:
        out = np.clip(out.astype(np.float32) * gain + bias, 0, 255).astype(np.uint8)
    return out


# ── geometry ─────────────────────────────────────────────────────────────────
def _mat(col, fr):
    return np.array(col[fr].as_py(), dtype=np.float64).reshape(4, 4)

def grasp_and_project(t, T):
    """Return dict side-> (u[T], v[T], world_g[T,3]) and per-frame K,cam already
    applied. Projection uses EgoDex's per-frame intrinsics + camera pose."""
    Kc  = t.column("camera_intrinsics")
    Cc  = t.column("observation.state.camera")
    cols = {s: [t.column("observation.state." + n) for n in names]
            for s, names in SIDES.items()}
    out = {}
    for s in SIDES:
        th, ix, md = cols[s]
        g = np.empty((T, 3)); u = np.empty(T); v = np.empty(T)
        for fr in range(T):
            pt = 0.5 * (_mat(th, fr)[:3, 3]
                        + 0.7 * _mat(ix, fr)[:3, 3]
                        + 0.3 * _mat(md, fr)[:3, 3])
            g[fr] = pt
            K   = np.array(Kc[fr].as_py()).reshape(3, 3)
            cam = _mat(Cc, fr)
            Xc  = (np.linalg.inv(cam) @ np.append(pt, 1))[:3]
            z   = -Xc[2] if Xc[2] != 0 else 1e-6
            u[fr] = K[0, 0] * Xc[0] / z + K[0, 2]
            v[fr] = -K[1, 1] * Xc[1] / z + K[1, 2]
        out[s] = (u, v, g)
    return out

HALF = WRIST_CROP // 2       # crop-center bounds so the window stays fully in-frame

def hand_track(u, v, g):
    """(active, cu[T], cv[T]). The crop-center track is smoothed AND clamped so the
    WRIST_CROP window always lies fully inside the frame -> the wrist view is ALWAYS
    real scene content, never black. When the hand is in FOV the crop tracks it; when
    the hand leaves FOV the center rides the nearest edge (hand-adjacent workspace).
    `active` is informational only (logging) now that no view is blacked."""
    T = len(u)
    inb = (u >= 0) & (u < FW) & (v >= 0) & (v < FH)
    motion = float(np.linalg.norm(np.diff(g, axis=0), axis=1).sum()) if T > 1 else 0.0
    active = (motion >= MOTION_MIN) and (inb.mean() >= INBOUNDS_MIN)
    cu = np.nan_to_num(u, nan=FW / 2, posinf=FW, neginf=0.0)
    cv = np.nan_to_num(v, nan=FH / 2, posinf=FH, neginf=0.0)
    cu = np.clip(cu, HALF, FW - HALF).astype(np.float64)
    cv = np.clip(cv, HALF, FH - HALF).astype(np.float64)
    if T >= 3:
        cu = gaussian_filter1d(cu, CENTER_SIGMA, mode="nearest")
        cv = gaussian_filter1d(cv, CENTER_SIGMA, mode="nearest")
        cu = np.clip(cu, HALF, FW - HALF)
        cv = np.clip(cv, HALF, FH - HALF)
    return active, cu, cv, inb


# ── running per-view image stats (LeRobot: per-channel, [0,1], shape (3,1,1)) ─
class Stat:
    def __init__(self):
        self.n = 0
        self.s = np.zeros(3); self.ss = np.zeros(3)
        self.mn = np.full(3, np.inf); self.mx = np.full(3, -np.inf)
    def add(self, frame):                    # frame uint8 (H,W,3)
        a = frame.reshape(-1, 3).astype(np.float64) / 255.0
        self.n += a.shape[0]
        self.s += a.sum(0); self.ss += (a * a).sum(0)
        self.mn = np.minimum(self.mn, a.min(0)); self.mx = np.maximum(self.mx, a.max(0))
    def finalize(self, T):
        if self.n == 0:                      # all-black safety
            z = np.zeros((3, 1, 1))
            return {"min": z.tolist(), "max": z.tolist(),
                    "mean": z.tolist(), "std": z.tolist(), "count": [T]}
        mean = self.s / self.n
        var = np.maximum(self.ss / self.n - mean * mean, 0.0)
        r = lambda a: a.reshape(3, 1, 1).tolist()
        return {"min": r(self.mn), "max": r(self.mx),
                "mean": r(mean), "std": r(np.sqrt(var)), "count": [T]}


# ── ffmpeg streaming ─────────────────────────────────────────────────────────
def _readn(f, n):
    buf = bytearray()
    while len(buf) < n:
        chunk = f.read(n - len(buf))
        if not chunk:
            break
        buf += chunk
    return bytes(buf)

def _fferr():
    return open(os.environ.get("FFMPEG_LOG", os.devnull), "a")


def open_decoder(vid, T):
    return subprocess.Popen(
        ["ffmpeg", "-v", "error", "-i", vid, "-frames:v", str(T),
         "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{FW}x{FH}", "-"],
        stdout=subprocess.PIPE, stderr=_fferr(), bufsize=FW * FH * 3 * 2)

def open_encoder(path):
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    return subprocess.Popen(
        ["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
         "-s", f"{OUT}x{OUT}", "-r", str(FPS), "-i", "-",
         "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "23",
         "-g", str(FPS), "-preset", "veryfast", "-threads", "1",
         "-f", "mp4", path],
        stdin=subprocess.PIPE, stderr=_fferr())


# ── per-episode work ─────────────────────────────────────────────────────────
def src_paths(cat, fyy):
    p = glob.glob(f"{EGO}/{cat}/data/chunk-*/{fyy}.parquet")
    v = glob.glob(f"{EGO}/{cat}/videos/observation.images.camera/chunk-*/{fyy}.mp4")
    return (p[0] if p else None), (v[0] if v else None)

def out_paths(eidx):
    ci = eidx // CHUNK
    return {k: f"{DS}/videos/chunk-{ci:03d}/{k}/episode_{eidx:06d}.mp4" for k in KEYS}

def process(e):
    eidx, cat, fyy, T = e["episode_index"], e["category"], e["fyy"], e["length"]
    t0 = time.time()
    pqf, vid = src_paths(cat, fyy)
    if not pqf or not vid:
        return {"episode_index": eidx, "error": f"missing source ({cat}/{fyy})"}
    outs = out_paths(eidx)
    try:
        cols = ["camera_intrinsics", "observation.state.camera"] + \
               [f"observation.state.{n}" for s in SIDES.values() for n in s]
        t = pq.read_table(pqf, columns=cols)
        Tsrc = t.num_rows
        Tn = min(T, Tsrc)
        proj = grasp_and_project(t, Tn)
        tracks = {}
        for s in SIDES:
            u, v, g = proj[s]
            tracks[s] = hand_track(u, v, g)

        stats = {k: Stat() for k in KEYS}
        dec = open_decoder(vid, T)
        enc = {k: open_encoder(outs[k] + ".tmp") for k in KEYS}
        frame_bytes = FW * FH * 3
        last = None
        for fr in range(T):
            raw = _readn(dec.stdout, frame_bytes)
            if len(raw) < frame_bytes:
                img = last if last is not None else np.zeros((FH, FW, 3), np.uint8)
            else:
                img = np.frombuffer(raw, np.uint8).reshape(FH, FW, 3)
                last = img
            fi = min(fr, Tn - 1)             # keypoints index (prefix-aligned)

            # top
            g_top, b_top = VIEW[KEYS[0]][2], VIEW[KEYS[0]][3]
            top = apply_lens(resize224(square_center(img)), KEYS[0], g_top, b_top)

            views = {KEYS[0]: top}
            for key, s in ((KEYS[1], "L"), (KEYS[2], "R")):
                _active, cu, cv, _ = tracks[s]
                # ALWAYS render both wrist views (both viewpoints present) β€”
                # crop tracks the hand's grasp point every frame; if the hand is
                # genuinely off-frame, crop_at zero-pads only that region.
                crop = crop_at(img, cu[fi], cv[fi], WRIST_CROP)
                gn, bs = VIEW[key][2], VIEW[key][3]
                views[key] = apply_lens(resize224(crop), key, gn, bs)

            for k in KEYS:
                stats[k].add(views[k])
                enc[k].stdin.write(views[k].tobytes())

        dec.stdout.close(); dec.wait()
        for k in KEYS:
            enc[k].stdin.close(); enc[k].wait()
            os.replace(outs[k] + ".tmp", outs[k])       # atomic publish

        return {"episode_index": eidx, "category": cat, "length": T,
                "active": {"L": bool(tracks["L"][0]), "R": bool(tracks["R"][0])},
                "stats": {k: stats[k].finalize(T) for k in KEYS},
                "sec": round(time.time() - t0, 2)}
    except Exception as ex:
        for k in KEYS:
            for p in (outs[k] + ".tmp",):
                try: os.remove(p)
                except OSError: pass
        return {"episode_index": eidx, "error": f"{type(ex).__name__}: {ex}"}


# ── mapping (replicate to_lerobot_v21.discover ordering) ─────────────────────
def build_episodes():
    lengths = {}
    with open(f"{DS}/meta/episodes.jsonl") as f:
        for line in f:
            d = json.loads(line); lengths[d["episode_index"]] = d["length"]
    rows = []
    for h in sorted(glob.glob(f"{RETGT}/*/clip_*/retargeted.hdf5")):
        parts = h.split("/")
        cat, name = parts[-3], parts[-2]
        m = re.search(r"(file-\d+)_ep", name)
        if not m:
            continue
        fyy = m.group(1)
        rows.append({"category": cat, "fyy": fyy, "fileidx": int(fyy.split("-")[1])})
    rows.sort(key=lambda r: (r["category"], r["fileidx"]))
    eps = []
    for i, r in enumerate(rows):
        if i not in lengths:            # dataset has fewer episodes than clips
            continue
        eps.append({"episode_index": i, "category": r["category"],
                    "fyy": r["fyy"], "length": lengths[i]})
    return eps


def main():
    print('>>> MULTIVIEW main() entered', flush=True)
    global DS, EGO, RETGT
    ap = argparse.ArgumentParser()
    ap.add_argument("--ds", default="/workspace/retargeted_lerobot")
    ap.add_argument("--ego", default="/workspace/ego")
    ap.add_argument("--retgt", default="/workspace/retargeted")
    ap.add_argument("--workers", type=int, default=48)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--categories", default="")
    ap.add_argument("--log", action="store_true")
    args = ap.parse_args()
    DS, EGO, RETGT = args.ds, args.ego, args.retgt

    logf = None
    if args.log:
        logf = open(f"{DS}/multiview.log", "a", buffering=1)
    def emit(msg):
        print(msg, flush=True)
        if logf: logf.write(msg + "\n")

    eps = build_episodes()
    if args.categories:
        keep = set(args.categories.split(","))
        eps = [e for e in eps if e["category"] in keep]
    if args.limit:
        eps = eps[:args.limit]

    # resume: results.jsonl is the source of truth (carries stats for finalize)
    res_path = f"{DS}/multiview_results.jsonl"
    done = set()
    if os.path.exists(res_path):
        with open(res_path) as f:
            for line in f:
                try:
                    d = json.loads(line)
                    if "stats" in d:
                        done.add(d["episode_index"])
                except Exception:
                    pass
    todo = [e for e in eps if e["episode_index"] not in done]

    emit(f"\n=== multiview run {time.strftime('%Y-%m-%d %H:%M:%S')} ===")
    emit(f"episodes={len(eps)}  resumed={len(done)}  todo={len(todo)}  "
         f"workers={args.workers}  keys={len(KEYS)}  out={OUT}x{OUT} h264")
    if not todo:
        emit("nothing to do β€” all episodes already have results.")
        return

    res_f = open(res_path, "a", buffering=1)
    t_start = time.time()
    n_ok = n_err = 0
    errs = []
    with mp.Pool(args.workers, maxtasksperchild=200) as pool:
        for i, r in enumerate(pool.imap_unordered(process, todo, chunksize=1), 1):
            res_f.write(json.dumps(r) + "\n")
            eidx = r["episode_index"]
            if "error" in r:
                n_err += 1; errs.append((eidx, r["error"]))
                emit(f"  [ERR {r['error'][:40]:40s}] ep{eidx:06d}  {i}/{len(todo)}")
            else:
                n_ok += 1
                el = time.time() - t_start
                eta = el / i * (len(todo) - i) / 3600
                a = r.get("active", {})
                tag = ("LR" if a.get("L") and a.get("R") else
                       "L-" if a.get("L") else "-R" if a.get("R") else "--")
                emit(f"  [ok {tag}] ep{eidx:06d} {r['category'][:14]:14s} "
                     f"{r['sec']:5.1f}s  {i}/{len(todo)}  ETA {eta:4.2f}h")
    res_f.close()
    emit(f"\nDONE: ok={n_ok} err={n_err} in {(time.time()-t_start)/3600:.2f}h")
    for eidx, msg in errs[:15]:
        emit(f"  ERR ep{eidx:06d}: {msg}")
    emit("next: /venv/main/bin/python3 finalize_multiview.py --ds " + DS)


if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    import traceback
    try:
        main()
    except BaseException:
        print(">>> MULTIVIEW CRASHED:", flush=True); traceback.print_exc(); raise