File size: 15,856 Bytes
580f7b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b91b0f5
 
580f7b0
 
 
 
 
 
3ae204c
580f7b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ae204c
580f7b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b91b0f5
580f7b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ae204c
580f7b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b91b0f5
580f7b0
 
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"""Presentation-quality showcase videos for the action-annotated clips (1280x720, H.264).

Usage: python 14_showcase.py <pack_dir> [preview_frame]    (needs ffmpeg; macOS system fonts)

Same data as 13_action_demo.py, laid out for viewers rather than for checking:
video on the left (1.25x), side panel with each instrument's current action,
jaw / energy state and instruction, tissue legend, and an action timeline with a
playhead. Masks are feathered and translucent, tip trails fade over 0.8 s.
Writes layer5_actions/showcase/clip_XX.mp4, poster_clip_XX.jpg and showreel.mp4
(intro card, the three clips with title cards, closing card).
With preview_frame, renders only that frame to showcase/preview.jpg.
"""
import csv
import json
import subprocess
import sys
from pathlib import Path

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

pack = Path(sys.argv[1])
PREVIEW = int(sys.argv[2]) if len(sys.argv) > 2 else None
L5 = pack / "layer5_actions"
OUT = L5 / "showcase"
OUT.mkdir(exist_ok=True)
W, H, VW, VH, S = 1280, 720, 900, 720, 1.25          # canvas, video area, scale from 720x576
FPS, TRAIL = 25, 20

SF, MONO = "/System/Library/Fonts/SFNS.ttf", "/System/Library/Fonts/SFNSMono.ttf"


def font(size, weight="Regular", path=SF):
    f = ImageFont.truetype(path, size)
    f.set_variation_by_name(weight)
    return f


F = {k: font(*v) for k, v in {
    "eyebrow": (11, "Semibold"), "title": (22, "Bold"), "goal": (15, "Regular"), "inst": (13, "Semibold"),
    "verb": (26, "Heavy"), "chip": (11, "Semibold"), "quote": (14, "Regular"), "small": (11, "Regular"),
    "tag": (12, "Semibold"), "big": (44, "Bold"), "card": (19, "Regular"), "cardsm": (15, "Regular")}.items()}
F["mono"] = font(12, "Medium", MONO)

BG, PANEL, LINE, TXT, MUTED, DIM = (12, 14, 19), (19, 22, 29), (40, 45, 56), (236, 239, 244), (150, 158, 172), (90, 97, 110)
INST = {"dark_rod": ((245, 166, 35), "Dark rod"), "white_insulated_jawed": ((79, 195, 247), "Insulated jaws"),
        "fenestrated_grasper": ((102, 214, 120), "Fenestrated grasper"), "jawed instrument": ((79, 195, 247), "Jawed grasper"),
        "gauze": ((224, 64, 251), "Gauze"), "instrument_text_detected": ((170, 180, 200), "Instrument")}
TISSUE = [(255, 122, 107), (46, 196, 182)]
FAMILY = {"grasp": "hold", "hold": "hold", "regrasp": "hold", "open_jaws": "hold", "position": "hold", "release": "hold",
          "retract": "traction", "peel": "traction", "counter_traction": "traction", "lift_off": "traction",
          "blunt_dissect": "dissect", "coagulate": "dissect", "press": "contact", "probe": "contact",
          "transport": "move", "approach": "move", "enter": "move", "withdraw": "move", "sweep": "move",
          "absent": "absent", "inspect": "move"}
FAM_COL = {"hold": (91, 141, 239), "traction": (157, 120, 245), "dissect": (239, 108, 87), "contact": (60, 196, 138),
           "move": (110, 119, 138), "absent": (34, 38, 48)}
FAM_NAME = {"hold": "Grasp / hold", "traction": "Traction", "dissect": "Dissect / energy", "contact": "Contact",
            "move": "Move"}


def inst_key(desc):
    return desc.split(" (")[0]


