| """Ray-based face parsing pipeline for local Hallo3 videos. |
| |
| This script scans a local directory of raw videos and runs SegFormer-based |
| face parsing on each file in parallel across multiple GPUs using Ray. |
| |
| For each input video, it produces a grayscale label video where each pixel |
| stores the class index (uint8) for that pixel. The labels are saved using |
| a lossless FFV1 codec (e.g., MKV container) so that labels can be read |
| back exactly as uint8 arrays. |
| |
| The saving format is compatible with the ``save_labels_to_video`` / |
| ``read_labels_from_video`` helpers in ``face_parse_example.py``. |
| |
| Example: |
| |
| ``` |
| python ray_face_parse_hallo3_pipeline.py \ |
| --input-dir /mnt/nfs/datasets/hallo3_data/videos \ |
| --output-dir /mnt/nfs/datasets/hallo3_data/face_parse_labels \ |
| --num-gpu-workers 4 \ |
| --stride 1 |
| |
| python 1_ray_face_parse_hallo3_pipeline.py \ |
| --input-dir /share/zhaohu_workspace/light-video-gen/meta_data_training/hallo3_training_data/videos \ |
| --output-dir /share/zhaohu_workspace/light-video-gen/meta_data_training/hallo3_training_data/face_parse_labels \ |
| --num-gpu-workers 1 \ |
| --start 0 \ |
| --stop 1 \ |
| --limit 1 \ |
| --shutdown-ray |
| |
| ## MEAD dataset |
| python 1_ray_face_parse_hallo3_pipeline.py \ |
| --input-dir /data/MEAD \ |
| --output-dir /data/MEAD_face_labels \ |
| --num-gpu-workers 16 \ |
| --start 0 \ |
| --shutdown-ray |
| ``` |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import os |
| from typing import Dict, List, Optional, Sequence |
|
|
| import ray |
| from ray.util.actor_pool import ActorPool |
| import torch |
| from torch import nn |
| from transformers import SegformerImageProcessor, SegformerForSemanticSegmentation |
|
|
| import cv2 |
| import ffmpeg |
| import numpy as np |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| import matplotlib.cm as cm |
|
|
|
|
| def _ensure_dir(path: str) -> str: |
| os.makedirs(path, exist_ok=True) |
| return path |
|
|
|
|
| def _list_video_files( |
| input_dir: str, |
| exts: Sequence[str] = (".mp4", ".mkv", ".webm", ".avi", ".mov"), |
| ) -> List[tuple[str, str]]: |
| """ |
| List video files recursively and return tuples of (absolute_path, relative_path). |
| |
| Returns: |
| List of tuples: (absolute_path, relative_path) where relative_path is |
| relative to input_dir, preserving subdirectory structure. |
| """ |
| input_dir = os.path.abspath(input_dir) |
| if not os.path.isdir(input_dir): |
| raise ValueError(f"input_dir does not exist or is not a directory: {input_dir}") |
|
|
| exts = tuple(ext.lower() for ext in exts) |
| video_paths: List[tuple[str, str]] = [] |
| for root, _, files in os.walk(input_dir): |
| for name in files: |
| if name.lower().endswith(exts): |
| abs_path = os.path.join(root, name) |
| |
| rel_path = os.path.relpath(abs_path, input_dir) |
| video_paths.append((abs_path, rel_path)) |
|
|
| |
| video_paths.sort(key=lambda x: x[1]) |
| if not video_paths: |
| raise ValueError(f"No video files found under {input_dir}") |
| return video_paths |
|
|
|
|
| def _build_output_path(rel_path: str, output_dir: str) -> str: |
| """ |
| Build output path preserving the original directory structure. |
| |
| Args: |
| rel_path: Relative path of the video file (from input_dir) |
| output_dir: Base output directory |
| |
| Returns: |
| Output path with same directory structure as input, with .mkv extension |
| """ |
| |
| rel_dir = os.path.dirname(rel_path) |
| base_name = os.path.basename(rel_path) |
| |
| |
| base_name_no_ext = os.path.splitext(base_name)[0] |
| out_name = f"{base_name_no_ext}.mkv" |
| |
| |
| if rel_dir: |
| out_dir = os.path.join(output_dir, rel_dir) |
| os.makedirs(out_dir, exist_ok=True) |
| return os.path.join(out_dir, out_name) |
| else: |
| return os.path.join(output_dir, out_name) |
|
|
|
|
| def read_labels_from_video(video_path: str) -> Optional[np.ndarray]: |
| """Read grayscale video back as numpy array.""" |
| try: |
| probe = ffmpeg.probe(video_path) |
| video_info = next(s for s in probe["streams"] if s["codec_type"] == "video") |
| width = int(video_info["width"]) |
| height = int(video_info["height"]) |
|
|
| out, _ = ( |
| ffmpeg.input(video_path) |
| .output("pipe:", format="rawvideo", pix_fmt="gray") |
| .run(capture_stdout=True, capture_stderr=True) |
| ) |
|
|
| decoded = np.frombuffer(out, np.uint8).reshape((-1, height, width)) |
| return decoded |
| except Exception as e: |
| print(f"Error reading video {video_path}: {e}") |
| return None |
|
|
|
|
| def visualize_labels(video_path: str, max_frames: int = 10, save_path: Optional[str] = None) -> None: |
| """ |
| Visualize face parsing labels from a label video file. |
| |
| Args: |
| video_path: Path to the label video file (e.g., .mkv file with face parsing labels) |
| max_frames: Maximum number of frames to display (default: 10). If None, displays all frames. |
| save_path: Optional path to save the visualization image. If None, displays interactively. |
| """ |
| |
| labels = read_labels_from_video(video_path) |
| |
| if labels is None: |
| print(f"Failed to read labels from {video_path}") |
| return |
| |
| if labels.size == 0: |
| print(f"No labels found in {video_path}") |
| return |
| |
| num_frames, height, width = labels.shape |
| print(f"Loaded {num_frames} frames of shape ({height}, {width}) from {video_path}") |
| |
| |
| if max_frames is not None and max_frames > 0: |
| num_frames = min(num_frames, max_frames) |
| |
| |
| |
| cmap = cm.get_cmap('tab20') |
| |
| |
| cols = min(5, num_frames) |
| rows = (num_frames + cols - 1) // cols |
| |
| fig, axes = plt.subplots(rows, cols, figsize=(15, 3 * rows)) |
| if num_frames == 1: |
| axes = [axes] |
| elif rows == 1: |
| axes = axes if isinstance(axes, np.ndarray) else [axes] |
| else: |
| axes = axes.flatten() |
| |
| |
| all_labels = np.unique(labels[:num_frames]) |
| max_label = int(all_labels.max()) if len(all_labels) > 0 else 0 |
| |
| |
| for idx in range(num_frames): |
| label_frame = labels[idx] |
| |
| |
| unique_labels = np.unique(label_frame) |
| |
| |
| if max_label > 0: |
| normalized = label_frame.astype(np.float32) / max_label |
| else: |
| normalized = label_frame.astype(np.float32) |
| |
| |
| colored = cmap(normalized)[:, :, :3] |
| |
| ax = axes[idx] |
| ax.imshow(colored) |
| ax.set_title(f'Frame {idx}\nClasses: {len(unique_labels)} (max={max_label})') |
| ax.axis('off') |
| |
| |
| for idx in range(num_frames, len(axes)): |
| axes[idx].axis('off') |
| |
| plt.tight_layout() |
| |
| if save_path: |
| plt.savefig(save_path, dpi=150, bbox_inches='tight') |
| print(f"Visualization saved to {save_path}") |
| else: |
| plt.show() |
| |
| plt.close() |
|
|
|
|
| def save_labels_to_video(labels: np.ndarray, output_path: str, fps: int = 30) -> bool: |
| """Save numpy array (frames, height, width) as grayscale lossless video.""" |
| try: |
| if labels.ndim != 3: |
| raise ValueError("Input array must be 3D (frames, height, width)") |
|
|
| frames, height, width = labels.shape |
|
|
| if labels.dtype != np.uint8: |
| labels = labels.astype(np.uint8) |
|
|
| process = ( |
| ffmpeg.input( |
| "pipe:", |
| format="rawvideo", |
| pix_fmt="gray", |
| s=f"{width}x{height}", |
| r=int(fps), |
| ) |
| .output( |
| output_path, |
| pix_fmt="gray", |
| vcodec="ffv1", |
| level=3, |
| ) |
| .overwrite_output() |
| .run_async(pipe_stdin=True) |
| ) |
|
|
| process.stdin.write(labels.tobytes()) |
| process.stdin.close() |
| process.wait() |
| return True |
|
|
| except Exception as e: |
| print(f"Error saving video {output_path}: {e}") |
| return False |
|
|
|
|
| def _device() -> torch.device: |
| if torch.cuda.is_available(): |
| return torch.device("cuda") |
| if torch.backends.mps.is_available(): |
| return torch.device("mps") |
| return torch.device("cpu") |
|
|
|
|
| def _parse_video_to_labels( |
| image_processor: SegformerImageProcessor, |
| model: SegformerForSemanticSegmentation, |
| video_path: str, |
| stride: int, |
| ) -> np.ndarray: |
| """Run face parsing on a video and return labels as (T, H, W) uint8.""" |
| cap = cv2.VideoCapture(video_path) |
| if not cap.isOpened(): |
| print(f"Failed to open video: {video_path}") |
| return None |
| |
|
|
| labels_list: List[np.ndarray] = [] |
| idx = 0 |
|
|
| try: |
| with torch.no_grad(): |
| while True: |
| ret, frame = cap.read() |
| if not ret: |
| break |
|
|
| if stride > 1 and (idx % stride) != 0: |
| idx += 1 |
| continue |
|
|
| frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| image = Image.fromarray(frame_rgb) |
|
|
| inputs = image_processor(images=image, return_tensors="pt") |
| inputs = {k: v.to(model.device) for k, v in inputs.items()} |
|
|
| outputs = model(**inputs) |
| logits = outputs.logits |
|
|
| upsampled_logits = nn.functional.interpolate( |
| logits, |
| size=image.size[::-1], |
| mode="bilinear", |
| align_corners=False, |
| ) |
|
|
| labels = upsampled_logits.argmax(dim=1)[0] |
| labels_np = labels.cpu().numpy().astype(np.uint8) |
| labels_list.append(labels_np) |
|
|
| idx += 1 |
| finally: |
| cap.release() |
|
|
| if not labels_list: |
| return np.zeros((0, 0, 0), dtype=np.uint8) |
|
|
| return np.stack(labels_list, axis=0) |
|
|
|
|
| @ray.remote |
| class FaceParseWorker: |
| def __init__( |
| self, |
| output_dir: str, |
| stride: int, |
| ) -> None: |
| dev = _device() |
| self.device = dev |
| self.image_processor = SegformerImageProcessor.from_pretrained( |
| "jonathandinu/face-parsing" |
| ) |
| self.model = SegformerForSemanticSegmentation.from_pretrained( |
| "jonathandinu/face-parsing" |
| ).to(dev) |
| self.output_dir = _ensure_dir(output_dir) |
| self.stride = stride |
| self.skip_existing = True |
|
|
| def parse(self, record: Dict) -> Dict: |
| index = int(record["index"]) |
| video_path = record["path"] |
| rel_path = record["rel_path"] |
| file_name = record["file_name"] |
| out_path = _build_output_path(rel_path, self.output_dir) |
|
|
| if self.skip_existing and os.path.exists(out_path): |
| return { |
| "index": index, |
| "file_name": file_name, |
| "result_path": out_path, |
| "frame_count": 0, |
| "skipped": True, |
| } |
|
|
| labels = _parse_video_to_labels( |
| self.image_processor, |
| self.model, |
| video_path, |
| stride=self.stride, |
| ) |
|
|
| if labels is None or labels.size == 0: |
| frame_count = 0 |
| save_ok = False |
| else: |
| frame_count = int(labels.shape[0]) |
| fps = 25 |
| save_ok = save_labels_to_video(labels, out_path, fps=fps) |
|
|
| return { |
| "index": index, |
| "file_name": file_name, |
| "result_path": out_path, |
| "frame_count": frame_count, |
| "skipped": False, |
| "saved": bool(save_ok), |
| } |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
|
|
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| |
| |
| |
|
|
|
|
| |
| |
|
|
| |
|
|
|
|