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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Visualize PE-Video samples with:
- colored instance masks (per object id)
- centroid label box (object name)
- relationship text panel appended under the video

Assumptions:
- training JSON entries look like:
    {
      "video": ".../xxx.mp4",
      "mask_json": "..._rle.json",
      "obj_list": [0,1,...],
      "has_relationships": True/False,
      "conversations": [
          {"from":"human", ...},
          {"from":"gpt", "value": "<json string of objects/relationships>"}
      ],
      "mode": "mode_6"
    }

- mask_json file format:
    masks = List[List[rle]]
    masks[frame_idx][object_idx] = {"size":[H,W], "counts": ...}

- relationships format inside gpt JSON:
    "relationships": [
        [sub_id, "rel", obj_id, [[t0,t1],[t2,t3], ...]],
        ...
    ]
  where each interval [t0,t1] is inclusive frame indices (we treat as inclusive).
"""

import os
import re
import json
import math
import random
import argparse
from typing import Any, Dict, List, Tuple, Optional

import cv2
import numpy as np

import shutil


try:
    from pycocotools import mask as mask_utils
except Exception as e:
    raise RuntimeError(
        "pycocotools is required. Install via: pip install pycocotools"
    ) from e


# -----------------------------
# Utilities
# -----------------------------
def draw_top_left_hud(frame_bgr: np.ndarray, text: str):
    x, y = 10, 10
    font = cv2.FONT_HERSHEY_SIMPLEX
    font_scale = 0.5
    thickness = 2
    pad = 8

    (tw, th), baseline = cv2.getTextSize(text, font, font_scale, thickness)
    box_w = tw + pad * 2
    box_h = th + baseline + pad * 2

    overlay = frame_bgr.copy()
    cv2.rectangle(overlay, (x, y), (x + box_w, y + box_h), (0, 0, 0), thickness=-1)
    cv2.addWeighted(overlay, 0.45, frame_bgr, 0.55, 0, frame_bgr)

    cv2.putText(frame_bgr, text, (x + pad, y + pad + th),
                font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
def draw_id_at_centroid(frame_bgr: np.ndarray, obj_id: int, center_xy: Tuple[int,int], color_bgr: Tuple[int,int,int]):
    cx, cy = center_xy
    font = cv2.FONT_HERSHEY_SIMPLEX
    font_scale = 0.5
    thickness = 1
    text = str(obj_id)

    (tw, th), baseline = cv2.getTextSize(text, font, font_scale, thickness)
    pad = 4

    x1 = cx - tw // 2 - pad
    y1 = cy - th // 2 - pad
    x2 = cx + tw // 2 + pad
    y2 = cy + th // 2 + pad

    H, W = frame_bgr.shape[:2]
    x1 = max(0, min(W - 1, x1))
    x2 = max(0, min(W - 1, x2))
    y1 = max(0, min(H - 1, y1))
    y2 = max(0, min(H - 1, y2))

    cv2.rectangle(frame_bgr, (x1, y1), (x2, y2), color_bgr, thickness=-1)
    txt_color = (0, 0, 0) if (sum(color_bgr) > 380) else (255, 255, 255)
    cv2.putText(frame_bgr, text, (x1 + pad, y2 - pad),
                font, font_scale, txt_color, thickness, cv2.LINE_AA)
def _wrap_text_to_width(text: str, font, font_scale: float, thickness: int, max_w: int) -> List[str]:
    if max_w <= 0:
        return [""]
    text = str(text)

    (tw, _), _b = cv2.getTextSize(text, font, font_scale, thickness)
    if tw <= max_w:
        return [text]

    words = text.split(" ")
    lines: List[str] = []
    cur = ""

    def fits(s: str) -> bool:
        (w, _), _b2 = cv2.getTextSize(s, font, font_scale, thickness)
        return w <= max_w

    for w in words:
        cand = w if cur == "" else (cur + " " + w)
        if fits(cand):
            cur = cand
        else:
            if cur:
                lines.append(cur)
                cur = ""
            if not fits(w):
                chunk = ""
                for ch in w:
                    cand2 = chunk + ch
                    if fits(cand2):
                        chunk = cand2
                    else:
                        if chunk:
                            lines.append(chunk)
                        chunk = ch
                if chunk:
                    cur = chunk
            else:
                cur = w
    if cur:
        lines.append(cur)
    return lines if lines else [""]


def render_object_list_panel_two_cols(
    width: int,
    panel_h: int,
    lines: List[str],
    font_scale: float = 0.5,
    thickness: int = 1,
    col_gap: int = 18,
    margin_x: int = 12,
    top_y: int = 24,
    line_h: int = 16,
) -> np.ndarray:
    """
    Two-column panel for object list lines like: "3: hand"
    Supports wrap inside each column.
    """
    panel = np.zeros((panel_h, width, 3), dtype=np.uint8)
    font = cv2.FONT_HERSHEY_SIMPLEX

    col_w = (width - 2 * margin_x - col_gap) // 2
    x1 = margin_x
    x2 = margin_x + col_w + col_gap

    pairs = [(lines[i], lines[i+1] if i+1 < len(lines) else "") for i in range(0, len(lines), 2)]

    y = top_y
    used = 0
    for left_text, right_text in pairs:
        left_wrapped = _wrap_text_to_width(left_text, font, font_scale, thickness, col_w) if left_text else []
        right_wrapped = _wrap_text_to_width(right_text, font, font_scale, thickness, col_w) if right_text else []
        row_lines = max(len(left_wrapped), len(right_wrapped), 1)
        row_h = row_lines * line_h

        if y + row_h > panel_h - 8:
            break

        yy = y
        for t in left_wrapped:
            cv2.putText(panel, t, (x1, yy), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
            yy += line_h

        yy = y
        for t in right_wrapped:
            cv2.putText(panel, t, (x2, yy), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
            yy += line_h

        y += row_h
        used += 2

    remaining = max(0, len(lines) - used)
    if remaining > 0:
        hint = f"... (+{remaining} more)"
        cv2.putText(panel, hint, (margin_x, panel_h - 10), font, font_scale, (200, 200, 200), thickness, cv2.LINE_AA)

    return panel

def safe_makedirs(p: str):
    os.makedirs(p, exist_ok=True)

def stable_color_for_id(obj_id: int) -> Tuple[int, int, int]:
    """
    Deterministic distinct-ish BGR color per object id.
    Uses HSV wheel -> BGR.
    """
    # golden ratio steps to spread hues
    hue = (obj_id * 0.61803398875) % 1.0
    h = int(hue * 179)            # OpenCV hue range [0,179]
    s = 200
    v = 255
    hsv = np.uint8([[[h, s, v]]])
    bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)[0, 0]
    return int(bgr[0]), int(bgr[1]), int(bgr[2])

def parse_gpt_json_from_conversations(convs: List[Dict[str, Any]]) -> Dict[str, Any]:
    """
    Extract and parse the 'gpt' message JSON (stored as a string in 'value').
    We make it robust to leading/trailing text by searching for the first {...} block.
    """
    gpt_msgs = [c for c in convs if c.get("from") == "gpt"]
    if not gpt_msgs:
        return {}

    raw = gpt_msgs[-1].get("value", "")
    if not raw:
        return {}

    # If it's already valid JSON, parse directly.
    try:
        return json.loads(raw)
    except Exception:
        pass

    # Otherwise, try to find the first JSON object substring.
    m = re.search(r"\{.*\}", raw, flags=re.DOTALL)
    if not m:
        return {}

    try:
        return json.loads(m.group(0))
    except Exception:
        return {}

def decode_rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
    """
    Robust RLE decode:
    - If rle['counts'] is list (uncompressed), use frPyObjects then decode.
    - If it's already compressed (bytes/str), decode directly.
    Returns uint8 mask of shape (H, W) with values 0/1.
    """
    if rle is None:
        return None

    if "size" not in rle or "counts" not in rle:
        return None

    h, w = rle["size"]
    counts = rle["counts"]

    try:
        if isinstance(counts, list):
            # uncompressed RLE -> convert using frPyObjects
            rle_obj = mask_utils.frPyObjects(rle, h, w)
            m = mask_utils.decode(rle_obj)
        else:
            # compressed (string/bytes)
            m = mask_utils.decode(rle)
    except Exception:
        # last attempt: sometimes need list-wrapping
        try:
            m = mask_utils.decode([rle])[:, :, 0]
        except Exception:
            return None

    # m can be (H,W) or (H,W,1)
    if m.ndim == 3:
        m = m[:, :, 0]
    m = (m > 0).astype(np.uint8)
    return m

def mask_centroid(mask01: np.ndarray) -> Optional[Tuple[int, int]]:
    """
    Compute centroid of binary mask (0/1). Returns (cx, cy) or None if empty.
    """
    if mask01 is None:
        return None
    ys, xs = np.where(mask01 > 0)
    if len(xs) == 0:
        return None
    cx = int(xs.mean())
    cy = int(ys.mean())
    return cx, cy

def overlay_mask(frame_bgr: np.ndarray, mask01: np.ndarray, color_bgr: Tuple[int,int,int], alpha: float) -> np.ndarray:
    """
    Alpha-blend colored mask onto frame.
    """
    if mask01 is None:
        return frame_bgr
    if mask01.sum() == 0:
        return frame_bgr

    out = frame_bgr.copy()
    color = np.array(color_bgr, dtype=np.float32).reshape(1, 1, 3)

    m = mask01.astype(bool)
    out_f = out.astype(np.float32)
    out_f[m] = out_f[m] * (1.0 - alpha) + color * alpha
    out = np.clip(out_f, 0, 255).astype(np.uint8)
    return out

def draw_label_box(frame_bgr: np.ndarray, text: str, center_xy: Tuple[int,int], color_bgr: Tuple[int,int,int]):
    """
    Draw filled rectangle with text centered at center_xy.
    """
    cx, cy = center_xy
    font = cv2.FONT_HERSHEY_SIMPLEX
    font_scale = 0.5
    thickness = 1

    (tw, th), baseline = cv2.getTextSize(text, font, font_scale, thickness)
    pad = 6

    x1 = int(cx - tw / 2) - pad
    y1 = int(cy - th / 2) - pad
    x2 = int(cx + tw / 2) + pad
    y2 = int(cy + th / 2) + pad

    # clamp
    h, w = frame_bgr.shape[:2]
    x1 = max(0, min(w - 1, x1))
    x2 = max(0, min(w - 1, x2))
    y1 = max(0, min(h - 1, y1))
    y2 = max(0, min(h - 1, y2))

    cv2.rectangle(frame_bgr, (x1, y1), (x2, y2), color_bgr, thickness=-1)
    # choose contrasting text color
    txt_color = (0, 0, 0) if (color_bgr[0] + color_bgr[1] + color_bgr[2]) > 380 else (255, 255, 255)
    cv2.putText(frame_bgr, text, (x1 + pad, y2 - pad),
                font, font_scale, txt_color, thickness, cv2.LINE_AA)

def relationship_active(rel_item: List[Any], frame_idx: int, fps: float) -> bool:
    """
    rel_item = [sub_id, rel_str, obj_id, intervals]
    intervals = [[t0,t1], ...]  where t0/t1 are seconds (float or int)
    We treat intervals inclusive on ends in time.
    """
    if len(rel_item) < 4:
        return False
    intervals = rel_item[3]
    if not isinstance(intervals, list) or fps <= 1e-6:
        return False

    t = frame_idx / fps  # current time in seconds
    for itv in intervals:
        if not (isinstance(itv, (list, tuple))) or len(itv) < 2:
            continue
        t0 = float(itv[0])
        t1 = float(itv[1])
        if t0 <= t <= t1:
            return True
    return False
def render_relationship_panel(
    width: int,
    panel_h: int,
    lines: List[str],
    font_scale: float = 0.5
) -> np.ndarray:
    """
    Create a black panel and draw relationship lines.
    """
    panel = np.zeros((panel_h, width, 3), dtype=np.uint8)
    font = cv2.FONT_HERSHEY_SIMPLEX
    thickness = 1
    y = 28
    for line in lines[: max(1, panel_h // 22) ]:
        cv2.putText(panel, line, (12, y), font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)
        y += 22
        if y > panel_h - 10:
            break
    return panel


# -----------------------------
# Core pipeline
# -----------------------------

def visualize_one(
    item: Dict[str, Any],
    out_path: str,
    alpha: float = 0.3,
    panel_h: int = 600,
    max_rels: int = 100,
    max_frames: Optional[int] = None,
    verbose: bool = True,
):
    video_path = item["video"]
    mask_path = item["mask_json"]
    obj_list = item.get("obj_list", None)

    g = parse_gpt_json_from_conversations(item.get("conversations", []))
    objects = g.get("objects", [])
    rels = g.get("relationships", [])

    # object id -> name (best effort)
    id2name: Dict[int, str] = {}
    for i, obj in enumerate(objects):
        if isinstance(obj, dict):
            # expected {"object_0":"hand", "attributes":[...]}
            # find key starting with object_
            name = None
            for k, v in obj.items():
                if isinstance(k, str) and k.startswith("object_"):
                    name = str(v)
                    # parse idx from key
                    try:
                        idx = int(k.split("_")[1])
                        id2name[idx] = name
                    except Exception:
                        pass
            # fallback: if it’s ordered list and missing explicit id
            if name is not None and i not in id2name:
                id2name[i] = name

    # load masks (2D list)
    with open(mask_path, "r") as f:
        masks_2d = json.load(f)

    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise RuntimeError(f"Failed to open video: {video_path}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    if not fps or math.isnan(fps) or fps <= 1e-3:
        fps = 30.0

    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # output writer with extra panel
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    writer = cv2.VideoWriter(out_path, fourcc, fps, (w, h + panel_h))
    if not writer.isOpened():
        raise RuntimeError(f"Failed to open writer: {out_path}")

    n_masks_frames = len(masks_2d)
    frame_idx = 0

    # decide which object ids to visualize
    if obj_list is None:
        # fallback to all objects present in gpt JSON
        obj_ids = sorted(id2name.keys())
    else:
        obj_ids = list(obj_list)

    if verbose:
        print(f"[viz] video={os.path.basename(video_path)} frames(video?) ~, masks_frames={n_masks_frames} obj_ids={obj_ids} rels={len(rels)} -> {out_path}")

    total_objs = len(obj_ids)
    obj_lines = []
    for oid in sorted(obj_ids):
        name = id2name.get(oid, f"obj_{oid}")
        obj_lines.append(f"{oid}: {name}")

    while True:
        ok, frame = cap.read()
        if not ok:
            break
        if frame_idx >= n_masks_frames:
            break
        if max_frames is not None and frame_idx >= max_frames:
            break

        draw_top_left_hud(frame, f"Os: {total_objs}")

        for obj_id in obj_ids:
            if obj_id >= len(masks_2d[frame_idx]):
                continue
            rle = masks_2d[frame_idx][obj_id]
            mask01 = decode_rle_to_mask(rle)
            if mask01 is None or mask01.sum() == 0:
                continue

            color = stable_color_for_id(obj_id)
            frame = overlay_mask(frame, mask01, color, alpha=alpha)

            cxy = mask_centroid(mask01)
            if cxy is not None:
                draw_id_at_centroid(frame, obj_id, cxy, color)

        panel = render_object_list_panel_two_cols(
            w, panel_h, obj_lines,
            font_scale=0.5,
            line_h=16
        )

        out_frame = np.vstack([frame, panel])
        writer.write(out_frame)

        frame_idx += 1

    cap.release()
    writer.release()






def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data_json", type=str, required=True,
                    help="Path to pe_with_relationships.json (800k items).")
    ap.add_argument("--out_dir", type=str, required=True,
                    help="Output directory for visualization videos.")
    ap.add_argument("--num_samples", type=int, default=100)
    ap.add_argument("--seed", type=int, default=42)
    ap.add_argument("--alpha", type=float, default=0.45)
    ap.add_argument("--panel_h", type=int, default=700)
    ap.add_argument("--max_rels", type=int, default=100)
    ap.add_argument("--max_frames", type=int, default=None,
                    help="Optional cap on frames per video (debug speed).")
    args = ap.parse_args()

    safe_makedirs(args.out_dir)
    
    raw_dir = args.out_dir + "_raw"
    safe_makedirs(raw_dir)


    with open(args.data_json, "r") as f:
        data = json.load(f)

    n = len(data)
    if n == 0:
        raise RuntimeError("Empty dataset JSON.")

    k = min(args.num_samples, n)
    rng = random.Random(args.seed)
    idxs = rng.sample(range(n), k)

    # dump sampled metadata (so you can reproduce)
    sampled_items = [data[i] for i in idxs]
    with open(os.path.join(args.out_dir, "sampled_items.json"), "w") as f:
        json.dump(sampled_items, f, indent=2)

    for j, i in enumerate(idxs):
        item = data[i]
        video_path = item["video"]
        base = os.path.splitext(os.path.basename(video_path))[0]
        # ===== 1. copy raw video =====
        raw_out_path = os.path.join(raw_dir, f"{j:03d}_{base}.mp4")
        if not os.path.exists(raw_out_path):
            try:
                shutil.copy2(video_path, raw_out_path)
            except Exception as e:
                print(f"[warn] failed to copy raw video: {video_path} -> {raw_out_path}: {e}")


        out_path = os.path.join(args.out_dir, f"{j:03d}_{base}_viz.mp4")
        try:
            visualize_one(
                item=item,
                out_path=out_path,
                alpha=args.alpha,
                panel_h=args.panel_h,
                max_rels=args.max_rels,
                max_frames=args.max_frames,
                verbose=True,
            )
        except Exception as e:
            # keep going; log failures
            err_path = os.path.join(args.out_dir, "errors.txt")
            with open(err_path, "a") as ef:
                ef.write(f"[ERROR] idx={i} video={video_path}\n{repr(e)}\n\n")
            print(f"[error] idx={i} video={video_path}: {e}")

    print(f"[done] wrote {k} videos into: {args.out_dir}")


if __name__ == "__main__":
    main()