File size: 11,944 Bytes
3ae204c
1fc8465
 
 
3ae204c
 
 
 
 
 
 
1fc8465
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ae204c
 
1fc8465
3ae204c
1fc8465
3ae204c
 
 
 
b91b0f5
1fc8465
3ae204c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fc8465
3ae204c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fc8465
 
 
 
 
 
 
 
 
3ae204c
1fc8465
 
 
3ae204c
1fc8465
 
 
 
 
 
 
 
 
 
 
 
 
 
944c1f9
 
 
 
 
1fc8465
 
 
944c1f9
1fc8465
 
 
944c1f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fc8465
944c1f9
 
 
1fc8465
 
 
 
 
 
 
 
 
3ae204c
1fc8465
 
 
 
 
3ae204c
1fc8465
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Action-level annotation of every 10 s clip, with per-frame instrument state.

Usage: python 12_actions.py <pack_dir>

Labels live in layer5_actions/labels/clip_XX.json, one file per clip, written by an
AI model from contact sheets with the dense masks drawn on: every 5 frames (0.2 s)
for clips 5, 40 and 43, every 10 frames (0.4 s) for the others, so boundaries are
accurate to about +-5 / +-10 frames. Nothing here has been reviewed by a surgeon.
Targets are named by appearance, not anatomy, because the procedure is not known.
The script validates every file (verbs, jaw states, frame ranges, track ids, no
overlapping segments on one track) and stops on any problem.

Each segment: one instrument track (track ids from dense_tracks/), one verb from
VERBS, the target, jaw state, whether energy use is visible, and an imperative
instruction of the kind a supervising surgeon would say. Tissue track ids refer
to layer5_actions/target_tissue/ (SAM 3.1 tracks from 11_sam31_target_tissue.py).

