PWM / PWM_code /reward_model /scripts /gen_pred_flow_opendrawer_live.py
hchen657Naza's picture
Add files using upload-large-folder tool
dd253d4 verified
Raw History Blame Contribute Delete
5.19 kB
#!/usr/bin/env python3
"""LIVE point-flow overlay for Open-Drawer ACT-rollout videos (no precomputed tracks).
Runs the EXACT TrackFlowScorer runtime pipeline on a raw mp4:
SAM3+CoTracker (_extract_tracks, 'wooden item' chain, disp-filter) -> GT green
3-PoinTr (_predict_demolike from frame-0 tracks) -> pred red
progress_gated reward (_track_similarity) -> per-frame score
Draws GT green + pred red on the (2x-upscaled) frames and annotates the per-frame
progress_gated reward + its running max. Proves whether a track_max=0.0 in the
comparison JSON was a real no-progress or a spurious pipeline miss.
Usage: python gen_pred_flow_opendrawer_live.py --vid success_ACTe4000_ep000.mp4 [--vid ...]
"""
import argparse, os, sys
import cv2, imageio
import numpy as np
RL = "/home/hongyi/PWM/policy_rl/rl"
for p in [RL, f"{RL}/old/online"]:
if p not in sys.path:
sys.path.insert(0, p)
from rewards import TrackFlowScorer
M = "/home/hongyi/PWM/reward_model/3pointr_models"
ODH = "/home/hongyi/PWM/external/DiffSynth-Studio/data/robot_new/Open-Drawer_halffail"
UPSCALE = 2
K_PIXEL = 50.0
def trim_video(src, max_frames):
"""Write the first max_frames of src to a temp mp4 (caps CoTracker memory)."""
cap = cv2.VideoCapture(src)
frames = []
while len(frames) < max_frames:
ok, f = cap.read()
if not ok:
break
frames.append(cv2.cvtColor(f, cv2.COLOR_BGR2RGB))
cap.release()
dst = f"/tmp/odlive_{os.path.basename(src)}"
imageio.mimwrite(dst, frames, fps=15, macro_block_size=1)
return dst
def render(tf, fn, out_dir, max_frames):
mp4 = trim_video(f"{ODH}/{fn}", max_frames)
# ---- live pipeline (same calls the scorer makes) ----
tracks, vis = tf._extract_tracks(mp4) # (T,N,2)@384, (T,N)
if tracks.shape[1] < 3:
print(f"[{fn}] only {tracks.shape[1]} pts after disp-filter -> would score 0")
return
pred = tf._predict_demolike(tracks[0], mp4_path=mp4) # (L,N,2)@384
resampled, raw = tf._track_similarity(tracks, vis, pred, mode="progress_gated", k_pixel=K_PIXEL)
T, N = tracks.shape[0], tracks.shape[1]
L = pred.shape[0]
# ---- frames (first T, 2x upscale) ----
cap = cv2.VideoCapture(mp4)
frames = []
while len(frames) < T:
ok, f = cap.read()
if not ok:
break
f = cv2.cvtColor(f, cv2.COLOR_BGR2RGB)
if UPSCALE != 1:
f = cv2.resize(f, (f.shape[1] * UPSCALE, f.shape[0] * UPSCALE), interpolation=cv2.INTER_LINEAR)
frames.append(f)
Td = min(len(frames), T)
H, W = frames[0].shape[:2]
s = float(UPSCALE)
# align pred (L) onto rollout timeline (Td)
tt = np.linspace(0, L - 1, Td, dtype=np.float32)
t0 = np.floor(tt).astype(int).clip(0, L - 1); t1 = np.minimum(t0 + 1, L - 1)
w = (tt - t0)[:, None, None]
pred_al = (1 - w) * pred[t0] + w * pred[t1] # (Td,N,2)@384
gt = tracks * s
pr = pred_al * s
run_max = 0.0
out_frames = []
for ti in range(Td):
cur = frames[ti].copy()
for pi in range(N):
if vis[ti, pi]:
x, y = gt[ti, pi]; cv2.circle(cur, (int(x), int(y)), 2, (0, 255, 0), -1)
for pi in range(N):
x, y = pr[ti, pi]; cv2.circle(cur, (int(x), int(y)), 2, (255, 0, 0), -1)
run_max = max(run_max, float(raw[ti]))
cv2.putText(cur, f"t={ti} reward={raw[ti]:.3f} max={run_max:.3f}", (10, 26),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
cv2.putText(cur, f"GT wooden item ({N}pts)", (10, H - 34), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
cv2.putText(cur, "3PoinTr pred", (10, H - 12), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)
out_frames.append(cur)
os.makedirs(out_dir, exist_ok=True)
out = f"{out_dir}/live_flow_{os.path.splitext(fn)[0]}.mp4"
imageio.mimwrite(out, out_frames, fps=15, macro_block_size=1)
err = np.linalg.norm(tracks[:Td] - pred_al, axis=-1)
print(f"[{fn}] N={N} L={L} Td={Td} track_max(reward)={float(raw.max()):.4f} "
f"px err@384 mean={err.mean():.1f} -> {out}")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--vid", action="append", default=[])
ap.add_argument("--out_dir", default="/home/hongyi/PWM/external/pred_flow_opendrawer_live")
ap.add_argument("--max_frames", type=int, default=160)
ap.add_argument("--point_stride", type=int, default=10)
a = ap.parse_args()
vids = a.vid or ["success_ACTe4000_ep000.mp4", "success_ACTe6000_ep000.mp4"]
tf = TrackFlowScorer(
pointr_ckpt=f"{M}/open_drawer_2d_wb_150pts_flow_backbone.pth",
prompt="wooden item",
prompt_fallbacks=["wooden block", "the wooden block", "wooden box", "wooden drawer"],
point_stride=a.point_stride,
subprocess_gpu=os.environ.get("TF_GPU", "1"), verbose=True)
for fn in vids:
try:
render(tf, fn, a.out_dir, a.max_frames)
except Exception as e:
import traceback; traceback.print_exc()
print(f"[{fn}] FAILED: {e}")
if __name__ == "__main__":
main()