| 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() |
|
|