Writes layer5_actions/actions.json, per_frame_state.csv and timeline_clip_XX.png.
"""
import csv
import json
import sys
from pathlib import Path

import cv2
import numpy as np

pack = Path(sys.argv[1])
out = pack / "layer5_actions"
out.mkdir(exist_ok=True)

VERBS = {
    "transport": "carry an object (gauze, tissue) to another place while holding it",
    "regrasp": "open the jaws and close them again on a different part of the held object",
    "press": "push an object or the tip against tissue and keep pressure",
    "lift_off": "lift a pressed object off the tissue to look underneath",
    "release": "open the jaws and let go of the held object",
    "withdraw": "move the instrument out of view",
    "enter": "move the instrument into view",
    "approach": "move the tip towards a target without acting on it",
    "open_jaws": "open the jaws near the target",
    "position": "place open jaws around the target with small adjustments",
    "grasp": "close the jaws on tissue",
    "hold": "keep the instrument or held tissue still",
    "coagulate": "energy applied at the tip: tissue darkens, smoke or char appears",
    "retract": "pull held tissue away to put it under tension",
    "peel": "pull held material so it separates from the surface underneath",
    "counter_traction": "push or hold tissue in the opposite direction to the other instrument",
    "blunt_dissect": "push or sweep the tip along a tissue plane to separate it",
    "probe": "touch a spot with the tip",
    "sweep": "move the shaft or tip across the view (often near the lens)",
    "absent": "instrument not in view",
}

CAMERA_VERBS = {"inspect": "camera held still on a region to check it",
                "move_view": "camera moves to a different part of the field"}

# ---- load the per-clip label files (one JSON per 10 s clip, written by hand from contact sheets)
FIELDS = ["track_id", "start_frame", "end_frame", "verb", "target", "jaw_state", "energy_visible", "instruction"]
JAW = {"open", "closed", "open->closed", "closed->open", "unknown", "n/a"}
problems = []
doc = {"description": "Action segments for every 10 s clip of the video. AI draft, written from contact sheets "
                      "sampled every 0.2 s (clips 5, 40, 43) or 0.4 s (the other clips), so boundaries are about "
                      "+-5 or +-10 frames; targets named by appearance; reviewed and approved by the contributing physician on 2026-11-17.",
       "frame_index": "frames of video/laparoscopic_sample_001_intracorporeal.mp4 (25 fps)",
       "verbs": VERBS, "camera_verbs": CAMERA_VERBS, "clips": []}
for lp in sorted((out / "labels").glob("clip_*.json")):
    lab = json.load(open(lp))
    cid = lab["clip_id"]
    tm = json.load(open(pack / "dense_tracks" / "tracks" / f"clip_{cid:02d}.json"))
    s0, s1 = tm["start_frame"], tm["start_frame"] + tm["num_frames"] - 1
    segs = []
    for row in lab["segments"]:
        s = dict(zip(FIELDS, row))
        s["energy_visible"] = bool(s["energy_visible"])
        if s["verb"] not in VERBS:
            problems.append(f"clip {cid}: unknown verb {s['verb']}")
        if s["jaw_state"] not in JAW:
            problems.append(f"clip {cid}: unknown jaw state {s['jaw_state']}")
        if not (s0 <= s["start_frame"] <= s["end_frame"] <= s1):
            problems.append(f"clip {cid}: segment out of range {row[:4]}")
        if str(s["track_id"]) not in lab["objects"]:
            problems.append(f"clip {cid}: track {s['track_id']} not in objects")
        s["instrument"] = lab["objects"][str(s["track_id"])]
        s["lane"] = lab.get("merge_tracks", {}).get(str(s["track_id"]), s["track_id"])   # same instrument, other track id
        s["duration_s"] = round((s["end_frame"] - s["start_frame"] + 1) / 25, 2)
        segs.append(s)
    by_t = {}
    for s in segs:
        by_t.setdefault(s["lane"], []).append(s)
    for t, ss in by_t.items():
        ss = sorted(ss, key=lambda s: s["start_frame"])
        for a, b in zip(ss, ss[1:]):
            if b["start_frame"] <= a["end_frame"]:
                problems.append(f"clip {cid}: overlap on track {t} at {b['start_frame']}")
    cam = [dict(zip(["start_frame", "end_frame", "verb", "target", "instruction"], x)) for x in lab["camera_segments"]]
    for x in cam:
        if x["verb"] not in CAMERA_VERBS:
            problems.append(f"clip {cid}: unknown camera verb {x['verb']}")
    doc["clips"].append({"clip_id": cid, "start_frame": s0, "end_frame": s1, "visible_goal": lab["visible_goal"],
                         "label_sampling_s": lab.get("label_sampling_s", 0.4), "objects": lab["objects"],
                         "tissue_tracks": lab["tissue_targets"], "segments": segs, "camera_segments": cam,
                         "decisions": lab.get("decisions", [])})
if problems:
    print("\n".join(problems))
    sys.exit(1)
json.dump(doc, open(out / "actions.json", "w"), indent=1)

# per-frame state: active verb per instrument + 2D kinematics from layer4
kin = {}
with open(pack / "layer4_tool_kinematics" / "tool_tips.csv") as fh:
    for r in csv.DictReader(fh):
        kin[(int(r["frame"]), int(r["track_id"]))] = r
rows = []
for c in doc["clips"]:
    tracks = sorted({s["lane"] for s in c["segments"]})
    for f in range(c["start_frame"], c["end_frame"] + 1):
        for t in tracks:
            act = [s for s in c["segments"] if s["start_frame"] <= f <= s["end_frame"] and
                   s["lane"] == t]
            k = kin.get((f, t)) or (kin.get((f, 3)) if t == 101 and c["clip_id"] == 5 else None)
            rows.append({"frame": f, "clip_id": c["clip_id"], "track_id": t,
                         "instrument": c["objects"][str(t)].split(" (")[0],
                         "verbs": "+".join(s["verb"] for s in act), "target": act[0]["target"] if act else "",
                         "jaw_state": act[0]["jaw_state"] if act else "",
                         "energy_visible": int(any(s["energy_visible"] for s in act)),
                         "in_mask": int(k is not None),
                         "tip_x": k["tip_x_smooth"] if k else "", "tip_y": k["tip_y_smooth"] if k else "",
                         "shaft_angle_deg": k["shaft_angle_deg"] if k else "", "speed_px_s": k["speed_px_s"] if k else ""})
with open(out / "per_frame_state.csv", "w", newline="") as fh:
    w = csv.DictWriter(fh, list(rows[0]))
    w.writeheader()
    w.writerows(rows)

# target-tissue reliability. A frame's tissue mask is flagged when it
#   - is more than twice the object's median area in the clip (spread into neighbouring tissue),
#   - covers more than 40 % of the image, or
#   - has at least half of its pixels on instrument masks (the track drifted onto an instrument).
# Flagged frames are kept but marked; an object flagged in more than half of its frames is "rejected".
qual = {}
for p in sorted((out / "target_tissue" / "tracks").glob("clip_*.json")):
    tm = json.load(open(p))
    cid = tm["clip_id"]
    for oid, o in tm["objects"].items():
        areas = {int(f): v["area"] for f, v in o["frames"].items()}
        med = float(np.median(list(areas.values())))
        bad, why = [], {"area_2x_median": 0, "over_40pct_of_image": 0, "on_instrument": 0}
        for f, a in sorted(areas.items()):
            r = []
            if a > 2 * med:
                r.append("area_2x_median")
            if a > 0.4 * 720 * 576:
                r.append("over_40pct_of_image")
            tis = cv2.imread(str(out / "target_tissue" / "masks" / f"clip_{cid:02d}" / f"{f:05d}.png"), 0) == int(oid)
            inst = cv2.imread(str(pack / "dense_tracks" / "masks" / f"clip_{cid:02d}" / f"{f:05d}.png"), 0) > 0
            if tis.sum() and (tis & inst).sum() / tis.sum() >= 0.5:
                r.append("on_instrument")
            if r:
                bad.append(f)
                for x in r:
                    why[x] += 1
        qual[f"clip_{cid:02d}/{oid}"] = {"name": o["name"], "frames_with_mask": len(areas), "median_area_px": int(med),
                                         "unreliable_frames": bad, "reasons": why,
                                         "status": "rejected" if len(bad) > 0.5 * len(areas) else "ok"}
json.dump({"rules": ["area > 2 x median area of the object in the clip", "area > 40 % of the image",
                     ">= 50 % of the mask on instrument masks"],
           "object_status": "rejected when more than half of its frames are flagged", "objects": qual},
          open(out / "target_tissue" / "quality.json", "w"), indent=1)
ok = [v for v in qual.values() if v["status"] == "ok"]
print("tissue objects", len(qual), "ok", len(ok), "rejected", len(qual) - len(ok),
      "reliable frame-masks in ok objects", sum(v["frames_with_mask"] - len(v["unreliable_frames"]) for v in ok))

# timeline charts
PAL = {}
cmap = [(66, 135, 245), (245, 130, 48), (60, 180, 75), (230, 25, 75), (145, 30, 180), (70, 240, 240),
        (240, 50, 230), (210, 245, 60), (0, 128, 128), (170, 110, 40), (128, 0, 0), (0, 0, 128), (128, 128, 0),
        (255, 215, 180), (170, 255, 195), (128, 128, 128), (255, 225, 25), (0, 130, 200), (250, 190, 212), (60, 60, 60)]
for i, v in enumerate(VERBS):
    PAL[v] = cmap[i % len(cmap)][::-1]
for c in doc["clips"]:
    tracks = sorted({s["lane"] for s in c["segments"]})
    Wd, lane, x0 = 1200, 60, 230
    img = np.full((70 + lane * (len(tracks) + 1) + 40, Wd, 3), 255, np.uint8)
    n = c["end_frame"] - c["start_frame"] + 1
    X = lambda f: int(x0 + (f - c["start_frame"]) / n * (Wd - x0 - 20))
    cv2.putText(img, f"clip {c['clip_id']}: {c['visible_goal']}", (10, 28), 0, 0.6, (0, 0, 0), 1, cv2.LINE_AA)
    lanes = [(str(t), [s for s in c["segments"] if s["lane"] == t])
             for t in tracks] + [("camera", c["camera_segments"])]
    for i, (name, segs) in enumerate(lanes):
        y = 50 + i * lane
        label = name if name == "camera" else f"{name} {c['objects'][name].split(' (')[0]}"
        cv2.putText(img, label[:28], (10, y + 32), 0, 0.5, (0, 0, 0), 1, cv2.LINE_AA)
        for s in segs:
            a, b = X(s["start_frame"]), X(s["end_frame"] + 1)
            col = PAL.get(s["verb"], (200, 200, 200))
            cv2.rectangle(img, (a, y + 8), (b, y + lane - 8), col, -1)
            cv2.rectangle(img, (a, y + 8), (b, y + lane - 8), (255, 255, 255), 1)
            if b - a > 40:
                ink = (0, 0, 0) if 0.114 * col[0] + 0.587 * col[1] + 0.299 * col[2] > 150 else (255, 255, 255)
                cv2.putText(img, s["verb"], (a + 4, y + 34), 0, 0.42, ink, 1, cv2.LINE_AA)
    yb = 50 + len(lanes) * lane + 5
    for f in range(c["start_frame"], c["end_frame"] + 2, 25):
        cv2.line(img, (X(f), yb), (X(f), yb + 6), (0, 0, 0), 1)
        cv2.putText(img, f"{f / 25:.0f}s", (X(f) - 10, yb + 22), 0, 0.4, (0, 0, 0), 1, cv2.LINE_AA)
    cv2.imwrite(str(out / f"timeline_clip_{c['clip_id']:02d}.png"), img)
print("segments", sum(len(c["segments"]) for c in doc["clips"]), "per-frame rows", len(rows))