Datasets:
File size: 18,641 Bytes
f20e058 b91b0f5 f20e058 3ae204c f20e058 3ae204c b91b0f5 3ae204c f20e058 3ae204c f20e058 3ae204c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | """Task hierarchy, symbolic state and decision points for the three action-labelled clips.
Usage: python 17_task_graph.py <pack_dir>
Adds the "why" layer on top of layer5_actions/actions.json:
goal -> subtasks -> action segments, where each subtask has
preconditions / effects symbolic predicates over instruments and tissue,
e.g. held(gauze, #101), under_tension(material)
success_check what is visible when the subtask has worked
decision points: observation -> assessment -> decision -> expected result,
each anchored to a frame, and the outcome actually seen afterwards.
Written by an AI model from the video. Observations and outcomes describe only
what is visible; assessments and decisions are a plausible rationale for what
the operator did, not a record of their intent. Reviewed and approved by the contributing physician (2026-11-17).
Writes layer5_actions/task_graph.json.
"""
import json
import re
import sys
from pathlib import Path
pack = Path(sys.argv[1])
acts = json.load(open(pack / "layer5_actions" / "actions.json"))
PREDICATES = {
"held(X, I)": "object X is between the closed jaws of instrument I",
"on(X, Y)": "object X lies on / presses against Y",
"visible(X)": "X can be seen in the view",
"jaws_open(I)": "instrument I's jaws are open",
"between_jaws(X, I)": "X lies between the open jaws of I",
"under_tension(X)": "X is stretched by traction",
"separated(X, Y, p)": "X has come off Y; p = none / partial / complete",
"energy_applied(X)": "smoke, darkening or char appears at X",
"out_of_view(I)": "instrument I is not in the image",
"red_spot_visible(X)": "a red spot / ooze is visible on X",
}
T = {
5: {
"goal": "Control oozing above the lobules with gauze pressure",
"initial_state": ["held(gauze, #101)", "visible(oozing_surface)", "red_spot_visible(oozing_surface)", "on(#102, tissue_right)"],
"subtasks": [
{"id": "5.1", "name": "Bring the gauze to the oozing area", "segments": [[101, 1250], [101, 1263]],
"pre": ["held(gauze, #101)"], "effects": ["gauze over oozing_surface"],
"success_check": "gauze edge reaches the upper oozing area"},
{"id": "5.2", "name": "Apply pressure", "segments": [[101, 1275]],
"pre": ["gauze over oozing_surface"], "effects": ["on(gauze, oozing_surface)"],
"success_check": "gauze stays on the area for about 3 s"},
{"id": "5.3", "name": "Check underneath", "segments": [[101, 1346]],
"pre": ["on(gauze, oozing_surface)"], "effects": ["visible(oozing_surface)"],
"success_check": "the area is uncovered and in view"},
{"id": "5.4", "name": "Re-apply pressure further right", "segments": [[101, 1363]],
"pre": ["red_spot_visible(oozing_surface)"], "effects": ["on(gauze, oozing_surface)"],
"success_check": "gauze covers the spot that was still red"},
{"id": "5.5", "name": "Leave the gauze and free the grasper", "segments": [[101, 1405], [101, 1412]],
"pre": ["on(gauze, oozing_surface)"], "effects": ["out_of_view(#101)", "not held(gauze, #101)"],
"success_check": "gauze stays in place after release"},
{"id": "5.6", "name": "Probe the site", "segments": [[102, 1416], [102, 1445]],
"pre": ["visible(oozing_surface)"], "effects": [], "success_check": "rod tip reaches the spot"},
{"id": "5.7", "name": "Take the gauze again", "segments": [[3, 1470], [101, 1476]],
"pre": ["out_of_view(#101)"], "effects": ["held(gauze, #101)"], "success_check": "gauze moves with the grasper"},
],
"decisions": [
{"frame": 1346, "observation": "The gauze has been pressed on the area for about 3 s; what is under it cannot be seen.",
"assessment": "Pressure alone gives no feedback; the site has to be looked at.",
"decision": "Lift the gauze off the area.", "expected": "The oozing area comes into view.",
"outcome_seen": "Frames 1350-1360: the area is uncovered; a red spot is still visible near the lobules."},
{"frame": 1363, "observation": "A red spot is still visible after lifting, slightly right of where the gauze was.",
"assessment": "The first placement did not cover the spot well.",
"decision": "Put the gauze back and press it further to the right.", "expected": "The gauze covers the remaining spot.",
"outcome_seen": "Frames 1385-1404: the gauze is pushed up and to the right over the area."},
{"frame": 1405, "observation": "The gauze lies over the area.",
"assessment": "The grasper is not needed to keep the gauze there.",
"decision": "Release the gauze and withdraw the grasper.", "expected": "The gauze stays in place.",
"outcome_seen": "Frames 1410-1420: the grasper leaves; the gauze stays at the left of the field."},
{"frame": 1416, "observation": "The field is open; the rod is free.",
"assessment": "The spot can be checked by touch while the gauze rests.",
"decision": "Move the rod to the spot and touch it.", "expected": "The rod tip reaches the spot.",
"outcome_seen": "Frames 1425-1440: the rod tip is next to the red spot."},
]},
40: {
"goal": "Grasp and coagulate a tissue band at the base of a yellow lobule",
"initial_state": ["visible(tissue_band)", "visible(yellow_lobule)", "visible(purplish_tissue)", "on(gauze, left)"],
"subtasks": [
{"id": "40.1", "name": "Open and position the jaws around the band", "segments": [[101, 10000], [101, 10013], [101, 10051]],
"pre": ["visible(tissue_band)"], "effects": ["jaws_open(#101)", "between_jaws(tissue_band, #101)"],
"success_check": "the band sits between the open jaws"},
{"id": "40.2", "name": "Expose with the second instrument", "segments": [[102, 10126], [102, 10201]],
"pre": ["jaws_open(#101)"], "effects": ["visible(tissue_band)"],
"success_check": "tissue on the right is pushed away from the jaw tip"},
{"id": "40.3", "name": "Grasp the band", "segments": [[101, 10186], [101, 10201]],
"pre": ["between_jaws(tissue_band, #101)"], "effects": ["held(tissue_band, #101)"],
"success_check": "jaws closed with tissue between them"},
{"id": "40.4", "name": "Coagulate", "segments": [[101, 10225]],
"pre": ["held(tissue_band, #101)", "rod clear of the jaws"], "effects": ["energy_applied(tissue_band)"],
"success_check": "smoke and darkening at the jaw tip"},
],
"decisions": [
{"frame": 10051, "observation": "The open jaws are next to the band; the rod is low on the right.",
"assessment": "The band is not yet clearly between the jaws.",
"decision": "Hold the jaws open and make small adjustments.", "expected": "The band settles between the jaws.",
"outcome_seen": "Frames 10051-10185: the jaws stay open at the band with small movements."},
{"frame": 10126, "observation": "Tissue on the right lies against the jaw tip.",
"assessment": "It may be caught in the jaws or block the view.",
"decision": "Lift it away with the rod.", "expected": "The jaw tip and band are clear.",
"outcome_seen": "Frames 10126-10142: the rod lifts the tissue beside the jaws, then lowers again."},
{"frame": 10186, "observation": "The band lies between the open jaws.",
"assessment": "Ready to grasp.", "decision": "Close the jaws.", "expected": "The band is held.",
"outcome_seen": "Frames 10190-10200: the jaws close."},
{"frame": 10225, "observation": "The band is held; the rod has moved down and away from the tip.",
"assessment": "Energy can be applied without touching the rod.",
"decision": "Activate energy briefly.", "expected": "The grasped tissue coagulates.",
"outcome_seen": "Frames 10230-10249: smoke rises and the tissue at the tip darkens."},
]},
43: {
"goal": "Peel pale adherent material off a smooth pink surface",
"initial_state": ["held(pale_material, #102)", "visible(attachment_line)", "separated(pale_material, pink_surface, none)"],
"subtasks": [
{"id": "43.1", "name": "Put the material under tension", "segments": [[102, 10750]],
"pre": ["held(pale_material, #102)"], "effects": ["under_tension(pale_material)"],
"success_check": "strands between material and surface stretch"},
{"id": "43.2", "name": "Separate along the attachment", "segments": [[102, 10813], [101, 10785], [101, 10831]],
"pre": ["under_tension(pale_material)"], "effects": ["separated(pale_material, pink_surface, partial)"],
"success_check": "a sheet of material lifts off the surface"},
{"id": "43.3", "name": "Change the pulling direction", "segments": [[102, 10871]],
"pre": ["separated(pale_material, pink_surface, partial)"], "effects": ["under_tension(pale_material)"],
"success_check": "material pulled from a new angle"},
{"id": "43.4", "name": "Separate further", "segments": [[102, 10899], [101, 10901]],
"pre": ["under_tension(pale_material)"], "effects": ["separated(pale_material, pink_surface, partial)"],
"success_check": "more of the surface is uncovered"},
{"id": "43.5", "name": "Take hold again", "segments": [[102, 10940], [101, 10940]],
"pre": ["out_of_view(#102)"], "effects": ["held(pale_material, #102)"], "success_check": "jaws on the material"},
{"id": "43.6", "name": "Inspect", "segments": [["camera", 10975]],
"pre": ["out_of_view(#101)", "out_of_view(#102)"], "effects": [],
"success_check": "view held still on the peeled area"},
],
"decisions": [
{"frame": 10785, "observation": "The material is under tension; a line of attachment to the surface is visible.",
"assessment": "Traction alone tears unevenly; the attachment needs to be opened.",
"decision": "Push the rod tip into the attachment line.", "expected": "The material starts to come away along the line.",
"outcome_seen": "Frames 10800-10830: the rod tip is at the junction and the material starts to lift."},
{"frame": 10831, "observation": "A sheet of material is lifting while the grasper pulls left.",
"assessment": "The surface underneath moves with it.",
"decision": "Press the surface down with the rod (counter-traction).", "expected": "The material separates instead of dragging the surface.",
"outcome_seen": "Frames 10835-10850: a large sheet comes off to the left."},
{"frame": 10871, "observation": "The material is pulled as far left as it goes.",
"assessment": "Pulling further in the same direction gains nothing.",
"decision": "Bring the material back to the right to change the angle.", "expected": "A new part of the attachment comes under tension.",
"outcome_seen": "Frames 10875-10898: the grasper moves the material down and right."},
{"frame": 10975, "observation": "Both instruments have left the view.",
"assessment": "Time to see how much has come off.",
"decision": "Hold the camera still on the area.", "expected": "Residual material, if any, is visible.",
"outcome_seen": "Frames 10975-10999: a patch of pale material is still attached at the upper middle; removal is partial."},
{"frame": 10928, "observation": "The grasper leaves the view and comes back about 0.5 s later to take hold again.",
"assessment": "Whether the grip slipped cannot be seen.",
"decision": "Re-grasp the material.", "expected": "The material is held again.",
"outcome_seen": "Frames 10940-10954: the jaws are back on the material, then leave the view."},
]},
}
# ---- template-derived structure for the other clips
PREDICATES.update({"contact(I, X)": "the tip of instrument I touches X", "near(I, X)": "instrument I is next to X"})
RULES = { # verb: (preconditions, effects); I = acting instrument, X = target
"grasp": (["between_jaws(X, I)"], ["held(X, I)"]), "regrasp": (["held(X, I)"], ["held(X, I)"]),
"retract": (["held(X, I)"], ["under_tension(X)"]), "peel": (["held(X, I)", "under_tension(X)"], ["separated(X, surface, partial)"]),
"coagulate": (["held(X, I) or contact(I, X)"], ["energy_applied(X)"]), "press": ([], ["on(I, X)"]),
"release": (["held(X, I)"], ["not held(X, I)"]), "position": (["jaws_open(I)"], ["between_jaws(X, I)"]),
"open_jaws": ([], ["jaws_open(I)"]), "probe": ([], ["contact(I, X)"]),
"blunt_dissect": (["contact(I, X)"], ["separated(X, neighbour, partial)"]), "counter_traction": ([], ["under_tension(X)"]),
"transport": ([], ["near(I, X)"]), "approach": ([], ["near(I, X)"]), "enter": (["out_of_view(I)"], ["visible(I)"]),
"withdraw": ([], ["out_of_view(I)"]), "lift_off": (["on(I, X)"], ["visible(X)"]), "hold": ([], []), "sweep": ([], []),
"absent": ([], ["out_of_view(I)"])}
NAME = {"grasp": "Grasp", "retract": "Retract", "peel": "Peel", "coagulate": "Coagulate", "press": "Press on",
"probe": "Probe", "blunt_dissect": "Separate", "position": "Position the jaws at", "transport": "Move",
"release": "Release", "counter_traction": "Hold back", "lift_off": "Lift", "open_jaws": "Open the jaws at",
"hold": "Hold", "approach": "Approach", "regrasp": "Re-grasp"}
PRIORITY = ["coagulate", "peel", "blunt_dissect", "retract", "grasp", "press", "lift_off", "probe", "position",
"counter_traction", "release", "regrasp", "open_jaws", "transport", "approach", "hold"]
NAMES = {} # tissue id -> name for the clip being processed
def clean(t):
"""'attachment line between [202] and [201]' -> tag replaced by the tissue name; '[id]' after a name dropped."""
t = re.sub(r"(\S.*?)\s*\[(\d+)\]", lambda m: m.group(1) if m.group(1).strip().endswith(NAMES.get(m.group(2), "\0"))
else f"{m.group(1)} {NAMES.get(m.group(2), '')}", t)
return re.sub(r"\s+", " ", t).strip()
def fill(xs, inst, target):
tname = clean(target) if target not in ("-", "") else "the field"
return [x.replace("X", tname).replace("I", f"#{inst}") if x.startswith(("held", "between", "on(", "contact", "near", "visible(I"))
else x.replace("(X", f"({tname}").replace("I)", f"#{inst})").replace("(I", f"(#{inst}") for x in xs]
def template(c):
NAMES.clear()
NAMES.update(c["tissue_tracks"])
segs = c["segments"]
act = {}
for s in segs:
if s["verb"] not in ("absent", "withdraw", "enter", "sweep"):
act[s["track_id"]] = act.get(s["track_id"], 0) + s["end_frame"] - s["start_frame"] + 1
if not act:
return []
prim = max(act, key=act.get)
# a subtask is a run of the main instrument's segments on one target; it ends after a release,
# withdraw or absence, and a new one starts at an approach/entry once something has been done
runs, cur = [], None
MOVE, END = {"approach", "enter", "transport"}, {"release", "withdraw", "absent"}
for i, s in sorted(((i, s) for i, s in enumerate(segs) if s["track_id"] == prim), key=lambda x: x[1]["start_frame"]):
key = clean(s["target"]) if s["target"] not in ("-", "") else None
acted = cur and any(segs[j]["verb"] not in MOVE | END | {"sweep", "hold"} for j in cur["idx"])
same = cur and not cur["closed"] and (key is None or cur["key"] in (None, key)) and not (s["verb"] in MOVE and acted)
if same:
cur["idx"].append(i)
cur["key"] = cur["key"] or key
else:
cur = {"key": key, "idx": [i], "closed": False}
runs.append(cur)
if s["verb"] in END:
cur["closed"] = True
subs = []
for k, r in enumerate(runs):
ss = [segs[i] for i in r["idx"]]
if all(s["verb"] in ("absent", "withdraw", "enter", "sweep") for s in ss):
continue
main = min((s["verb"] for s in ss if s["verb"] in PRIORITY), key=PRIORITY.index, default="hold")
tgt = next((s["target"] for s in ss if s["target"] not in ("-", "")), "-")
f0, f1 = ss[0]["start_frame"], ss[-1]["end_frame"]
pre = fill(RULES[ss[0]["verb"]][0], prim, tgt)
eff = []
for s in ss:
for e in fill(RULES[s["verb"]][1], prim, s["target"] if s["target"] not in ("-", "") else tgt):
if e not in eff:
eff.append(e)
lasting = [e for e in eff if not e.startswith(("near(", "jaws_open(", "out_of_view(", "visible(#"))]
eff = lasting or eff # keep passing states only when nothing lasting happened
assist = [i for i, s in enumerate(segs) if s["track_id"] != prim and s["verb"] not in ("absent",)
and s["start_frame"] <= f1 and s["end_frame"] >= f0]
subs.append({"id": f"{c['clip_id']}.{len(subs) + 1}", "name": f"{NAME.get(main, main)} {clean(tgt) if tgt != '-' else ''}".strip(),
"primary_instrument": prim, "segment_index": r["idx"], "assisting_segment_index": assist,
"frames": [f0, f1], "pre": pre, "effects": eff,
"success_check": "; ".join(eff) if eff else "position maintained", "derived": "template"})
return subs
doc = {"description": "Task hierarchy, symbolic state and decision points for every clip. Clips 5, 40 and 43: "
"subtasks written by hand. Other clips: subtasks derived from the action segments of the clip's "
"main instrument with fixed verb rules (RULES), decision points written by hand from the video. "
"Observations and outcomes describe what is visible; assessments and decisions are a plausible "
"rationale, not the operator's recorded intent. AI draft, reviewed and approved by the contributing physician on 2026-11-17.",
"predicates": PREDICATES, "verb_rules": {k: {"pre": v[0], "effects": v[1]} for k, v in RULES.items()}, "clips": []}
for c in acts["clips"]:
if c["clip_id"] in T:
t = dict(T[c["clip_id"]])
segs = {(s["track_id"], s["start_frame"]): i for i, s in enumerate(c["segments"])}
for st in t["subtasks"]:
st["segment_index"] = [segs.get(tuple(k)) for k in st["segments"] if k[0] != "camera"]
assert None not in st["segment_index"], (c["clip_id"], st["id"])
st["frames"] = [min(k[1] for k in st["segments"]),
max(c["segments"][i]["end_frame"] for i in st["segment_index"]) if st["segment_index"] else c["end_frame"]]
st["derived"] = "hand"
doc["clips"].append({"clip_id": c["clip_id"], **t})
else:
doc["clips"].append({"clip_id": c["clip_id"], "goal": c["visible_goal"], "initial_state": [],
"subtasks": template(c), "decisions": c["decisions"]})
json.dump(doc, open(pack / "layer5_actions" / "task_graph.json", "w"), indent=1)
print("clips", len(doc["clips"]), "subtasks", sum(len(c["subtasks"]) for c in doc["clips"]),
"decisions", sum(len(c["decisions"]) for c in doc["clips"])) |