def rr(d, box, r, fill=None, outline=None, width=1):
    d.rounded_rectangle(box, r, fill=fill, outline=outline, width=width)


def wrap(d, text, f, width):
    lines, cur = [], ""
    for w in text.split():
        t = (cur + " " + w).strip()
        if d.textlength(t, font=f) <= width:
            cur = t
        else:
            lines.append(cur)
            cur = w
    return lines + [cur] if cur else lines


def chip(d, x, y, text, fg, bg):
    w = d.textlength(text, font=F["chip"]) + 16
    rr(d, (x, y, x + w, y + 20), 10, fill=bg)
    d.text((x + 8, y + 3), text, font=F["chip"], fill=fg)
    return x + w + 6


def feather(mask, sigma=1.6):
    m = cv2.resize(mask.astype(np.float32), (VW, VH), interpolation=cv2.INTER_LINEAR)
    return cv2.GaussianBlur(m, (0, 0), sigma)


def blend(img, alpha, col, a):
    k = (alpha * a)[..., None]
    img[:] = img * (1 - k) + np.array(col, np.float32) * k


def outline(img, mask, col, a=0.95, width=2):
    m = (cv2.resize(mask.astype(np.uint8), (VW, VH), interpolation=cv2.INTER_LINEAR) > 0).astype(np.uint8)
    edge = cv2.morphologyEx(m, cv2.MORPH_GRADIENT, np.ones((width + 1, width + 1), np.uint8)).astype(np.float32)
    blend(img, cv2.GaussianBlur(edge, (0, 0), 0.8), col, a)


tips = {}
with open(pack / "layer4_tool_kinematics" / "tool_tips.csv") as fh:
    for r in csv.DictReader(fh):
        if r["tip_x_smooth"]:
            tips[(int(r["frame"]), int(r["track_id"]))] = (float(r["tip_x_smooth"]) * S, float(r["tip_y_smooth"]) * S)
