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