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
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
from __future__ import annotations

import argparse
import csv
import os
import shutil
import subprocess
from fractions import Fraction
from pathlib import Path

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

try:
    from Cut_video.build_sentence_dataset import load_pickle_compatible
except ModuleNotFoundError:
    from build_sentence_dataset import load_pickle_compatible


WIDTH = 1440
HEIGHT = 720
PANEL_WIDTH = 336
PANEL_HEIGHT = 420
PANEL_TOP = 72
PANEL_LEFTS = (72, 552, 1032)
FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"

BODY_EDGES = [
    (0, 1), (0, 2), (1, 3), (2, 4),
    (5, 6), (5, 7), (7, 9), (6, 8), (8, 10),
    (5, 11), (6, 12), (11, 12),
    (11, 13), (13, 15), (12, 14), (14, 16),
    (15, 17), (15, 18), (15, 19),
    (16, 20), (16, 21), (16, 22),
]
UPPER_BODY_EDGES = [
    (0, 1), (0, 2), (1, 3), (2, 4),
    (5, 6), (5, 7), (7, 9), (6, 8), (8, 10),
    (5, 11), (6, 12), (11, 12),
    (9, 91), (10, 112),
]
HAND_LOCAL_EDGES = [
    (0, 1), (1, 2), (2, 3), (3, 4),
    (0, 5), (5, 6), (6, 7), (7, 8),
    (0, 9), (9, 10), (10, 11), (11, 12),
    (0, 13), (13, 14), (14, 15), (15, 16),
    (0, 17), (17, 18), (18, 19), (19, 20),
]
FACE_PATHS = [
    (list(range(23, 40)), False),
    (list(range(40, 45)), False),
    (list(range(45, 50)), False),
    (list(range(50, 54)), False),
    (list(range(54, 59)), False),
    (list(range(59, 65)), True),
    (list(range(65, 71)), True),
    (list(range(71, 83)), True),
    (list(range(83, 91)), True),
]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Create an RGB/skeleton/overlay comparison preview with source audio."
    )
    parser.add_argument("--sample-id", required=True)
    parser.add_argument("--dataset-root", type=Path, required=True)
    parser.add_argument("--source-video-dir", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument(
        "--upper-body-only",
        action="store_true",
        help="Keep keypoints through the hips; hide knees, ankles and feet (13-22).",
    )
    return parser.parse_args()


def find_sample(dataset_root: Path, sample_id: str) -> dict[str, str]:
    for split in ("train", "val", "test"):
        csv_path = dataset_root / "csv" / f"{split}.csv"
        with csv_path.open(encoding="utf-8", newline="") as handle:
            for row in csv.DictReader(handle):
                if row["sample_id"] == sample_id:
                    row["split"] = split
                    return row
    raise KeyError(f"Sample not found in train/val/test CSV: {sample_id}")


def valid_point(point: np.ndarray, score: float, threshold: float = 0.3) -> bool:
    return bool(
        score > threshold
        and np.isfinite(point).all()
        and 0 <= point[0] < PANEL_WIDTH
        and 0 <= point[1] < PANEL_HEIGHT
    )


def draw_edges(
    image: np.ndarray,
    points: np.ndarray,
    scores: np.ndarray,
    edges: list[tuple[int, int]],
    color: tuple[int, int, int],
    thickness: int,
) -> None:
    for start, end in edges:
        if valid_point(points[start], scores[start]) and valid_point(
            points[end], scores[end]
        ):
            cv2.line(
                image,
                tuple(np.rint(points[start]).astype(int)),
                tuple(np.rint(points[end]).astype(int)),
                color,
                thickness,
                cv2.LINE_AA,
            )


def draw_face(
    image: np.ndarray, points: np.ndarray, scores: np.ndarray, thickness: int
) -> None:
    color = (0, 165, 255)
    for indices, closed in FACE_PATHS:
        valid_runs: list[list[tuple[int, int]]] = []
        run: list[tuple[int, int]] = []
        for index in indices:
            if valid_point(points[index], scores[index]):
                run.append(tuple(np.rint(points[index]).astype(int)))
            elif run:
                valid_runs.append(run)
                run = []
        if run:
            valid_runs.append(run)
        for coordinates in valid_runs:
            if len(coordinates) >= 2:
                cv2.polylines(
                    image,
                    [np.asarray(coordinates, dtype=np.int32)],
                    closed and len(coordinates) == len(indices),
                    color,
                    thickness,
                    cv2.LINE_AA,
                )


def draw_skeleton(
    image: np.ndarray,
    normalized_keypoints: np.ndarray,
    scores: np.ndarray,
    overlay: bool,
    upper_body_only: bool,
) -> np.ndarray:
    points = normalized_keypoints.astype(np.float32).copy()
    points[:, 0] *= PANEL_WIDTH
    points[:, 1] *= PANEL_HEIGHT
    line_width = 3 if overlay else 2

    body_edges = UPPER_BODY_EDGES if upper_body_only else BODY_EDGES
    draw_edges(image, points, scores, body_edges, (80, 255, 80), line_width)
    left_edges = [(91 + a, 91 + b) for a, b in HAND_LOCAL_EDGES]
    right_edges = [(112 + a, 112 + b) for a, b in HAND_LOCAL_EDGES]
    draw_edges(image, points, scores, left_edges, (255, 220, 40), line_width)
    draw_edges(image, points, scores, right_edges, (255, 80, 220), line_width)
    draw_face(image, points, scores, 2 if overlay else 1)

    for index, (point, score) in enumerate(zip(points, scores)):
        if upper_body_only and 13 <= index < 23:
            continue
        if not valid_point(point, score):
            continue
        if index < 23:
            color, radius = (80, 255, 80), 4
        elif index < 91:
            color, radius = (0, 165, 255), 2
        elif index < 112:
            color, radius = (255, 220, 40), 3
        else:
            color, radius = (255, 80, 220), 3
        cv2.circle(
            image,
            tuple(np.rint(point).astype(int)),
            radius,
            color,
            -1,
            cv2.LINE_AA,
        )
    return image


def load_font(size: int) -> ImageFont.FreeTypeFont:
    return ImageFont.truetype(FONT_PATH, size=size)


def draw_text_bgr(
    image: np.ndarray,
    text: str,
    position: tuple[int, int],
    font: ImageFont.FreeTypeFont,
    color: tuple[int, int, int],
) -> None:
    pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(pil_image)
    draw.text(position, text, font=font, fill=(color[2], color[1], color[0]))
    image[:] = cv2.cvtColor(np.asarray(pil_image), cv2.COLOR_RGB2BGR)


def wrap_text(
    text: str, font: ImageFont.FreeTypeFont, maximum_width: int
) -> list[str]:
    probe = ImageDraw.Draw(Image.new("RGB", (1, 1)))
    lines: list[str] = []
    current = ""
    for word in text.split():
        candidate = f"{current} {word}".strip()
        width = probe.textbbox((0, 0), candidate, font=font)[2]
        if current and width > maximum_width:
            lines.append(current)
            current = word
        else:
            current = candidate
    if current:
        lines.append(current)
    return lines


def compose_frame(
    rgb_frame: np.ndarray,
    keypoints: np.ndarray,
    scores: np.ndarray,
    row: dict[str, str],
    frame_index: int,
    fps: Fraction,
    upper_body_only: bool,
) -> np.ndarray:
    canvas = np.full((HEIGHT, WIDTH, 3), 22, dtype=np.uint8)
    panel_rgb = cv2.resize(
        rgb_frame, (PANEL_WIDTH, PANEL_HEIGHT), interpolation=cv2.INTER_CUBIC
    )
    skeleton = draw_skeleton(
        np.zeros((PANEL_HEIGHT, PANEL_WIDTH, 3), dtype=np.uint8),
        keypoints,
        scores,
        overlay=False,
        upper_body_only=upper_body_only,
    )
    overlay = draw_skeleton(
        panel_rgb.copy(),
        keypoints,
        scores,
        overlay=True,
        upper_body_only=upper_body_only,
    )
    for left, panel in zip(PANEL_LEFTS, (panel_rgb, skeleton, overlay)):
        canvas[PANEL_TOP : PANEL_TOP + PANEL_HEIGHT, left : left + PANEL_WIDTH] = panel
        cv2.rectangle(
            canvas,
            (left - 1, PANEL_TOP - 1),
            (left + PANEL_WIDTH, PANEL_TOP + PANEL_HEIGHT),
            (110, 110, 110),
            2,
        )

    title_font = load_font(25)
    label_font = load_font(23)
    transcript_font = load_font(22)
    source_second = int(row["clip_start_frame"]) / float(fps) + frame_index / float(fps)
    header = (
        f"{row['sample_id']}  |  split={row['split']}  |  "
        f"source frame={int(row['clip_start_frame']) + frame_index}  |  "
        f"time={source_second:.3f}s  |  AUDIO: source AAC"
    )
    draw_text_bgr(canvas, header, (36, 20), title_font, (245, 245, 245))
    skeleton_label = (
        "TỪ HÔNG TRỞ LÊN + FACE + HANDS"
        if upper_body_only
        else "SKELETON 133 ĐIỂM"
    )
    labels = ("VIDEO RGB", skeleton_label, "OVERLAY RGB + SKELETON")
    for left, label in zip(PANEL_LEFTS, labels):
        draw_text_bgr(canvas, label, (left, 505), label_font, (90, 230, 255))

    transcript_top = 552
    cv2.rectangle(canvas, (24, transcript_top), (WIDTH - 24, HEIGHT - 18), (8, 8, 8), -1)
    prefix = (
        f"Transcript [{row['transcript_start_sec']}s - "
        f"{row['transcript_end_sec']}s] (+3s padding): "
    )
    lines = wrap_text(prefix + row["text"], transcript_font, WIDTH - 80)
    for line_index, line in enumerate(lines[:4]):
        draw_text_bgr(
            canvas,
            line,
            (40, transcript_top + 14 + line_index * 34),
            transcript_font,
            (240, 240, 240),
        )
    return canvas


def write_visual_video(
    clip_path: Path,
    pkl_path: Path,
    row: dict[str, str],
    output_path: Path,
    upper_body_only: bool,
) -> Fraction:
    payload = load_pickle_compatible(pkl_path)
    keypoints = payload["keypoints"]
    scores = payload["scores"]
    expected_frames = int(row["num_frames"])
    if len(keypoints) != expected_frames or len(scores) != expected_frames:
        raise ValueError("PKL length does not match CSV num_frames")

    with av.open(str(clip_path)) as input_container:
        input_stream = input_container.streams.video[0]
        fps = Fraction(input_stream.average_rate or input_stream.base_rate)
        with av.open(str(output_path), mode="w") as output_container:
            stream = output_container.add_stream("libx264", rate=fps)
            stream.width = WIDTH
            stream.height = HEIGHT
            stream.pix_fmt = "yuv420p"
            stream.options = {"crf": "18", "preset": "fast"}
            decoded = 0
            for frame_index, frame in enumerate(input_container.decode(video=0)):
                if frame_index >= expected_frames:
                    raise ValueError("Video contains more frames than CSV")
                rgb_bgr = frame.to_ndarray(format="bgr24")
                composed = compose_frame(
                    rgb_bgr,
                    np.asarray(keypoints[frame_index])[0],
                    np.asarray(scores[frame_index])[0],
                    row,
                    frame_index,
                    fps,
                    upper_body_only,
                )
                output_frame = av.VideoFrame.from_ndarray(composed, format="bgr24")
                output_frame.pts = frame_index
                output_frame.time_base = Fraction(fps.denominator, fps.numerator)
                for packet in stream.encode(output_frame):
                    output_container.mux(packet)
                decoded += 1
            if decoded != expected_frames:
                raise ValueError(
                    f"Decoded {decoded} video frames, expected {expected_frames}"
                )
            for packet in stream.encode():
                output_container.mux(packet)
    return fps


def mux_source_audio(
    visual_path: Path,
    source_video: Path,
    start_seconds: float,
    duration_seconds: float,
    output_path: Path,
) -> None:
    ffmpeg = shutil.which("ffmpeg")
    if ffmpeg is None:
        raise FileNotFoundError("ffmpeg is not available")
    subprocess.run(
        [
            ffmpeg,
            "-hide_banner",
            "-loglevel",
            "error",
            "-y",
            "-i",
            str(visual_path),
            "-ss",
            f"{start_seconds:.6f}",
            "-i",
            str(source_video),
            "-map",
            "0:v:0",
            "-map",
            "1:a:0",
            "-c:v",
            "copy",
            "-c:a",
            "aac",
            "-b:a",
            "192k",
            "-af",
            "asetpts=PTS-STARTPTS",
            "-t",
            f"{duration_seconds:.6f}",
            "-movflags",
            "+faststart",
            str(output_path),
        ],
        check=True,
    )


def main() -> None:
    args = parse_args()
    dataset_root = args.dataset_root.resolve()
    row = find_sample(dataset_root, args.sample_id)
    clip_path = dataset_root / row["video_path"]
    pkl_path = dataset_root / row["pkl_path"]
    source_video = args.source_video_dir.resolve() / f"{row['source_id']}.mp4"
    for path in (clip_path, pkl_path, source_video):
        if not path.is_file():
            raise FileNotFoundError(path)

    args.output.parent.mkdir(parents=True, exist_ok=True)
    visual_temporary = args.output.with_name(
        f".{args.output.stem}.{os.getpid()}.visual.tmp.mp4"
    )
    muxed_temporary = args.output.with_name(
        f".{args.output.stem}.{os.getpid()}.muxed.tmp.mp4"
    )
    try:
        fps = write_visual_video(
            clip_path,
            pkl_path,
            row,
            visual_temporary,
            upper_body_only=args.upper_body_only,
        )
        start_seconds = int(row["clip_start_frame"]) / float(fps)
        duration_seconds = int(row["num_frames"]) / float(fps)
        mux_source_audio(
            visual_temporary,
            source_video,
            start_seconds,
            duration_seconds,
            muxed_temporary,
        )
        os.replace(muxed_temporary, args.output)
    finally:
        visual_temporary.unlink(missing_ok=True)
        muxed_temporary.unlink(missing_ok=True)

    print(args.output.resolve())


if __name__ == "__main__":
    main()