"""Referent labels for the SO-101 shards from the demonstrations themselves ("hindsight"): no detector, no hand marks. The gripper's 3D tip comes from the recorded joints (URDF forward kinematics, with the joint offsets of the camera fit). Where the gripper closes on an object is where that object was; where it opens is where the object was put. Per frame the labels are the active step's skill code, the object point ("what") and the destination point ("where", or none) in the robot's base frame, in metres. The policy sees them as form B: projected into the fixed camera with the fitted camera (scripts/fit_camera.py), plus their offset from the projected tip. Steps per task (REALWORLD.md, Stage 2): towel fold: what = grasp point (then the tip, the towel edge is in the hand), where = release point cups pick-and-place: what = pink cup at grasp 1, where = release 1 (beige cup); then pick-and-place: what = grasp 2 (the beige cup), where = release 2 (white cup) drawer open: what = handle (the first reach before the block grasp; then the tip while pulling), no where; pick-and-place: what = block grasp point, where = block release point (inside the drawer); close: what = the handle where the pull ended (drawer open), no where push push: what = the mug, where = where the mug ends. The gripper never opens in this task, so the mug is found by colour in the fixed view (yellow) and placed on the table plane through the camera. Gripper events: a fall (close) or rise (open) of more than --delta units within --win frames (10 Hz). An episode whose events do not match its task's pattern is listed and gets no labels (mask False). Writes ref.npz into every shard directory (train and val): step, skill, what (N, 3), where (N, 3), where_valid, ok (frame labelled), tip (N, 3); and /labels_report.json. """ import argparse import json import os import sys import numpy as np import torch sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from popt.so101 import SO101, SO101Torch, project # noqa: E402 SKILLS = {"open": 0, "pick_place": 1, "close": 2, "push": 3, "fold": 4} # PoP's 5 skill rows; row 5 = unspecified TASK = {"so101-fold-towel": "towel", "so101-stack-cup-v4": "cups", "so101-drawer-v3": "drawer", "so101-push": "push"} def events(g: np.ndarray, delta: float, win: int) -> list: """[(t, 'close' | 'open')], alternating; close at the end of a fall, open at the start of a rise.""" d = g[win:] - g[:-win] out = [] for kind, m in (("close", d < -delta), ("open", d > delta)): t = 0 while t < len(m): if m[t]: s = t while t < len(m) and m[t]: t += 1 out.append((t - 1 + win if kind == "close" else s, kind)) t += 1 out.sort() merged = [] for t, k in out: # collapse repeats of the same kind (a fall in two stages is one close) if merged and merged[-1][1] == k: if k == "close": merged[-1] = (t, k) continue merged.append((t, k)) return merged def label_episode(task, tip, g, a, img=None, cam=None, table_z=None): """-> dict of per-frame arrays, or a reason string.""" L = len(tip) step = np.full(L, -1); skill = np.full(L, -1) what = np.zeros((L, 3)); where = np.zeros((L, 3)); wv = np.zeros(L, bool) ev = events(g, a.delta, a.win) closes = [t for t, k in ev if k == "close"] opens = [t for t, k in ev if k == "open"] def fill(s, e, k, sk, obj, dst, grasp_t=None): step[s:e] = k; skill[s:e] = SKILLS[sk] what[s:e] = obj if grasp_t is not None and grasp_t < e: what[max(s, grasp_t):e] = tip[max(s, grasp_t):e] # object in the hand if dst is not None: where[s:e] = dst; wv[s:e] = True if task in ("towel", "cups"): n = 1 if task == "towel" else 2 seq, t0 = [], 0 for _ in range(n): gc = [t for t in closes if t > t0 and any(o < t for o in opens)] if not gc: return "no_grasp" tg = gc[0] ro = [t for t in opens if t > tg] if not ro: return "no_release" tr = ro[0] seq.append((tg, tr)); t0 = tr s = 0 for k, (tg, tr) in enumerate(seq): e = tr + 1 if k < n - 1 else L fill(s, e, k, "fold" if task == "towel" else "pick_place", tip[tg], tip[tr], grasp_t=tg) s = e elif task == "drawer": if not opens: return "no_events" first_open = opens[0] r = np.linalg.norm(tip[:, :2], axis=1) # horizontal reach from the base # handle: the first reach peak after the gripper opens that is followed by a pull of at least 5 cm within # 4 s; end of the pull: the closest point to the base before the arm lifts (3 cm above the pull's lowest point) th = tp = None for t in range(first_open, L - 1): w = r[t:min(t + 40, L)] if len(w) > 2 and r[t] >= r[max(t - 5, 0):t + 6].max() and r[t] - w.min() > 0.05: th = t break if th is None: return "no_pull" lift = th + 1 while lift < L and tip[lift, 2] - tip[th:lift + 1, 2].min() < 0.03: lift += 1 tp = th + int(np.argmin(r[th:lift])) # block grasp: after the pull, the gripper falls 8 units below its open value and settles (hold value); # release: the first time it leaves the hold value by more than 1 unit, opening or closing # a close below --hold-min units holds nothing (missed grasp): wait for the gripper to reopen and look again start = tp + 1 while True: g_open = g[start - 1] tc = start while tc < L and g[tc] > g_open - 8: tc += 1 if tc >= L - 3: return "no_grasp" tg = tc while tg < L - 3 and g[tg + 3] < g[tg] - 0.5: tg += 1 if g[tg] >= a.hold_min: break reo = tg + 1 while reo < L and g[reo] < a.hold_min + 8: reo += 1 if reo >= L - 3: return "no_grasp" while reo < L - 1 and g[reo + 1] > g[reo] + 0.5: # let it finish opening reo += 1 start = reo + 1 tr = tg + 1 while tr < L and abs(g[tr] - g[tg]) <= 1.0: tr += 1 if tr >= L: return "no_release" fill(0, tp + 1, 0, "open", tip[th], None, grasp_t=th) fill(tp + 1, tr + 1, 1, "pick_place", tip[tg], tip[tr], grasp_t=tg) fill(tr + 1, L, 2, "close", tip[tp], None) elif task == "push": if img is None: return "no_image" mug = mug_track(img, cam, table_z, a) if mug is None: return "no_mug" fill(0, L, 0, "push", 0.0, mug[-1]) what[:] = mug return {"step": step, "skill": skill, "what": what, "where": where, "where_valid": wv} def yellow_mask(img): x = img.astype(np.float32) / 255 mx, mn = x.max(-1), x.min(-1) dd = mx - mn + 1e-6 r, g, b = x[..., 0], x[..., 1], x[..., 2] h = np.where(mx == r, ((g - b) / dd) % 6, np.where(mx == g, (b - r) / dd + 2, (r - g) / dd + 4)) * 60 s = dd / (mx + 1e-6) return (h >= 42) & (h <= 66) & (s >= 0.45) & (mx >= 0.35) def mug_track(img, cam, table_z, a): """Mug centroid per frame (yellow pixels; held over frames where it is hidden) -> 3D on the plane z = table_z + mug half height.""" m = yellow_mask(np.asarray(img)) L = len(m) pts = np.full((L, 2), np.nan) for t in range(L): ys, xs = np.nonzero(m[t]) if len(xs) >= a.min_px: pts[t] = [xs.mean(), ys.mean()] ok = ~np.isnan(pts[:, 0]) if ok.sum() < L // 2 or not ok[0]: return None for t in range(1, L): # hold the last seen position if not ok[t]: pts[t] = pts[t - 1] return backproject(pts, cam, table_z + a.mug_half_height) def backproject(uv, cam, z_plane): """Pixels (N, 2) in the stored image -> points on the plane z = z_plane (base frame).""" from popt.so101 import rotvec_to_matrix R = rotvec_to_matrix(torch.tensor(cam["rotvec"])).numpy() t = np.array(cam["t"]); f = np.array(cam["f"]); c = np.array(cam["c"]) xy = (uv - c) / f if "k1" in cam: # undo radial distortion by fixed-point iteration xd = xy.copy() for _ in range(10): r2 = (xy ** 2).sum(1, keepdims=True) xy = xd / (1 + cam["k1"] * r2 + cam.get("k2", 0.0) * r2 ** 2) rays = np.concatenate([xy, np.ones((len(xy), 1))], 1) @ R # camera -> base directions (R^T d) C = -R.T @ t s = (z_plane - C[2]) / rays[:, 2] return C + s[:, None] * rays def main(): p = argparse.ArgumentParser() p.add_argument("--shards", required=True, help="directory with train/ and val/") p.add_argument("--camera", required=True, help="directory with .json from scripts/fit_camera.py") p.add_argument("--urdf", required=True) p.add_argument("--delta", type=float, default=6.0, help="gripper change (units of 0-100) that counts as an event") p.add_argument("--win", type=int, default=3, help="frames (10 Hz) over which the change is measured") p.add_argument("--hold-min", type=float, default=8.0, help="drawer: a block hold keeps the gripper above this") p.add_argument("--release-tol", type=float, default=0.06, help="drawer: max distance (m) of a block release from the median") p.add_argument("--min-px", type=int, default=30, help="push: yellow pixels for the mug to count as seen") p.add_argument("--mug-half-height", type=float, default=0.045) a = p.parse_args() arm = SO101(a.urdf, 1) kin = SO101Torch(arm, "cpu") report, drawer_release = {}, {} for split in ("train", "val"): idx = json.load(open(os.path.join(a.shards, split, "index.json"))) for s in idx["shards"]: d = os.path.join(a.shards, split, s["dir"]) cam_j = json.load(open(os.path.join(a.camera, s["dir"] + ".json"))) cam = cam_j["camera"] | ({"k1": cam_j["distortion_k1_k2"][0], "k2": cam_j["distortion_k1_k2"][1]} if "distortion_k1_k2" in cam_j else {}) off = torch.tensor(cam_j.get("joint_offsets_deg", [0] * 5) + [0.0]) z = np.load(os.path.join(d, "arrays.npz")) eps = json.load(open(os.path.join(d, "episodes.json"))) N = s["frames"] with torch.no_grad(): tip = kin.tip(torch.tensor(z["state"], dtype=torch.float32), off).numpy().astype(np.float64) task = TASK[s["dataset"].split("/")[-1]] # table height: the lowest tip heights reached while the gripper is closed on something table_z = float(np.percentile(tip[:, 2], 1)) img = np.memmap(os.path.join(d, "agent.u8"), np.uint8, "r", shape=(N, 256, 256, 3)) if task == "push" else None out = {k: np.zeros((N,) + sh, dt) for k, sh, dt in (("step", (), np.int16), ("skill", (), np.int16), ("what", (3,), np.float32), ("where", (3,), np.float32), ("where_valid", (), bool), ("ok", (), bool))} rep = {"episodes": len(eps), "labelled": 0, "dropped": {}, "table_z": table_z, "dropped_episodes": {}} results = [] for e in eps: sl = slice(e["start"], e["start"] + e["length"]) r = label_episode(task, tip[sl], z["state"][sl, 5].astype(np.float64), a, img[sl] if img is not None else None, cam, table_z) results.append((e, sl, r)) if task == "drawer": # the drawer unit does not move: a block release far from the usual one is a mislabelled event rel = lambda r: r["where"][int(np.argmax(r["step"] == 1))] # noqa: E731 if split == "train": drawer_release[s["dataset"]] = np.median([rel(r) for _, _, r in results if not isinstance(r, str)], 0) med = drawer_release[s["dataset"]] results = [(e, sl, "release_off_drawer" if not isinstance(r, str) and np.linalg.norm(rel(r) - med) > a.release_tol else r) for e, sl, r in results] rep["drawer_release_median_m"] = med.round(4).tolist() for e, sl, r in results: if isinstance(r, str): rep["dropped"][r] = rep["dropped"].get(r, 0) + 1 rep["dropped_episodes"][str(e["source_episode"])] = r continue for k in ("step", "skill", "what", "where", "where_valid"): out[k][sl] = r[k] out["ok"][sl] = r["step"] >= 0 rep["labelled"] += 1 np.savez(os.path.join(d, "ref.npz"), tip=tip.astype(np.float32), **out) json.dump(cam_j, open(os.path.join(d, "camera.json"), "w"), indent=1) report[f"{split}/{s['dir']}"] = rep print(split, s["dataset"], rep, flush=True) json.dump(report, open(os.path.join(a.shards, "labels_report.json"), "w"), indent=1) if __name__ == "__main__": main()