hkust-aaron's picture
Whole-video action labels, task graphs and robot-learning exports
3ae204c verified
Raw History Blame Contribute Delete
9.92 kB
"""Training-ready exports for the three action-labelled clips.
Usage: python 19_training_exports.py <pack_dir>
Turns the label layers into the record formats models are trained on. All files go
to layer6_robot_learning/ and refer to images in frames/clip_XX/<frame>.jpg
(every 5th frame, 0.2 s; 150 images).
vla_steps.jsonl one record per 0.2 s step: image, task, active subtask,
per-instrument state (tip, angle, relative depth, jaw,
energy), the action taken (token + continuous deltas),
the next 10 steps as an action chunk, and the language
instruction in force. Vision-language-action format.
vqa.jsonl grounded question/answer pairs generated from the labels
(what is instrument X doing, jaw state, energy, target,
tip location, counting, next action). Every answer is a
label lookup, not free text.
reasoning.jsonl decision points as observation -> assessment -> decision
-> expected result, with the outcome seen afterwards;
plus one plan per clip (goal -> ordered subtasks).
next_action.jsonl at each action boundary: recent history -> next verb,
target and instruction for that instrument.
"""
import csv
import json
import sys
from pathlib import Path
import cv2
pack = Path(sys.argv[1])
L4, L5, OUT = pack / "layer4_tool_kinematics", pack / "layer5_actions", pack / "layer6_robot_learning"
acts = json.load(open(L5 / "actions.json"))
graph = {c["clip_id"]: c for c in json.load(open(L5 / "task_graph.json"))["clips"]}
toks = {}
with open(OUT / "action_tokens.csv") as fh:
for r in csv.DictReader(fh):
toks[(int(r["clip_id"]), int(r["track_id"]), int(r["frame"]))] = r
sgs = {}
with open(OUT / "scene_graphs.jsonl") as fh:
for l in fh:
d = json.loads(l)
sgs[d["frame"]] = d
NAMES = {"dark_rod": "the dark rod", "white_insulated_jawed": "the instrument with white-insulated jaws",
"fenestrated_grasper": "the fenestrated grasper", "jawed instrument": "the jawed grasper"}
# frames
cap = cv2.VideoCapture(str(pack / "video" / "laparoscopic_sample_001_intracorporeal.mp4"))
for c in acts["clips"]:
d = OUT / "frames" / f"clip_{c['clip_id']:02d}"
d.mkdir(parents=True, exist_ok=True)
for f in range(c["start_frame"], c["end_frame"] + 1, 5):
cap.set(cv2.CAP_PROP_POS_FRAMES, f)
_, img = cap.read()
cv2.imwrite(str(d / f"{f:05d}.jpg"), img, [cv2.IMWRITE_JPEG_QUALITY, 88])
def img(cid, f):
return f"frames/clip_{cid:02d}/{f - (f - acts_by[cid]['start_frame']) % 5:05d}.jpg"
acts_by = {c["clip_id"]: c for c in acts["clips"]}
def inst_name(c, t):
return NAMES.get(c["objects"][str(t)].split(" (")[0], "the instrument")
def subtask_at(cid, f):
return [s["name"] for s in graph[cid]["subtasks"] if s["frames"][0] <= f <= s["frames"][1]]
n = {}
# ---- VLA steps
with open(OUT / "vla_steps.jsonl", "w") as fh:
k = 0
for c in acts["clips"]:
cid = c["clip_id"]
tracks = sorted({s["lane"] for s in c["segments"]})
steps = list(range(c["start_frame"], c["end_frame"] + 1, 5))
for i, f in enumerate(steps):
sg = {nd["id"]: nd for nd in sgs[f]["nodes"]}
state, action, chunk, instr = {}, {}, {}, {}
for t in tracks:
nd = sg[f"instrument:{t}"]
state[str(t)] = {"class": nd["class"], "in_view": nd["in_view"], "tip_xy": nd["tip"],
"shaft_angle_deg": nd["shaft_angle_deg"], "tip_rel_inv_depth": nd["tip_rel_inv_depth"],
"jaw_state": nd["jaw_state"], "energy": nd["energy"]}
r = toks[(cid, t, f)]
num = lambda v: float(v) if v != "" else None
action[str(t)] = {"token": r["token"], "verb": r["verb"],
"dx_px": num(r["dx_px"]), "dy_px": num(r["dy_px"]), "dz_rel": num(r["dz_rel"]),
"rot_deg": num(r["rot_deg"]), "jaw": r["jaw"], "energy": int(r["energy"])}
chunk[str(t)] = [toks[(cid, t, g)]["token"] for g in steps[i:i + 10]]
seg = [s for s in c["segments"] if s["start_frame"] <= f <= s["end_frame"] and s["lane"] == t
and s["instruction"]]
instr[str(t)] = seg[0]["instruction"] if seg else ""
fh.write(json.dumps({"episode": f"clip_{cid:02d}", "step": i, "frame": f, "time_s": round(f / 25, 2),
"image": img(cid, f), "task": c["visible_goal"], "subtask": subtask_at(cid, f),
"instruction": instr, "state": state, "action": action, "action_chunk_2s": chunk,
"camera": sgs[f]["camera"]}) + "\n")
k += 1
n["vla_steps"] = k
# ---- VQA
with open(OUT / "vqa.jsonl", "w") as fh:
k = 0
def qa(cid, f, qtype, q, a, **extra):
global k
fh.write(json.dumps({"image": img(cid, f), "frame": f, "type": qtype, "question": q, "answer": a, **extra}) + "\n")
k += 1
for c in acts["clips"]:
cid = c["clip_id"]
tracks = sorted({s["lane"] for s in c["segments"]})
tp = L5 / "target_tissue" / "tracks" / f"clip_{cid:02d}.json"
tmeta = json.load(open(tp)) if tp.exists() else {"objects": {}}
for f in range(c["start_frame"], c["end_frame"] + 1, 5):
sg = {nd["id"]: nd for nd in sgs[f]["nodes"]}
inview = [t for t in tracks if sg[f"instrument:{t}"]["in_view"]]
qa(cid, f, "count", "How many instruments are working in the view?", str(len(inview)))
for t in tracks:
nd = sg[f"instrument:{t}"]
nm = inst_name(c, t)
if not nd["in_view"]:
qa(cid, f, "presence", f"Is {nm} in view?", "No")
continue
seg = [s for s in c["segments"] if s["start_frame"] <= f <= s["end_frame"] and s["lane"] == t][0]
qa(cid, f, "action", f"What is {nm} doing?", seg["verb"].replace("_", " "))
if seg["jaw_state"] not in ("n/a", "unknown"):
qa(cid, f, "jaw_state", f"Are the jaws of {nm} open or closed?", seg["jaw_state"].replace("->", " to "))
qa(cid, f, "energy", f"Is energy being applied by {nm}?", "Yes" if seg["energy_visible"] else "No")
if seg["target"] not in ("-", ""):
qa(cid, f, "target", f"What is {nm} acting on?", seg["target"].split(" [")[0] if "[" in seg["target"]
else seg["target"])
if nd["tip"]:
px, py = round(nd["tip"][0]), round(nd["tip"][1])
qa(cid, f, "point", f"Point to the tip of {nm}.", f"({px}, {py})", answer_point=[px, py],
answer_format="(x, y) in 720x576 pixels")
nxt = [s for s in c["segments"] if s["lane"] == t and s["start_frame"] > f and s["verb"] != "absent"]
if nxt:
s = min(nxt, key=lambda s: s["start_frame"])
qa(cid, f, "next_action", f"What will {nm} do next?", s["verb"].replace("_", " "),
in_seconds=round((s["start_frame"] - f) / 25, 1))
for oid, o in tmeta["objects"].items():
tn = sg[f"tissue:{oid}"]
if tn["reliable"] and tn["area_px"] >= 150:
actors = [e["src"] for e in sgs[f]["edges"] if e["rel"] == "acts_on" and e["dst"] == f"tissue:{oid}"]
qa(cid, f, "tissue_interaction", f"Which instrument is working on the {o['name'].replace('_', ' ')}?",
", ".join(inst_name(c, int(a.split(':')[1])) for a in sorted(set(actors))) or "None")
n["vqa"] = k
# ---- reasoning + plans
with open(OUT / "reasoning.jsonl", "w") as fh:
k = 0
for c in acts["clips"]:
cid = c["clip_id"]
g = graph[cid]
fh.write(json.dumps({"type": "plan", "image": img(cid, c["start_frame"]), "goal": g["goal"],
"initial_state": g["initial_state"],
"plan": [{"subtask": s["name"], "pre": s["pre"], "effects": s["effects"],
"success_check": s["success_check"]} for s in g["subtasks"]]}) + "\n")
k += 1
for d in g["decisions"]:
fh.write(json.dumps({"type": "decision", "image": img(cid, d["frame"]),
"context_images": [img(cid, max(c["start_frame"], d["frame"] - x)) for x in (50, 25)],
"goal": g["goal"], **d}) + "\n")
k += 1
n["reasoning"] = k
# ---- next action at boundaries
with open(OUT / "next_action.jsonl", "w") as fh:
k = 0
for c in acts["clips"]:
cid = c["clip_id"]
tracks = sorted({s["lane"] for s in c["segments"]})
for t in tracks:
segs = sorted([s for s in c["segments"] if s["lane"] == t], key=lambda s: s["start_frame"])
for i in range(1, len(segs)):
s = segs[i]
fh.write(json.dumps({"image": img(cid, max(c["start_frame"], s["start_frame"] - 1)),
"instrument": c["objects"][str(t)].split(" (")[0], "track_id": t,
"task": c["visible_goal"],
"history": [x["verb"] for x in segs[max(0, i - 4):i]],
"next": {"verb": s["verb"], "target": s["target"], "jaw_state": s["jaw_state"],
"instruction": s["instruction"], "start_frame": s["start_frame"]}}) + "\n")
k += 1
n["next_action"] = k
print(n)