acts = json.load(open(L5 / "actions.json"))
SHOWCASE = (5, 40, 43)                     # the clips rendered as videos
acts["clips"] = [c for c in acts["clips"] if c["clip_id"] in SHOWCASE]
unreliable = {k: set(v["unreliable_frames"]) for k, v in json.load(open(L5 / "target_tissue" / "quality.json"))["objects"].items()}
cap = cv2.VideoCapture(str(pack / "video" / "laparoscopic_sample_001_intracorporeal.mp4"))


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 render(c, f, dmeta, tmeta, tracks):
    cid = c["clip_id"]
    cap.set(cv2.CAP_PROP_POS_FRAMES, f)
    _, bgr = cap.read()
    img = cv2.resize(bgr, (VW, VH), interpolation=cv2.INTER_CUBIC)[..., ::-1].astype(np.float32)
    img *= 0.92                                                   # slight dim so overlays read
    tis = cv2.imread(str(L5 / "target_tissue" / "masks" / f"clip_{cid:02d}" / f"{f:05d}.png"), 0)
    labels = []
    for k, (oid, o) in enumerate(tmeta["objects"].items()):
        if f in unreliable[f"clip_{cid:02d}/{oid}"]:
            continue
        m = tis == int(oid)
        if m.sum() < 150:
            continue
        blend(img, feather(m, 2.5), TISSUE[k], 0.30)
        outline(img, m, TISSUE[k], 0.55, 1)
        dist = cv2.distanceTransform(m.astype(np.uint8), cv2.DIST_L2, 5)
        y, x = np.unravel_index(np.argmax(dist), dist.shape)
        labels.append((x * S, y * S, o["name"].replace("_", " "), TISSUE[k]))
    inst = cv2.imread(str(pack / "dense_tracks" / "masks" / f"clip_{cid:02d}" / f"{f:05d}.png"), 0)
    for tid in np.unique(inst)[1:]:
        cat = dmeta["tracks"][str(tid)]["category"]
        col = INST.get(cat, INST["instrument_text_detected"])[0]
        m = inst == tid
        blend(img, feather(m), col, 0.08 if cat == "gauze" else 0.12)
        outline(img, m, col, 0.6 if cat == "gauze" else 0.95, 2)
    # fading tip trails
    for t in tracks:
        col = INST[inst_key(c["objects"][str(t)])][0]
        alpha = np.zeros((VH, VW), np.float32)
        for g in range(f - TRAIL + 1, f + 1):
            a, b = tips.get((g - 1, t)), tips.get((g, t))
            if a and b and np.hypot(a[0] - b[0], a[1] - b[1]) <= 50:
                w = (g - (f - TRAIL)) / TRAIL
                cv2.line(alpha, tuple(map(int, a)), tuple(map(int, b)), float(w), 3, cv2.LINE_AA)
        if alpha.any():
            blend(img, np.clip(cv2.GaussianBlur(alpha, (0, 0), 4) * 1.2, 0, 1), col, 0.45)   # glow
            blend(img, alpha, col, 1.0)

    canvas = Image.new("RGB", (W, H), BG)
    canvas.paste(Image.fromarray(img.astype(np.uint8)), (0, 0))
    d = ImageDraw.Draw(canvas, "RGBA")
    for x, y, name, col in labels:                                # tissue tags
        tw = d.textlength(name, font=F["tag"])
        rr(d, (x - tw / 2 - 9, y - 11, x + tw / 2 + 9, y + 11), 11, fill=(10, 12, 16, 170), outline=col + (200,))
        d.text((x - tw / 2, y - 8), name, font=F["tag"], fill=TXT)
    for t in tracks:                                              # tip markers + tags
        if (f, t) not in tips:
            continue
        x, y = tips[(f, t)]
        col = INST[inst_key(c["objects"][str(t)])][0]
        d.ellipse((x - 9, y - 9, x + 9, y + 9), outline=col + (120,), width=3)
        d.ellipse((x - 4, y - 4, x + 4, y + 4), fill=(255, 255, 255), outline=col, width=2)
        act = active(c, t, f)
        if act and act[0]["verb"] != "absent":
            txt = act[0]["verb"].replace("_", " ").upper()
            tw = d.textlength(txt, font=F["tag"])
            tx, ty = min(x + 14, VW - tw - 24), max(y - 30, 8)
            rr(d, (tx, ty, tx + tw + 18, ty + 22), 11, fill=col + (230,))
            d.text((tx + 9, ty + 3), txt, font=F["tag"], fill=(12, 14, 19))
    rr(d, (14, 14, 210, 38), 12, fill=(10, 12, 16, 170))           # HUD
    d.text((26, 19), f"FRAME {f:05d}   {int(f / FPS // 60)}:{f / FPS % 60:05.2f}", font=F["mono"], fill=TXT)

    # side panel
    d.rectangle((VW, 0, W, H), fill=PANEL)
    d.line((VW, 0, VW, H), fill=LINE)
    x0, x1 = VW + 24, W - 24
    d.text((x0, 22), "SURGICAL ACTION DATA  ·  SAMPLE", font=F["eyebrow"], fill=MUTED)
    t0 = c["start_frame"] / FPS
    d.text((x0, 42), f"Clip {cid}  ·  {int(t0 // 60)}:{int(t0 % 60):02d}–{int((t0 + 10) // 60)}:{int((t0 + 10) % 60):02d}",
           font=F["title"], fill=TXT)
    y = 76
    for ln in wrap(d, c["visible_goal"], F["goal"], x1 - x0)[:2]:
        d.text((x0, y), ln, font=F["goal"], fill=MUTED)
        y += 20
    y += 10
    for t in tracks:                                              # instrument cards
        col, name = INST[inst_key(c["objects"][str(t)])]
        act = active(c, t, f)
        rr(d, (x0 - 8, y, x1 + 8, y + 150), 12, fill=(26, 30, 39), outline=LINE)
        d.rectangle((x0 - 8, y + 14, x0 - 5, y + 136), fill=col)
        d.text((x0 + 6, y + 12), f"{name.upper()}  #{t}", font=F["inst"], fill=col)
        if not act or act[0]["verb"] == "absent":
            d.text((x0 + 6, y + 34), "OUT OF VIEW", font=F["verb"], fill=DIM)
        else:
            s = act[0]
            d.text((x0 + 6, y + 32), s["verb"].replace("_", " ").upper(), font=F["verb"], fill=TXT)
            cx = x0 + 6
            if s["jaw_state"] not in ("n/a", "unknown"):
                cx = chip(d, cx, y + 68, "JAWS " + s["jaw_state"].upper().replace("->", " → "), TXT, (48, 54, 68))
            if s["energy_visible"]:
                cx = chip(d, cx, y + 68, "ENERGY ON", (20, 10, 8), (255, 138, 76))
            fam = FAMILY[s["verb"]]
            chip(d, cx, y + 68, FAM_NAME[fam].upper(), FAM_COL[fam], (36, 40, 52))
            yy = y + 96
            for ln in wrap(d, f"“{s['instruction']}”", F["quote"], x1 - x0 - 12)[:2]:
                d.text((x0 + 6, yy), ln, font=F["quote"], fill=(205, 210, 220))
                yy += 19
        y += 162
    # tissue legend
    d.text((x0, y), "TARGET TISSUE", font=F["eyebrow"], fill=MUTED)
    y += 18
    for k, o in enumerate(tmeta["objects"].values()):
        d.ellipse((x0, y + 4, x0 + 10, y + 14), fill=TISSUE[k])
        d.text((x0 + 18, y + 1), o["name"].replace("_", " "), font=F["small"], fill=TXT)
        y += 18
    # timeline
    ty0 = H - 128
    d.text((x0, ty0), "ACTION TIMELINE", font=F["eyebrow"], fill=MUTED)
    n = c["end_frame"] - c["start_frame"] + 1
    X = lambda g: x0 + (g - c["start_frame"]) / n * (x1 - x0)
    lanes = [(t, [s for s in c["segments"] if s["lane"] == t]) for t in tracks]
    for i, (t, segs) in enumerate(lanes):
        ly = ty0 + 20 + i * 22
        col = INST[inst_key(c["objects"][str(t)])][0]
        rr(d, (x0, ly, x1, ly + 14), 4, fill=(30, 34, 44))
        for s in segs:
            fc = FAM_COL[FAMILY[s["verb"]]]
            on = s["start_frame"] <= f <= s["end_frame"]
            rr(d, (X(s["start_frame"]) + 1, ly + 1, X(s["end_frame"] + 1) - 1, ly + 13), 3,
               fill=fc + ((255,) if on else (150,)))
        d.ellipse((x0 - 12, ly + 3, x0 - 4, ly + 11), fill=col)
    px = X(f)
    d.line((px, ty0 + 16, px, ty0 + 20 + len(lanes) * 22), fill=(255, 255, 255), width=2)
    ly = ty0 + 24 + len(lanes) * 22
    lx = x0
    for fam in ("hold", "traction", "dissect", "contact", "move"):
        d.rounded_rectangle((lx, ly + 3, lx + 8, ly + 11), 2, fill=FAM_COL[fam])
        d.text((lx + 12, ly), FAM_NAME[fam], font=F["small"], fill=MUTED)
        lx += d.textlength(FAM_NAME[fam], font=F["small"]) + 24
    d.text((x0, H - 24), "Physician-reviewed labels · SAM 3.1 masks", font=F["small"], fill=DIM)
    return canvas


