hkust-aaron's picture
Whole-video actions, task graphs, tissue tracks and robot-learning exports
944c1f9 verified
Raw History Blame Contribute Delete
11.1 kB
"""Per-frame scene graphs and discretised action tokens for the three action-labelled clips.
Usage: python 18_scene_graph_tokens.py <pack_dir>
Scene graph (every frame): nodes for each instrument (class, tip, shaft angle,
relative depth, jaw state, energy, active verb), each target tissue (area,
centroid, reliability) and gauze; edges
acts_on(I, X, verb) from the action segments
tip_contacts(I, X) tip within 6 px of tissue X's mask (2D proxy for contact)
occludes(I, X) instrument mask overlaps tissue X's mask
near(I, J) tips closer than 80 px
plus tissue states derived from the actions: under_traction, energy_applied, pressed.
Action tokens (every 5 frames = 0.2 s, per instrument), the form a policy or
video-language-action model is trained to output:
dx, dy tip displacement over the step with camera motion removed (px),
binned to -4..+4 with edges 2 / 6 / 15 / 30 px
dz change of tip relative inverse depth, binned -2..+2 (edges 0.03 / 0.10);
positive = towards the lens; empty when no depth
rot change of shaft angle, binned -2..+2 (edges 3 / 10 degrees)
jaw open / close / hold / none (from the jaw-state labels)
energy 0 / 1
token e.g. "<dx+2><dy-1><dz0><rot0><jaw:close><e0>"
verb the active action label for the step (the supervision target)
Writes layer6_robot_learning/scene_graphs.jsonl and action_tokens.csv.
"""
import csv
import json
import sys
from pathlib import Path
import cv2
import numpy as np
pack = Path(sys.argv[1])
L4, L5 = pack / "layer4_tool_kinematics", pack / "layer5_actions"
OUT = pack / "layer6_robot_learning"
OUT.mkdir(exist_ok=True)
acts = json.load(open(L5 / "actions.json"))
qual = json.load(open(L5 / "target_tissue" / "quality.json"))["objects"]
def load(path, key=("frame", "track_id")):
d = {}
if path.exists():
with open(path) as fh:
for r in csv.DictReader(fh):
d[tuple(int(r[k]) for k in key)] = r
return d
tips, comp, depth = load(L4 / "tool_tips.csv"), load(L4 / "tool_motion_compensated.csv"), load(L4 / "tool_depth.csv")
cam = load(L4 / "camera_motion.csv", ("frame",))
TRACTION = {"retract", "peel", "counter_traction", "lift_off"}
def fnum(r, k):
return float(r[k]) if r and r.get(k) not in (None, "") else None
def active(c, t, f):
return [s for s in c["segments"] if s["start_frame"] <= f <= s["end_frame"] and
s["lane"] == t]
def tip_of(f, t, c):
r = tips.get((f, t)) or (tips.get((f, 3)) if c["clip_id"] == 5 and t == 101 else None)
return r
def target_ids(s):
return [int(x) for x in __import__("re").findall(r"\[(\d+)\]", s["target"])]
def binv(v, edges):
if v is None:
return None
k = int(np.searchsorted(edges, abs(v), side="right"))
return int(np.sign(v)) * k
sg_f = open(OUT / "scene_graphs.jsonl", "w")
tok_rows = []
for c in acts["clips"]:
cid = c["clip_id"]
dmeta = json.load(open(pack / "dense_tracks" / "tracks" / f"clip_{cid:02d}.json"))
tp = L5 / "target_tissue" / "tracks" / f"clip_{cid:02d}.json"
tmeta = json.load(open(tp)) if tp.exists() else {"objects": {}}
tracks = sorted({s["lane"] for s in c["segments"]})
for f in range(c["start_frame"], c["end_frame"] + 1):
inst = cv2.imread(str(pack / "dense_tracks" / "masks" / f"clip_{cid:02d}" / f"{f:05d}.png"), 0)
tpath = L5 / "target_tissue" / "masks" / f"clip_{cid:02d}" / f"{f:05d}.png"
tis = cv2.imread(str(tpath), 0) if tmeta["objects"] and tpath.exists() else None
nodes, edges = [], []
tissue_nodes = {}
names = {**{k: {"name": v} for k, v in c["tissue_tracks"].items()}, **tmeta["objects"]}
for oid, o in names.items(): # named targets without a SAM track get a node with no mask
m = (tis == int(oid)) if (tis is not None and oid in tmeta["objects"]) else np.zeros((576, 720), bool)
qo = qual.get(f"clip_{cid:02d}/{oid}", {})
reliable = qo.get("status") == "ok" and f not in set(qo.get("unreliable_frames", []))
node = {"id": f"tissue:{oid}", "type": "tissue", "name": o["name"], "has_mask": oid in tmeta["objects"],
"area_px": int(m.sum()), "reliable": reliable and oid in tmeta["objects"],
"state": []}
if m.any():
ys, xs = np.nonzero(m)
node["centroid"] = [round(float(xs.mean()), 1), round(float(ys.mean()), 1)]
tissue_nodes[int(oid)] = (node, m if reliable else None) # unreliable masks give no geometric edges
nodes.append(node)
for tid_s, tr in dmeta["tracks"].items():
if tr["category"] == "gauze" and (inst == int(tid_s)).any():
nodes.append({"id": f"gauze:{tid_s}", "type": "gauze", "area_px": int((inst == int(tid_s)).sum())})
tip_pts = {}
for t in tracks:
act = active(c, t, f)
r = tip_of(f, t, c)
dr = depth.get((f, t))
node = {"id": f"instrument:{t}", "type": "instrument", "class": c["objects"][str(t)].split(" (")[0],
"in_view": bool(act and act[0]["verb"] != "absent"),
"tip": [fnum(r, "tip_x_smooth"), fnum(r, "tip_y_smooth")] if r and r["tip_x_smooth"] else None,
"shaft_angle_deg": fnum(r, "shaft_angle_deg"), "tip_rel_inv_depth": fnum(dr, "tip_rel_inv_depth"),
"verb": act[0]["verb"] if act else None, "jaw_state": act[0]["jaw_state"] if act else None,
"energy": bool(act and any(s["energy_visible"] for s in act))}
nodes.append(node)
if node["tip"]:
tip_pts[t] = node["tip"]
for s in act:
for x in target_ids(s):
edges.append({"rel": "acts_on", "src": f"instrument:{t}", "dst": f"tissue:{x}", "verb": s["verb"]})
tn = tissue_nodes.get(x)
if tn:
st = tn[0]["state"]
if s["verb"] in TRACTION and "under_traction" not in st:
st.append("under_traction")
if s["verb"] == "press" and "pressed" not in st:
st.append("pressed")
if s["energy_visible"] and "energy_applied" not in st:
st.append("energy_applied")
im = inst == t
for x, (tn, m) in tissue_nodes.items():
if m is None or not m.any():
continue
if node["tip"]:
xx, yy = int(node["tip"][0]), int(node["tip"][1])
win = m[max(0, yy - 6):yy + 7, max(0, xx - 6):xx + 7]
if win.any():
edges.append({"rel": "tip_contacts", "src": f"instrument:{t}", "dst": f"tissue:{x}"})
if (im & m).any():
edges.append({"rel": "occludes", "src": f"instrument:{t}", "dst": f"tissue:{x}"})
ks = sorted(tip_pts)
for i in range(len(ks)):
for j in range(i + 1, len(ks)):
a, b = tip_pts[ks[i]], tip_pts[ks[j]]
if np.hypot(a[0] - b[0], a[1] - b[1]) < 80:
edges.append({"rel": "near", "src": f"instrument:{ks[i]}", "dst": f"instrument:{ks[j]}"})
cr = cam.get((f,))
sg_f.write(json.dumps({"clip_id": cid, "frame": f, "time_s": round(f / 25, 2),
"camera": {k: fnum(cr, k) for k in ("tx", "ty", "rot_deg", "scale", "inlier_ratio")},
"nodes": nodes, "edges": edges}) + "\n")
# action tokens at 0.2 s steps
for t in tracks:
for f in range(c["start_frame"], c["end_frame"] + 1, 5):
g = min(f + 5, c["end_frame"])
act = active(c, t, f)
verb = act[0]["verb"] if act else None
dx = dy = 0.0
n_ok = 0
for h in range(f + 1, g + 1):
r = comp.get((h, t)) or (comp.get((h, 3)) if cid == 5 and t == 101 else None)
if r and r["dx_camera_removed"] != "":
dx += float(r["dx_camera_removed"])
dy += float(r["dy_camera_removed"])
n_ok += 1
have = n_ok >= 3
a0, a1 = tip_of(f, t, c), tip_of(g, t, c)
rot = None
if a0 and a1 and a0["shaft_angle_deg"] and a1["shaft_angle_deg"]:
rot = (float(a1["shaft_angle_deg"]) - float(a0["shaft_angle_deg"]) + 180) % 360 - 180
d0, d1 = fnum(depth.get((f, t)), "tip_rel_inv_depth"), fnum(depth.get((g, t)), "tip_rel_inv_depth")
dz = d1 - d0 if d0 is not None and d1 is not None else None
js0 = act[0]["jaw_state"] if act else "n/a"
act_g = active(c, t, g)
js1 = act_g[0]["jaw_state"] if act_g else "n/a"
if "->closed" in js0 or (js0 == "open" and js1 in ("closed", "open->closed")):
jaw = "close"
elif "->open" in js0 or (js0 == "closed" and js1 in ("open", "closed->open")):
jaw = "open"
elif js0 in ("open", "closed"):
jaw = "hold"
else:
jaw = "none"
e = int(bool(act and any(s["energy_visible"] for s in act)))
bx = binv(dx, [2, 6, 15, 30]) if have else None
by = binv(dy, [2, 6, 15, 30]) if have else None
bz = binv(dz, [0.03, 0.10])
br = binv(rot, [3, 10])
fmt = lambda name, v: f"<{name}{'+' if v and v > 0 else ''}{v if v is not None else 'NA'}>"
tok_rows.append({"clip_id": cid, "track_id": t, "frame": f, "to_frame": g, "verb": verb or "",
"dx_px": round(dx, 1) if have else "", "dy_px": round(dy, 1) if have else "",
"dz_rel": round(dz, 4) if dz is not None else "", "rot_deg": round(rot, 1) if rot is not None else "",
"jaw": jaw, "energy": e,
"token": fmt("dx", bx) + fmt("dy", by) + fmt("dz", bz) + fmt("rot", br) + f"<jaw:{jaw}><e{e}>"})
sg_f.close()
with open(OUT / "action_tokens.csv", "w", newline="") as fh:
w = csv.DictWriter(fh, list(tok_rows[0]))
w.writeheader()
w.writerows(tok_rows)
with open(OUT / "action_tokens.jsonl", "w") as fh: # same rows, typed, for JSON loaders
for r in tok_rows:
fh.write(json.dumps({k: (None if v == "" else v) for k, v in r.items()}) + "\n")
# sanity check: compensated tip speed per verb (holding should be slower than moving)
by = {}
for r in tok_rows:
if r["dx_px"] != "" and r["verb"]:
by.setdefault(r["verb"], []).append(np.hypot(r["dx_px"], r["dy_px"]) * 5)
check = {v: {"steps": len(x), "median_speed_px_s": round(float(np.median(x)), 1)} for v, x in sorted(by.items())}
json.dump(check, open(OUT / "speed_by_verb.json", "w"), indent=1)
print("scene graphs", sum(c["end_frame"] - c["start_frame"] + 1 for c in acts["clips"]), "token rows", len(tok_rows))
print(check)