"""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) # Calculate relative path from input_dir rel_path = os.path.relpath(abs_path, input_dir) video_paths.append((abs_path, rel_path)) # Sort by relative path to maintain consistent ordering 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 """ # Get the directory part and filename part of the relative path rel_dir = os.path.dirname(rel_path) base_name = os.path.basename(rel_path) # Remove original extension and add .mkv base_name_no_ext = os.path.splitext(base_name)[0] out_name = f"{base_name_no_ext}.mkv" # Reconstruct the full output path preserving directory structure 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. """ # Read labels from video 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}") # Limit number of frames to display if max_frames is not None and max_frames > 0: num_frames = min(num_frames, max_frames) # Create a colormap for visualization # Use a colormap that provides good visual distinction between different label classes cmap = cm.get_cmap('tab20') # Use tab20 colormap for up to 20 classes # Calculate grid size for subplots 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() # Get all unique labels across all frames for consistent colormap all_labels = np.unique(labels[:num_frames]) max_label = int(all_labels.max()) if len(all_labels) > 0 else 0 # Normalize labels to [0, 1] range for colormap for idx in range(num_frames): label_frame = labels[idx] # Get unique labels in this frame unique_labels = np.unique(label_frame) # Normalize to [0, 1] range based on all possible labels if max_label > 0: normalized = label_frame.astype(np.float32) / max_label else: normalized = label_frame.astype(np.float32) # Apply colormap colored = cmap(normalized)[:, :, :3] # Remove alpha channel, keep RGB ax = axes[idx] ax.imshow(colored) ax.set_title(f'Frame {idx}\nClasses: {len(unique_labels)} (max={max_label})') ax.axis('off') # Hide unused subplots 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 # raise RuntimeError(f"Failed to open video: {video_path}") 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 # fallback if we can't probe; video-specific fps is optional 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), } # def parse_args() -> argparse.Namespace: # parser = argparse.ArgumentParser( # description="Ray-based face parsing for local Hallo3 videos" # ) # parser.add_argument( # "--input-dir", # default="/share/zhaohu_workspace/light-video-gen/test_videos", # help="Directory containing raw Hallo3 video files", # ) # parser.add_argument( # "--output-dir", # default="/share/zhaohu_workspace/light-video-gen/test_videos/face_labels", # help="Directory to store face parsing label videos", # ) # parser.add_argument( # "--num-gpu-per-actor", # type=float, # default=1.0, # help="Number of GPUs per actor", # ) # parser.add_argument( # "--num-total-gpu", # type=int, # default=1, # help="Total number of GPUs available", # ) # parser.add_argument( # "--num-cpus", # type=int, # default=1, # help="Total number of CPUs available", # ) # return parser.parse_args() # def run_pipeline(args: argparse.Namespace) -> None: # # Set Ray temp directory to use /tmp/ray to avoid socket path length limits # # AF_UNIX socket paths cannot exceed 107 bytes on Linux # ray_temp_dir = "/tmp/ray" # _ensure_dir(ray_temp_dir) # ray.init( # address=None, # ignore_reinit_error=True, # _temp_dir=ray_temp_dir, # ) # _ensure_dir(args.output_dir) # video_paths = _list_video_files(args.input_dir) # dataset_size = len(video_paths) # # Process all videos # start_idx = 0 # stop_idx = dataset_size # # Default values # stride = 1 # # Calculate number of actors based on GPU and CPU resources # num_actors = int(args.num_total_gpu / args.num_gpu_per_actor) # cpus_per_actor = args.num_cpus / num_actors if num_actors > 0 else 1 # print(f"Starting processing with {num_actors} actors on {dataset_size} videos.") # print(f"Resources: {args.num_gpu_per_actor} GPUs per actor, {cpus_per_actor:.2f} CPUs per actor") # if num_actors <= 0: # raise ValueError(f"Invalid configuration: num_total_gpu={args.num_total_gpu}, num_gpu_per_actor={args.num_gpu_per_actor}") # # Create actors # actors = [ # FaceParseWorker.options( # num_gpus=args.num_gpu_per_actor, # num_cpus=cpus_per_actor # ).remote( # output_dir=args.output_dir, # stride=stride, # ) # for _ in range(num_actors) # ] # # Create ActorPool # pool = ActorPool(actors) # total_submitted = 0 # total_completed = 0 # try: # # Submit tasks # for idx in range(start_idx, stop_idx): # video_path, rel_path = video_paths[idx] # file_name = os.path.basename(video_path) # record = { # "index": idx, # "file_name": file_name, # "rel_path": rel_path, # "path": video_path, # } # # Submit task to pool # pool.submit(lambda actor, rec: actor.parse.remote(rec), record) # total_submitted += 1 # # Collect results # while pool.has_next(): # try: # result = pool.get_next_unordered() # total_completed += 1 # status = "skipped" if result.get("skipped") else "done" # saved = result.get("saved", False) # print( # f"[{total_completed}] idx={result['index']} file={result['file_name']} " # f"-> {result['result_path']} ({status}, frames={result['frame_count']}, saved={saved})" # ) # except Exception as e: # print(f"Error getting result from pool: {e}") # finally: # ray.shutdown() # def main() -> None: # args = parse_args() # run_pipeline(args) # if __name__ == "__main__": # main() # visualize_labels("/data/MEAD_face_labels/M003/video/down/angry/level_1/001.mkv", max_frames=10, save_path="./visualization_face_labels.png")