File size: 3,866 Bytes
e3f3efe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""make_ego_vis.py — render ego-view visualizations with the PROJECT visualizer.

Assembles a merged episode dir (view1 + view2 + ego) that `visualize_episode.py`
can consume directly, then invokes it. The tracks stay in their shipped view1
frame — the visualizer reconstructs world points once per frame and projects the
SAME points into all three views, so the output shows exo/ego consistency.
"""
from __future__ import annotations
import json, os, subprocess, sys
from pathlib import Path
import numpy as np

SHIPPED = Path("/data/jh_dataset/droid")
EGO = Path("/data/droid_ego_view")
RAWS = [Path("/data/droid_raw_subset"), Path("/data/droid_raw_laundry"),
        Path("/data/droid_raw_laundry_scene9")]
STAGE = Path("/data/droid_ego_view_vis")
OUTD = STAGE / "_renders"
VIS = Path("/home/nvidia/jonghoon/gripper_augmentator/gripper_point_tracks/.debug/bw_jh_dataset/visualize_episode.py")



def h264(path):
    """Re-encode an OpenCV-written mp4v file in place to broadly-playable H.264."""
    import subprocess, os
    p = str(path); tmp = p[:-4] + ".h264.tmp.mp4"
    r = subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", p,
                        "-c:v", "libx264", "-preset", "veryfast", "-crf", "18",
                        "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-an", tmp],
                       capture_output=True, text=True)
    if r.returncode == 0 and os.path.exists(tmp):
        os.replace(tmp, p)
    else:
        if os.path.exists(tmp): os.remove(tmp)
        print(f"  WARN: ffmpeg re-encode failed for {p}: {r.stderr[-200:]}")


def wrist_mp4(ep, serial):
    for b in RAWS:
        p = b / ep / "recordings" / "MP4" / f"{serial}.mp4"
        if p.exists():
            return p
    return None


def stage(ep):
    md = json.loads((EGO / ep / "meta_ego.json").read_text())
    I = md["views"]["ego"]["intrinsics"]
    if I is None:
        return None, "no_intrinsics"
    serial = md["views"]["ego"]["serial"]
    mp4 = wrist_mp4(ep, serial)
    if mp4 is None:
        return None, "no_wrist_video"
    d = STAGE / ep
    d.mkdir(parents=True, exist_ok=True)
    for f in ("robot.npz", "gripper.npz", "view1.mp4", "view2.mp4"):
        lk = d / f
        if not lk.exists():
            lk.symlink_to(SHIPPED / ep / f)
    lk = d / "ego.mp4"
    if not lk.exists():
        lk.symlink_to(mp4)

    meta = json.loads((SHIPPED / ep / "meta.json").read_text())
    T = np.load(EGO / ep / "ego_extrinsics.npz")["T_cam_world_perframe"]
    meta["views"]["ego"] = {
        "serial": serial,
        "intrinsics": {"fx": I["fx"], "fy": I["fy"], "cx": I["cx"], "cy": I["cy"],
                       "width": I["width"], "height": I["height"],
                       "source": I["source"]},
        "T_cam_world_perframe": T.astype(np.float64).tolist(),
        "extrinsics_refined": False,
        "n_video_frames": int(T.shape[0]),
    }
    (d / "meta.json").write_text(json.dumps(meta))
    return d, "ok"


def main():
    eps = sys.argv[1:]
    OUTD.mkdir(parents=True, exist_ok=True)
    for ep in eps:
        d, st = stage(ep)
        if d is None:
            print(f"skip {ep}: {st}")
            continue
        out = OUTD / f"ego_{ep}.mp4"
        r = subprocess.run([sys.executable, str(VIS), "--split", "droid",
                            "--root", str(STAGE), "--episode", ep,
                            "--out", str(out), "--height", "420",
                            "--dump-frame", "-1"],
                           capture_output=True, text=True)
        if r.returncode == 0 and out.exists():
            h264(out)
        tail = (r.stdout or "").strip().splitlines()[-3:]
        print(f"{ep}: rc={r.returncode} " + " | ".join(tail))
        if r.returncode != 0:
            print("   STDERR:", (r.stderr or "")[-300:])


if __name__ == "__main__":
    main()