def card(lines, sub=None):
    im = Image.new("RGB", (W, H), BG)
    d = ImageDraw.Draw(im)
    y = H / 2 - 30 * len(lines) - (40 if sub else 0)
    for i, (txt, f, col) in enumerate(lines):
        tw = d.textlength(txt, font=F[f])
        d.text(((W - tw) / 2, y), txt, font=F[f], fill=col)
        y += {"big": 64, "card": 34, "cardsm": 26, "eyebrow": 30}[f]
    if sub:
        y += 20
        for ln in sub:
            tw = d.textlength(ln, font=F["cardsm"])
            d.text(((W - tw) / 2, y), ln, font=F["cardsm"], fill=MUTED)
            y += 26
    return im


def write(path, frames_iter):
    ff = subprocess.Popen(["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{W}x{H}",
                           "-r", str(FPS), "-i", "-", "-c:v", "libx264", "-preset", "slow", "-crf", "20",
                           "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(path)], stdin=subprocess.PIPE)
    for im in frames_iter:
        ff.stdin.write(np.asarray(im).tobytes())
    ff.stdin.close()
    ff.wait()


def fade(im, k):
    return Image.fromarray((np.asarray(im).astype(np.float32) * k + np.array(BG) * (1 - k)).astype(np.uint8))


def hold(im, sec, fade_in=True, fade_out=True):
    n = int(sec * FPS)
    for i in range(n):
        k = min(1, (i + 1) / 8 if fade_in else 1, (n - i) / 8 if fade_out else 1)
        yield fade(im, k)


clips = []
for c in acts["clips"]:
    cid = c["clip_id"]
    dmeta = json.load(open(pack / "dense_tracks" / "tracks" / f"clip_{cid:02d}.json"))
    tmeta = json.load(open(L5 / "target_tissue" / "tracks" / f"clip_{cid:02d}.json"))
    tracks = sorted({s["lane"] for s in c["segments"]})
    clips.append((c, dmeta, tmeta, tracks))
    if PREVIEW is not None and c["start_frame"] <= PREVIEW <= c["end_frame"]:
        render(c, PREVIEW, dmeta, tmeta, tracks).save(OUT / "preview.jpg", quality=92)
        sys.exit(0)

for c, dmeta, tmeta, tracks in clips:
    cid = c["clip_id"]
    frames = (render(c, f, dmeta, tmeta, tracks) for f in range(c["start_frame"], c["end_frame"] + 1))
    write(OUT / f"clip_{cid:02d}.mp4", frames)
    mid = (c["start_frame"] + c["end_frame"]) // 2
    poster = {5: 1300, 40: 10235, 43: 10840}.get(cid, mid)
    render(c, poster, dmeta, tmeta, tracks).save(OUT / f"poster_clip_{cid:02d}.jpg", quality=92)
    print("clip", cid, "done", flush=True)


def reel():
    intro = card([("LAPAROSCOPIC VIDEO  →  ACTION-LEVEL TRAINING DATA", "eyebrow", MUTED),
                  ("Surgical action data sample", "big", TXT)],
                 ["Instrument & tissue masks · tool-tip kinematics · action segments · surgeon-style instructions",
                  "One recording, three 10-second clips"])
    yield from hold(intro, 3.0)
    for c, dmeta, tmeta, tracks in clips:
        t = card([(f"CLIP {c['clip_id']}", "eyebrow", MUTED), (c["visible_goal"], "card", TXT)])
        yield from hold(t, 1.6)
        cap_frames = [render(c, f, dmeta, tmeta, tracks) for f in range(c["start_frame"], c["end_frame"] + 1)]
        for i, im in enumerate(cap_frames):
            k = min(1, (i + 1) / 8, (len(cap_frames) - i) / 8)
            yield fade(im, k) if k < 1 else im
    outro = card([("WHAT EACH CLIP CARRIES", "eyebrow", MUTED), ("Per frame: masks, tool tips, active action", "card", TXT),
                  ("Per segment: verb, target, jaw state, energy, instruction", "card", TXT)],
                 ["Physician-reviewed labels · hand-held laparoscopy",
                  "huggingface.co/datasets/hkust-aaron/laparoscopic-robotic-vision-sample"])
    yield from hold(outro, 4.0)


write(OUT / "showreel.mp4", reel())
print("showreel done")