"""Control adherence: does the generated video put the robot where the control (rendered robot normal / mask) says it is? For every manifest unit and method with ///pred.mp4: sample F prediction frames (evenly spaced, frame 0 excluded), map each to its GT frame by prediction time (same rule as metrics.py), take the GT RENDER MASK of that frame (cropped by pred_meta["gt_crop"] when present), resize prediction + mask to the work resolution (width 640) and run the SAM3 robot segmenter on the PREDICTED frame with the same prompt/selection recipe the dataset QC uses for real frames (text instances gated to the render + point/box prompts derived from the render; trex/scripts/trex_gt_masks.py, droid/scripts/diag/gt_masks.py). per frame : iou_ctrl = IoU(SAM3(pred frame), render mask); status ok/single/low_conf (usable) | failed | marginal | error per unit : iou_mean over usable frames, miss = fraction of sampled frames with status failed/error or iou_ctrl < 0.3 (robot absent, duplicated or misplaced), n_usable per method: mean iou / miss with bootstrap-by-unit 95% CIs; `--with-gt` scores the real video at the same GT frames ("gt" pseudo-method) = ceiling given render-vs-real alignment. --normals : control-normal adherence with MoGe-2 (Ruicheng/moge-2-vitl-normal, same env): per sampled frame the predicted image -> MoGe normals (OpenCV camera frame) vs the rendered control normal (decoded n = rgb/127.5-1; OpenGL maps have y,z negated) inside the eroded control mask: mean / median angular error (deg) and the fraction < 30 deg. GT frames (--with-gt) give the ceiling (render-vs-real + MoGe error). Output: //.json (cached, skip-existing), /summary.csv, /summary.md. Interpreter: /home/wujiayir/miniconda3/envs/sam_3d_body/bin/python (torch + sam3), 1 GPU. """ import argparse import json import math import sys import time from pathlib import Path import cv2 import numpy as np sys.path.insert(0, "/home/wujiayir/robot_tools/trex/scripts") sys.path.insert(0, "/home/wujiayir/robot_tools/droid/scripts/diag") import trex_gt_masks as TG # noqa: E402 (read-only reuse) import gt_masks as GM # noqa: E402 WORK_W = 640 MISS_IOU = 0.3 def read_jsonl(p): return [json.loads(l) for l in open(p) if l.strip()] def pred_time_pairs(n_pred, pred_fps, start_time_s, gt_fps, n_gt): pairs = [] for j in range(n_pred): t = start_time_s + j / pred_fps n = int(round(t * gt_fps)) if 0 <= n < n_gt: pairs.append((j, n, t)) return pairs def read_frames(path, idx, gray=False): """frames at the given indices (sorted set) from a video; returns {index: frame}. Sequential decode up to max(idx).""" want = sorted(set(int(i) for i in idx)) out = {} if not want: return out cap = cv2.VideoCapture(str(path)) k, last = 0, want[-1] wi = 0 while k <= last: ok, fr = cap.read() if not ok: break if k == want[wi]: out[k] = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY) if gray else fr wi += 1 if wi >= len(want): break k += 1 cap.release() return out def video_len(path): cap = cv2.VideoCapture(str(path)) n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) cap.release() return n def work_size(w, h): hh = int(round(WORK_W * h / w / 2.0)) * 2 return WORK_W, max(2, hh) def make_g(mask_u8): robot = mask_u8 > 127 z = np.zeros_like(robot) return dict(robot=robot, left_arm=robot, right_arm=z, body=z, left_hand=z, right_hand=z, arms=robot, hands=z, vega=robot) MOGE_GLOB = "/home/wujiayir/.cache/huggingface/hub/models--Ruicheng--moge-2-vitl-normal/snapshots/*/model.pt" def build_moge(device="cuda"): import glob import torch from moge.model.v2 import MoGeModel ck = sorted(glob.glob(MOGE_GLOB), key=lambda p: Path(p).stat().st_mtime)[-1] m = MoGeModel.from_pretrained(ck).to(device).eval() print(f"[moge] {ck}", flush=True) return m def moge_normal(model, bgr): """-> (normal float32 [H,W,3] in the OpenCV camera frame, valid bool [H,W]).""" import torch x = torch.from_numpy(bgr[:, :, ::-1].copy()).permute(2, 0, 1).float().to(next(model.parameters()).device) / 255.0 with torch.no_grad(): out = model.infer(x, apply_mask=False) n = out["normal"].float().cpu().numpy() valid = out["mask"].cpu().numpy().astype(bool) if "mask" in out else np.ones(n.shape[:2], bool) valid &= np.linalg.norm(n, axis=2) > 0.5 return n, valid # Per-dataset decode of the stored normal video into OpenCV camera normals, VERIFIED against MoGe-2 on real frames # (diag_normal_convention.py): DROID/trex/HRDexDB/Xp renders are OpenGL -> flip y,z (17 deg on real frames); hot3d UmeTrack normals # were rendered in the sensor frame and the video rotated with np.rot90(k=3) WITHOUT rotating the vectors -> stored (R,G,B) = # (n_y, -n_x, n_z): decode x = -G, y = R, z = B (29 deg on real frames vs 67/112 for the naive decodes). NORMAL_DECODE = {"hot3d": ((1, 0, 2), (-1.0, 1.0, 1.0))} def decode_control_normal(rgb, convention, dataset=None): n = rgb.astype(np.float32) / 127.5 - 1.0 if dataset in NORMAL_DECODE: perm, signs = NORMAL_DECODE[dataset] n = n[..., list(perm)] * np.array(signs, np.float32) elif convention == "opengl": # OpenGL camera (y up, z toward camera) -> OpenCV (y down, z forward) n[..., 1] *= -1.0 n[..., 2] *= -1.0 nn = np.linalg.norm(n, axis=2, keepdims=True) return n / np.maximum(nn, 1e-6) def normal_metrics(moge, bgr, ctrl_rgb, ctrl_mask, convention, dataset=None): """angular error between MoGe normals of `bgr` and the decoded control normal inside the eroded control mask.""" try: n_pred, valid = moge_normal(moge, bgr) except Exception as ex: # noqa return dict(normal_status="error", normal_err=None, normal_err_median=None, normal_in30=None, normal_n=0, normal_error_msg=repr(ex)[:200]) n_ctrl = decode_control_normal(ctrl_rgb, convention, dataset) m = cv2.erode(ctrl_mask.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool) & valid if m.sum() < 50: return dict(normal_status="no_mask", normal_err=None, normal_err_median=None, normal_in30=None, normal_n=int(m.sum())) dot = np.clip((n_pred[m] * n_ctrl[m]).sum(1), -1.0, 1.0) ang = np.degrees(np.arccos(dot)) return dict(normal_status="ok", normal_err=float(ang.mean()), normal_err_median=float(np.median(ang)), normal_in30=float((ang < 30).mean()), normal_n=int(m.sum())) def sam_frame(model, proc, bgr, g): rend = g["robot"] if rend.sum() < 50: return dict(status="no_control", iou=None, choice=None, area_rend=int(rend.sum()), area_sam=0) try: cands, pr, info = TG.sam3_robot_frame(model, proc, bgr, g) pos = np.array(pr["pos"]) if pr["pos"] else np.zeros((0, 2)) cmasks, mt = {}, {} for c in TG.PRIORITY: cmasks[c] = GM.clean_mask(cands[c], rend, spatial=True) mt[c] = GM.metrics(cmasks[c], rend, pos) choice, status, agree, m = TG.choose_robot(mt, cmasks, int(rend.sum())) iou = float((m & rend).sum() / max(1, (m | rend).sum())) return dict(status=status, iou=iou, choice=choice, agree_text_pts=agree, area_rend=int(rend.sum()), area_sam=int(m.sum()), area_ratio=float(m.sum() / max(1, rend.sum()))) except Exception as ex: # noqa return dict(status="error", iou=None, choice=None, error=repr(ex)[:300], area_rend=int(rend.sum()), area_sam=0) def sample_indices(n_pred, k): """k evenly spaced prediction frame indices in [1, n_pred-1].""" if n_pred <= 1: return [] k = min(k, n_pred - 1) return sorted(set(int(round(x)) for x in np.linspace(1, n_pred - 1, k))) def eval_unit(row, method, pred_root, model, proc, k_frames, moge=None): ud = pred_root / method / row["unit_id"] meta_p = ud / "pred_meta.json" if not (ud / "pred.mp4").exists() or not meta_p.exists(): return dict(unit_id=row["unit_id"], method=method, status="missing") meta = json.load(open(meta_p)) if meta.get("status") in ("missing", "na", "failed"): return dict(unit_id=row["unit_id"], method=method, status=meta.get("status"), reason=meta.get("reason")) n_gt = row["num_frames"] n_pred = video_len(ud / "pred.mp4") pfps = float(meta.get("fps") or row["fps"]) pairs = pred_time_pairs(n_pred, pfps, float(meta.get("start_time_s", 0.0)), row["fps"], n_gt) if len(pairs) < 2: return dict(unit_id=row["unit_id"], method=method, status="too_short", n_pred=n_pred) js = sample_indices(len(pairs), k_frames) sel = [pairs[j] for j in js] pf = read_frames(ud / "pred.mp4", [j for j, _, _ in sel]) off = row["start_frame"] if row.get("mask_indexed_like_rgb", True) else 0 mf = read_frames(row["mask_path"], [off + n for _, n, _ in sel], gray=True) nf_ = read_frames(row["normal_path"], [off + n for _, n, _ in sel]) if moge is not None else {} W, H = row["image_size"] box = meta.get("gt_crop") x0, y0, x1, y1 = box if box else [0, 0, W, H] ww, hh = work_size(x1 - x0, y1 - y0) frames = [] for j, n, t in sel: if j not in pf or (off + n) not in mf: frames.append(dict(j=j, n=n, t=round(t, 3), status="decode_error", iou=None)) continue m = mf[off + n] if m.shape[:2] != (H, W): m = cv2.resize(m, (W, H), interpolation=cv2.INTER_NEAREST) m = cv2.resize(m[y0:y1, x0:x1], (ww, hh), interpolation=cv2.INTER_NEAREST) p = cv2.resize(pf[j], (ww, hh), interpolation=cv2.INTER_AREA) r = sam_frame(model, proc, p, make_g(m)) if moge is not None and (off + n) in nf_: c = nf_[off + n] if c.shape[:2] != (H, W): c = cv2.resize(c, (W, H), interpolation=cv2.INTER_AREA) c = cv2.resize(c[y0:y1, x0:x1], (ww, hh), interpolation=cv2.INTER_AREA)[:, :, ::-1] # BGR -> RGB r.update(normal_metrics(moge, p, c, m > 127, row["normal_convention"], row.get("dataset"))) frames.append(dict(j=j, n=n, t=round(t, 3), **r)) return finish_unit(row, method, frames, extra=dict(n_pred=n_pred, pred_fps=pfps, gt_crop=box, work_size=[ww, hh])) def eval_unit_gt(row, model, proc, k_frames, box=None, moge=None): """score the REAL video at k GT frames (ceiling).""" n_gt = row["num_frames"] ns = sample_indices(n_gt, k_frames) off_rgb = row["start_frame"] off = row["start_frame"] if row.get("mask_indexed_like_rgb", True) else 0 rf = read_frames(row["rgb_path"], [off_rgb + n for n in ns]) mf = read_frames(row["mask_path"], [off + n for n in ns], gray=True) nf_ = read_frames(row["normal_path"], [off + n for n in ns]) if moge is not None else {} W, H = row["image_size"] x0, y0, x1, y1 = box if box else [0, 0, W, H] ww, hh = work_size(x1 - x0, y1 - y0) frames = [] for n in ns: if (off_rgb + n) not in rf or (off + n) not in mf: frames.append(dict(j=n, n=n, t=round(n / row["fps"], 3), status="decode_error", iou=None)) continue m, p = mf[off + n], rf[off_rgb + n] if m.shape[:2] != (H, W): m = cv2.resize(m, (W, H), interpolation=cv2.INTER_NEAREST) if p.shape[:2] != (H, W): p = cv2.resize(p, (W, H), interpolation=cv2.INTER_AREA) m = cv2.resize(m[y0:y1, x0:x1], (ww, hh), interpolation=cv2.INTER_NEAREST) p = cv2.resize(p[y0:y1, x0:x1], (ww, hh), interpolation=cv2.INTER_AREA) r = sam_frame(model, proc, p, make_g(m)) if moge is not None and (off + n) in nf_: c = nf_[off + n] if c.shape[:2] != (H, W): c = cv2.resize(c, (W, H), interpolation=cv2.INTER_AREA) c = cv2.resize(c[y0:y1, x0:x1], (ww, hh), interpolation=cv2.INTER_AREA)[:, :, ::-1] r.update(normal_metrics(moge, p, c, m > 127, row["normal_convention"], row.get("dataset"))) frames.append(dict(j=n, n=n, t=round(n / row["fps"], 3), **r)) return finish_unit(row, "gt", frames, extra=dict(gt_crop=box, work_size=[ww, hh])) def finish_unit(row, method, frames, extra=None): scored = [f for f in frames if f.get("status") not in ("decode_error", "no_control")] usable = [f["iou"] for f in scored if f.get("status") in TG.STATUS_USABLE and f.get("iou") is not None] miss = [1.0 if (f.get("status") in ("failed", "error") or (f.get("iou") is not None and f["iou"] < MISS_IOU)) else 0.0 for f in scored] # IoU with misses counted as 0 (penalised mean): the number to compare methods on iou_all = [f["iou"] if (f.get("iou") is not None and f.get("status") in TG.STATUS_USABLE + ("marginal",)) else 0.0 for f in scored] ne = [f["normal_err"] for f in frames if f.get("normal_status") == "ok"] nm = [f["normal_err_median"] for f in frames if f.get("normal_status") == "ok"] n30 = [f["normal_in30"] for f in frames if f.get("normal_status") == "ok"] rec = dict(unit_id=row["unit_id"], method=method, dataset=row["dataset"], unit_type=row["unit_type"], status="ok" if scored else "no_frames", n_sampled=len(frames), n_scored=len(scored), n_usable=len(usable), iou_usable_mean=float(np.mean(usable)) if usable else None, iou_mean_pen=float(np.mean(iou_all)) if iou_all else None, miss_rate=float(np.mean(miss)) if miss else None, normal_err=float(np.mean(ne)) if ne else None, normal_err_median=float(np.mean(nm)) if nm else None, normal_in30=float(np.mean(n30)) if n30 else None, normal_frames=len(ne), frames=frames) if extra: rec.update(extra) return rec def boot_ci(vals, n=1000, seed=0): v = np.asarray([x for x in vals if x is not None], float) if len(v) == 0: return (None, None, None) if len(v) == 1: return (float(v[0]), float(v[0]), float(v[0])) rng = np.random.default_rng(seed) bs = [rng.choice(v, len(v), replace=True).mean() for _ in range(n)] return (float(v.mean()), float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))) def main(): ap = argparse.ArgumentParser() ap.add_argument("--manifests", nargs="+", required=True) ap.add_argument("--pred-root", default="preds") ap.add_argument("--methods", nargs="+", required=True) ap.add_argument("--out", required=True) ap.add_argument("--frames-per-unit", type=int, default=8, help="sampled prediction frames per short unit") ap.add_argument("--frames-per-unit-long", type=int, default=24) ap.add_argument("--with-gt", action="store_true", help="also score the real video at the same GT frames (ceiling)") ap.add_argument("--max-units", type=int, default=0) ap.add_argument("--ckpt", default=None) ap.add_argument("--summarize-only", action="store_true") ap.add_argument("--normals", action="store_true", help="also MoGe-2 normal angular error vs the control normal") ap.add_argument("--normal-convention-override", default=None, choices=[None, "opencv", "opengl"], help="decode the control normals with this convention instead of the manifest's (diagnostic)") a = ap.parse_args() out = Path(a.out) out.mkdir(parents=True, exist_ok=True) pred_root = Path(a.pred_root) rows = [] for mp in a.manifests: rows += [r for r in read_jsonl(mp) if not r.get("excluded_reason")] if a.max_units: rows = rows[: a.max_units] if a.normal_convention_override: for r in rows: r["normal_convention"] = a.normal_convention_override methods = list(a.methods) + (["gt"] if a.with_gt else []) todo = [(r, m) for m in methods for r in rows if not (out / m / f"{r['unit_id']}.json").exists()] print(f"[ctrl] {len(rows)} units x {len(methods)} methods; {len(todo)} to compute", flush=True) if todo and not a.summarize_only: model, proc = GM.build_sam3(a.ckpt) moge = build_moge() if a.normals else None t0 = time.time() for i, (r, m) in enumerate(todo): k = a.frames_per_unit_long if r["unit_type"] == "long" else a.frames_per_unit if m == "gt": # use the first method's crop so the ceiling is scored on the same field of view when available box = None for mm in a.methods: mp_ = pred_root / mm / r["unit_id"] / "pred_meta.json" if mp_.exists(): box = json.load(open(mp_)).get("gt_crop") if box: break rec = eval_unit_gt(r, model, proc, k, box, moge) else: rec = eval_unit(r, m, pred_root, model, proc, k, moge) (out / m).mkdir(exist_ok=True) json.dump(rec, open(out / m / f"{r['unit_id']}.json", "w")) if i % 10 == 0 or i == len(todo) - 1: el = time.time() - t0 print(f"[ctrl] {i + 1}/{len(todo)} {m} {r['unit_id'][:48]} {el:.0f}s ({el / (i + 1):.1f}s/unit) iou_pen={rec.get('iou_mean_pen')} miss={rec.get('miss_rate')} nerr={rec.get('normal_err')}", flush=True) # ---- summary lines = ["dataset,unit_type,method,n_units,n_ok,iou_pen_mean,iou_pen_lo,iou_pen_hi,iou_usable_mean,miss_rate,miss_lo,miss_hi,usable_frac,normal_err_deg,normal_err_lo,normal_err_hi,normal_err_median,normal_in30"] md = ["| dataset | type | method | units | IoU_ctrl (miss=0) [95% CI] | IoU usable | miss rate [95% CI] | usable frames | normal err deg [95% CI] | median | <30 deg |", "|---|---|---|---|---|---|---|---|---|---|---|"] groups = {} for m in methods: for r in rows: p = out / m / f"{r['unit_id']}.json" if p.exists(): groups.setdefault((r["dataset"], r["unit_type"], m), []).append(json.load(open(p))) for (ds, ut, m), recs in sorted(groups.items()): ok = [x for x in recs if x.get("status") == "ok"] ip = boot_ci([x["iou_mean_pen"] for x in ok]) iu = boot_ci([x["iou_usable_mean"] for x in ok]) ms = boot_ci([x["miss_rate"] for x in ok]) uf = (sum(x["n_usable"] for x in ok) / max(1, sum(x["n_scored"] for x in ok))) if ok else None ne = boot_ci([x.get("normal_err") for x in ok]); nmed = boot_ci([x.get("normal_err_median") for x in ok]); n30 = boot_ci([x.get("normal_in30") for x in ok]) f = lambda v: "" if v is None else f"{v:.3f}" lines.append(",".join([ds, ut, m, str(len(recs)), str(len(ok)), f(ip[0]), f(ip[1]), f(ip[2]), f(iu[0]), f(ms[0]), f(ms[1]), f(ms[2]), f(uf), f(ne[0]), f(ne[1]), f(ne[2]), f(nmed[0]), f(n30[0])])) md.append(f"| {ds} | {ut} | {m} | {len(ok)}/{len(recs)} | {f(ip[0])} [{f(ip[1])}, {f(ip[2])}] | {f(iu[0])} | {f(ms[0])} [{f(ms[1])}, {f(ms[2])}] | {f(uf)} | {f(ne[0])} [{f(ne[1])}, {f(ne[2])}] | {f(nmed[0])} | {f(n30[0])} |") (out / "summary.csv").write_text("\n".join(lines) + "\n") (out / "summary.md").write_text("\n".join(md) + "\n") print("\n".join(md)) if __name__ == "__main__": main()