File size: 32,581 Bytes
4b3a024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
"""
Dataset implementations for video generation.
"""

import os
import json
import cv2
import torch
import torch.nn.functional as F
import random
import numpy as np
from torch.utils.data import Dataset
from omegaconf import DictConfig, ListConfig
from typing import Optional, List, Sequence
from decord import VideoReader
import ffmpeg
import librosa
import warnings
from transformers import Wav2Vec2Processor

# Prefer audioread for MP4 containers to avoid PySoundFile warnings
try:
    if hasattr(librosa, "set_audio_backend"):
        librosa.set_audio_backend("audioread")
except Exception:
    pass

# Suppress noisy backend warnings from librosa when reading MP4
warnings.filterwarnings("ignore", message="PySoundFile failed. Trying audioread instead.")
warnings.filterwarnings(
    "ignore",
    category=FutureWarning,
    message=r"librosa\.core\.audio\.__audioread_load.*",
)

# Import our modular utilities
from .landmark_utils import (
    FACEMESH_LEFT_EYE, FACEMESH_RIGHT_EYE, FACEMESH_LEFT_EYEBROW, 
    FACEMESH_RIGHT_EYEBROW, FACEMESH_LIPS_ALL, FACEMESH_FACE_OVAL,
    LandmarkRenderer, create_valid_landmark_mask
)
from .video_utils import load_video_rgb_fchw, infer_video_path_from_cache, choose_window_start
from .config import DatasetConfig


def _is_audio_silent(audio_array: np.ndarray, threshold: float = 0.001) -> bool:
    """Check if audio is approximately silent via RMS amplitude."""
    if audio_array.size == 0:
        return True
    rms = float(np.sqrt(np.mean(np.square(audio_array, dtype=np.float32))))
    return rms < threshold


def _read_labels_from_video(video_path: str) -> Optional[np.ndarray]:
    """Read grayscale label video back as numpy array: (T, H, W), uint8."""
    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 label video {video_path}: {e}")
        return None


def _compute_lip_bboxes(
    labels: np.ndarray,
    lip_scale: float = 1.2,
    nose_labels: Sequence[int] = (2,),
    face_labels: Sequence[int] = (1,),
) -> List[Optional[tuple[int, int, int, int]]]:
    """Compute per-frame mouth-region bboxes using nose + face masks, with temporal interpolation.

    Copied and adapted from visualize_face_parse_labels_v2._compute_lip_bboxes.
    """
    if labels.ndim != 3:
        raise ValueError("labels must have shape (T, H, W)")

    T, H, W = labels.shape
    lip_scale = max(float(lip_scale), 1.0)

    raw_bboxes: List[Optional[tuple[int, int, int, int]]] = [None] * T

    # First, per-frame bbox from masks (if present).
    for t in range(T):
        frame_labels = labels[t]

        nose_mask = np.isin(frame_labels, nose_labels)
        face_mask = np.isin(frame_labels, face_labels)

        if not np.any(nose_mask) or not np.any(face_mask):
            continue

        # Nose: lowest point (max y) used as top boundary.
        nose_ys, _ = np.where(nose_mask)
        y_top = float(nose_ys.max())

        # Face: use full extent as bottom/left/right.
        face_ys, face_xs = np.where(face_mask)
        y_bottom = float(face_ys.max())
        x_left = float(face_xs.min())
        x_right = float(face_xs.max())

        # Sanity check.
        if y_bottom <= y_top:
            continue

        # Base bbox.
        x_min = x_left
        x_max = x_right
        y_min = y_top
        y_max = y_bottom

        # Size and center.
        w = x_max - x_min + 1.0
        h = y_max - y_min + 1.0
        cx = (x_min + x_max) / 2.0
        cy = (y_min + y_max) / 2.0

        # Apply scaling around center.
        new_w = w * lip_scale
        new_h = h * lip_scale

        x_min_s = int(round(cx - new_w / 2.0))
        x_max_s = int(round(cx + new_w / 2.0))
        y_min_s = int(round(cy - new_h / 2.0))
        y_max_s = int(round(cy + new_h / 2.0))

        x_min_s = max(0, min(x_min_s, W - 1))
        x_max_s = max(0, min(x_max_s, W - 1))
        y_min_s = max(0, min(y_min_s, H - 1))
        y_max_s = max(0, min(y_max_s, H - 1))

        if x_max_s <= x_min_s or y_max_s <= y_min_s:
            continue

        raw_bboxes[t] = (x_min_s, y_min_s, x_max_s, y_max_s)

    # If no frame has a bbox, return all None.
    if not any(bb is not None for bb in raw_bboxes):
        return raw_bboxes

    # Temporal interpolation over time for each coordinate.
    coords: List[List[Optional[int]]] = [[None] * T for _ in range(4)]
    for t, bb in enumerate(raw_bboxes):
        if bb is None:
            continue
        for d in range(4):
            coords[d][t] = bb[d]

    for d in range(4):
        keyframes = [(t, coords[d][t]) for t in range(T) if coords[d][t] is not None]
        if not keyframes:
            continue

        # Fill before first keyframe.
        first_idx, first_val = keyframes[0]
        for t in range(0, first_idx):
            coords[d][t] = first_val

        # Linear interpolation between keyframes.
        for (i, v0), (j, v1) in zip(keyframes, keyframes[1:]):
            coords[d][i] = v0
            coords[d][j] = v1
            gap = j - i
            if gap <= 1:
                continue
            for t in range(i + 1, j):
                alpha = (t - i) / float(gap)
                interp_val = int(round(v0 + (v1 - v0) * alpha))
                coords[d][t] = interp_val

        # Fill after last keyframe.
        last_idx, last_val = keyframes[-1]
        for t in range(last_idx + 1, T):
            coords[d][t] = last_val

    final_bboxes: List[Optional[tuple[int, int, int, int]]] = [None] * T
    for t in range(T):
        if all(coords[d][t] is not None for d in range(4)):
            final_bboxes[t] = (
                int(coords[0][t]),
                int(coords[1][t]),
                int(coords[2][t]),
                int(coords[3][t]),
            )

    return final_bboxes


def _bboxes_to_masks(
    bboxes: List[Optional[tuple[int, int, int, int]]], H: int, W: int
) -> np.ndarray:
    """Convert per-frame bboxes to binary masks (T, H, W) with 1 inside bbox, 0 outside."""
    T = len(bboxes)
    masks = np.zeros((T, H, W), dtype=np.float32)
    for t, bb in enumerate(bboxes):
        if bb is None:
            continue
        x_min, y_min, x_max, y_max = bb
        y1 = int(max(0, min(y_min, H - 1)))
        y2 = int(max(0, min(y_max, H - 1)))
        x1 = int(max(0, min(x_min, W - 1)))
        x2 = int(max(0, min(x_max, W - 1)))
        if x2 <= x1 or y2 <= y1:
            continue
        masks[t, y1 : y2 + 1, x1 : x2 + 1] = 1.0
    return masks


def _infer_label_path(label_root: str, video_name: str) -> Optional[str]:
    """Infer face-parse label video path from original video filename."""
    base, ext = os.path.splitext(video_name)
    candidates = [
        os.path.join(label_root, base + ".mkv"),
        os.path.join(label_root, base + ".mp4"),
        os.path.join(label_root, base + ".avi"),
        os.path.join(label_root, video_name),
        # Common pattern in this repo: "<name>.mp4.mkv"
        os.path.join(label_root, video_name + ".mkv"),
    ]
    for c in candidates:
        if os.path.exists(c):
            return c
    return None


class OpenHumanVidDataset(Dataset):
    """Dataset for OpenHumanVid with filtered CSV."""
    
    def __init__(self, config: DictConfig, split: str = 'train'):
        self.config = config
        self.split = split
        self.csv_path = config.get('csv_path', '/share/st_workspace/openhumanvid_part/csv/OpenHumanVid_filtered.csv')
        # Default resolution if not specified
        res = config.get('resolution', [720, 1280])
        if isinstance(res, ListConfig):
            res = list(res)
        print("🚩###Dataset Res:", res)
        if isinstance(res, (list, tuple)):
            self.sample_size = list(res)
        else:
            self.sample_size = [720, 1280]
            
        self.n_sample_frames = config.get('n_sample_frames', 65)
        
        self.samples = []
        if os.path.exists(self.csv_path):
            import csv
            with open(self.csv_path, 'r', encoding='utf-8') as f:
                reader = csv.reader(f)
                header = next(reader, None) # Skip header
                for row in reader:
                    if len(row) >= 2:
                        self.samples.append({
                            'video_path': row[0],
                            'prompt': row[1]
                        })
        else:
            print(f"⚠️ CSV not found: {self.csv_path}")
            
        print(f"🎯 OpenHumanVidDataset loaded: {len(self.samples)} samples")
        
    def __len__(self):
        return len(self.samples)
        
    def __getitem__(self, idx):
        sample = self.samples[idx]
        video_path = sample['video_path']
        prompt = sample['prompt']
        
        try:
            # Target resolution
            H, W = self.sample_size[0], self.sample_size[1]
            
            video = load_video_rgb_fchw(
                video_path, 
                (W, H), 
                count=self.n_sample_frames,
                accurate_seek=True
            )
            
            if video is None:
                raise ValueError("Video loading returned None")
            
            if video.shape[0] < self.n_sample_frames:
                # Pad with last frame
                pad_len = self.n_sample_frames - video.shape[0]
                last_frame = video[-1:]
                padding = last_frame.repeat(pad_len, 1, 1, 1)
                video = torch.cat([video, padding], dim=0)
            elif video.shape[0] > self.n_sample_frames:
                video = video[:self.n_sample_frames]
                
            return {
                "pixel_values_vid": video,
                "caption_content": prompt,
                "prompt": prompt,
                "video_length": self.n_sample_frames,
                "video_path": video_path
            }
            
        except Exception as e:
            print(f"⚠️ Error loading {video_path}: {e}")
            # Return a dummy sample to avoid crashing
            new_idx = (idx + 1) % len(self)
            return self.__getitem__(new_idx)


class Hallo3VidwTalkingHeadDataset(Dataset):
    """Dataset for local Hallo3 videos and captions.
    
    Expects a directory structure:
        /mnt/nfs/datasets/hallo3_data/videos   # *.mp4 files
        /mnt/nfs/datasets/hallo3_data/caption  # *.txt captions with same base name
    
    Uses `load_video_rgb_fchw` to load a fixed number of frames.
    Samples whose frame count is smaller than `n_sample_frames` are skipped.
    """

    def __init__(self, config: DictConfig, split: str = "train"):
        self.config = config
        self.split = split

        # Roots for videos and captions
        self.video_root = config.get(
            "video_root", "/mnt/nfs/datasets/hallo3_data/videos"
        )
        self.caption_root = config.get(
            "caption_root", "/mnt/nfs/datasets/hallo3_data/caption"
        )
        self.label_root = config.get(
            "label_root", "/mnt/nfs/datasets/hallo3_data/face_parse_labels"
        )

        # Target resolution [H, W]
        res = config.get("resolution", [720, 1072])
        if isinstance(res, ListConfig):
            res = list(res)
        if isinstance(res, (list, tuple)):
            self.sample_size = list(res)
        else:
            self.sample_size = [720, 1072]

        # Fixed resolution for talking-head clips (default 640x640)
        th_res = config.get("talking_head_resolution", [640, 640])
        if isinstance(th_res, ListConfig):
            th_res = list(th_res)
        if isinstance(th_res, (list, tuple)) and len(th_res) == 2:
            self.talking_head_resolution = [int(th_res[0]), int(th_res[1])]
        else:
            self.talking_head_resolution = [640, 640]

        print("🚩###Dataset Res:", self.sample_size)
        # Number of frames per sample
        self.n_sample_frames = config.get("n_sample_frames", 49)

        # Audio / Wav2Vec2 config (follow TAI2V dataset design)
        self.sample_rate = int(config.get("audio_sample_rate", 16000))
        self.processor_model_id = config.get(
            "audio_feature_model_id", "facebook/wav2vec2-base-960h"
        )
        self.processor = Wav2Vec2Processor.from_pretrained(self.processor_model_id)

        # Additional talking-head sources and sampling probability
        talking_head_prob = float(config.get("talking_head_prob", 0.0))
        self.talking_head_prob = min(max(talking_head_prob, 0.0), 1.0)

        th_roots = config.get(
            "talking_head_roots",
            [
                "/mnt/nfs/datasets/celebv_hq/head_talk",
                "/mnt/nfs/datasets/celebv_hq/head_talk_2",
                "/mnt/nfs/datasets/celebv_hq/lip_sync",
                "/mnt/nfs/datasets/celebv_hq/lip_sync_2",
                "/mnt/nfs/datasets/HDTF/clips",
            ],
        )
        if isinstance(th_roots, ListConfig):
            th_roots = list(th_roots)
        self.talking_head_roots = [r for r in th_roots if r]
        self.talking_head_samples = self._collect_talking_head_videos(
            self.talking_head_roots
        )

        sync_c_cfg = config.get("sync_c_threshold", 7.0)
        sync_d_cfg = config.get("sync_d_threshold", 8.0)
        try:
            self.sync_c_threshold = float(sync_c_cfg)
        except (TypeError, ValueError):
            self.sync_c_threshold = 7.0
        try:
            self.sync_d_threshold = float(sync_d_cfg)
        except (TypeError, ValueError):
            self.sync_d_threshold = 8.0

        mode_cfg = config.get("sync_filter_mode", "tag")
        mode = str(mode_cfg).strip().lower()
        if mode not in {"tag", "only_filter"}:
            mode = "tag"
        self.sync_filter_mode = mode

        self.sync_score_path = config.get(
            "sync_score_path",
            "/raid/yt_workspace/TalkingDataProcess/LipSync/hallo3_1208_scores.jsonl",
        )
        self.syncnet_scores = self._load_syncnet_scores(self.sync_score_path)

        self.samples = []
        if os.path.isdir(self.video_root) and os.path.isdir(self.caption_root):
            for name in sorted(os.listdir(self.video_root)):
                if not name.lower().endswith(".mp4"):
                    continue
                video_path = os.path.join(self.video_root, name)
                base, _ = os.path.splitext(name)
                caption_path = os.path.join(self.caption_root, base + ".txt")
                label_path = (
                    _infer_label_path(self.label_root, name)
                    if os.path.isdir(self.label_root)
                    else None
                )
                # Strictly require all three paths to exist at indexing time
                if (
                    os.path.exists(video_path)
                    and os.path.exists(caption_path)
                    and label_path is not None
                    and os.path.exists(label_path)
                ):
                    sync_tag = self._get_sync_tag(video_path)
                    if not self._tag_passes_filter(sync_tag):
                        continue
                    self.samples.append(
                        {
                            "video_path": video_path,
                            "caption_path": caption_path,
                            "label_path": label_path,
                            "sync_tag": sync_tag,
                        }
                    )
        else:
            print(
                f"⚠️ Invalid Hallo3 data roots: "
                f"videos={self.video_root}, captions={self.caption_root}"
            )

        print(
            f"🎯 Hallo3VidDataset indexed: {len(self.samples)} Hallo3 samples, "
            f"{len(self.talking_head_samples)} extra talking-head clips, "
            f"prob={self.talking_head_prob:.2f}"
        )
        self._report_filtered_sync_stats()

    def __len__(self):
        return len(self.samples)

    def _collect_talking_head_videos(self, roots: List[str]) -> List[str]:
        allowed_exts = {".mp4", ".mov", ".mkv", ".avi", ".webm"}
        collected: List[str] = []
        for root in roots:
            if not root or not os.path.isdir(root):
                continue
            for curr_dir, _, files in os.walk(root):
                for name in files:
                    ext = os.path.splitext(name)[1].lower()
                    if ext not in allowed_exts:
                        continue
                    collected.append(os.path.join(curr_dir, name))
        return collected

    def _load_syncnet_scores(self, score_path: Optional[str]) -> dict:
        scores: dict = {}
        if not score_path:
            return scores
        if not os.path.isfile(score_path):
            print(f"⚠️ Sync score file not found: {score_path}")
            return scores

        try:
            with open(score_path, "r", encoding="utf-8") as f:
                for line_idx, line in enumerate(f, 1):
                    line = line.strip()
                    if not line:
                        continue
                    try:
                        record = json.loads(line)
                    except json.JSONDecodeError as e:
                        print(
                            f"⚠️ Failed to parse sync score line {line_idx} in "
                            f"{score_path}: {e}"
                        )
                        continue

                    video_path = record.get("video")
                    if not video_path:
                        continue
                    normalized_path = os.path.abspath(os.path.realpath(video_path))
                    sync_c = record.get("sync_c_score")
                    sync_d = record.get("sync_d_score")
                    scores[normalized_path] = {
                        "sync_c_score": sync_c,
                        "sync_d_score": sync_d,
                        "tag": self._evaluate_sync_tag(sync_c, sync_d),
                    }
        except Exception as e:
            print(f"⚠️ Failed to load sync scores from {score_path}: {e}")
            return {}

        print(f"🎯 Loaded {len(scores)} sync entries from {score_path}")
        return scores

    def _evaluate_sync_tag(
        self, sync_c_score: Optional[float], sync_d_score: Optional[float]
    ) -> str:
        try:
            sync_c = float(sync_c_score)
            sync_d = float(sync_d_score)
        except (TypeError, ValueError):
            return "I"

        if sync_c > self.sync_c_threshold and sync_d < self.sync_d_threshold:
            return "A"
        return "I"

    def _get_sync_tag(self, video_path: Optional[str]) -> str:
        if not video_path:
            return "I"
        normalized_path = os.path.abspath(os.path.realpath(video_path))
        entry = self.syncnet_scores.get(normalized_path)
        if entry is None:
            return "I"
        return entry.get("tag", "I") or "I"

    def _tag_passes_filter(self, tag: str) -> bool:
        if self.sync_filter_mode == "only_filter":
            return tag == "A"
        return True

    def _report_filtered_sync_stats(self) -> None:
        filtered_entries = [
            entry
            for entry in self.syncnet_scores.values()
            if entry.get("tag") == "A"
        ]

        def _collect_values(key: str) -> List[float]:
            values: List[float] = []
            for entry in filtered_entries:
                try:
                    values.append(float(entry.get(key)))
                except (TypeError, ValueError):
                    continue
            return values

        def _format_stats(values: List[float]) -> tuple[int, float, float, float]:
            if not values:
                return 0, float("nan"), float("nan"), float("nan")
            count = len(values)
            return count, min(values), max(values), sum(values) / count

        c_values = _collect_values("sync_c_score")
        d_values = _collect_values("sync_d_score")

        c_count, c_min, c_max, c_mean = _format_stats(c_values)
        d_count, d_min, d_max, d_mean = _format_stats(d_values)

        print(
            f"📊 Filtered sync_c_score: count={c_count}, min={c_min:.3f}, max={c_max:.3f}, mean={c_mean:.3f}"
        )
        print(
            f"📊 Filtered sync_d_score: count={d_count}, min={d_min:.3f}, max={d_max:.3f}, mean={d_mean:.3f}"
        )

    def _getitem_talking_head(self) -> Optional[dict]:
        if not self.talking_head_samples:
            return None

        num_trials = min(8, len(self.talking_head_samples))
        th_H, th_W = self.talking_head_resolution[0], self.talking_head_resolution[1]

        for _ in range(num_trials):
            sample_idx = random.randint(0, len(self.talking_head_samples) - 1)
            video_path = self.talking_head_samples[sample_idx]

            try:
                vr = VideoReader(video_path)
                total_frames = len(vr)
                if total_frames < self.n_sample_frames:
                    continue

                max_start = total_frames - self.n_sample_frames
                start = random.randint(0, max_start) if max_start > 0 else 0

                video = load_video_rgb_fchw(
                    video_path,
                    (th_W, th_H),
                    start=start,
                    count=self.n_sample_frames,
                    accurate_seek=True,
                )

                if video is None or video.shape[0] < self.n_sample_frames:
                    continue
                if video.shape[0] > self.n_sample_frames:
                    video = video[: self.n_sample_frames]

                try:
                    fps = float(vr.get_avg_fps())
                    if not np.isfinite(fps) or fps <= 0:
                        fps = 25.0
                except Exception:
                    fps = 25.0

                audio_waveform, _ = librosa.load(
                    video_path, sr=self.sample_rate, mono=True
                )
                if audio_waveform.size == 0:
                    continue

                clip_start_time = start / fps
                clip_duration = self.n_sample_frames / fps
                clip_end_time = clip_start_time + clip_duration

                start_sample = int(max(0, clip_start_time * self.sample_rate))
                end_sample = int(max(start_sample, clip_end_time * self.sample_rate))
                end_sample = min(end_sample, audio_waveform.shape[0])

                audio_clip = audio_waveform[start_sample:end_sample]
                if audio_clip.size == 0:
                    audio_clip = audio_waveform
                if audio_clip.size == 0 or _is_audio_silent(audio_clip):
                    continue

                audio_input_values = self.processor(
                    audio_clip,
                    sampling_rate=self.sample_rate,
                    return_tensors="pt",
                ).input_values[0]

                face_mask = torch.zeros(
                    (
                        self.n_sample_frames,
                        1,
                        th_H,
                        th_W,
                    ),
                    dtype=torch.float32,
                )

                caption = "a talking head video"

                sync_tag = self._get_sync_tag(video_path)
                if not self._tag_passes_filter(sync_tag):
                    continue

                return {
                    "pixel_values_vid": video,
                    "face_mask": face_mask,
                    "caption_content": caption,
                    "prompt": caption,
                    "video_length": self.n_sample_frames,
                    "video_path": video_path,
                    "audio_input_values": audio_input_values,
                    "audio_sample_rate": self.sample_rate,
                    "audio_num_samples": int(audio_clip.shape[0]),
                    "sync_tag": sync_tag,
                }

            except Exception as e:
                print(f"⚠️ Error loading talking-head clip {video_path}: {e}")
                continue

        return None

    def _load_caption(self, caption_path: str) -> str:
        try:
            with open(caption_path, "r", encoding="utf-8") as f:
                text = f.read()
            return text.strip()
        except Exception as e:
            print(f"⚠️ Failed to read caption {caption_path}: {e}")
            return ""

    def __getitem__(self, idx):
        if len(self.samples) == 0:
            raise IndexError("Hallo3VidDataset has no samples")

        if (
            self.talking_head_prob > 0
            and self.talking_head_samples
            and random.random() < self.talking_head_prob
        ):
            talking_head_sample = self._getitem_talking_head()
            if talking_head_sample is not None:
                return talking_head_sample

        # Try a few times in case of short or broken videos
        num_trials = min(8, len(self.samples))
        for _ in range(num_trials):
            sample = self.samples[idx]
            video_path = sample["video_path"]
            caption_path = sample["caption_path"]
            label_path = sample["label_path"]
            sync_tag = sample.get("sync_tag", self._get_sync_tag(video_path))
            if not self._tag_passes_filter(sync_tag):
                idx = (idx + 1) % len(self.samples)
                continue

            try:
                # Read face-parse label video and compute lip bboxes
                labels = _read_labels_from_video(label_path)
                if labels is None or labels.ndim != 3:
                    print(f"⚠️ Skipping {video_path}: failed to read labels {label_path}")
                    idx = (idx + 1) % len(self.samples)
                    continue

                T_lab, H_lab, W_lab = labels.shape
                if T_lab < self.n_sample_frames:
                    print(
                        f"⚠️ Skipping {video_path}: "
                        f"label_frames={T_lab}, required={self.n_sample_frames}"
                    )
                    idx = (idx + 1) % len(self.samples)
                    continue

                bboxes = _compute_lip_bboxes(labels)
                if not any(bb is not None for bb in bboxes):
                    print(f"⚠️ Skipping {video_path}: no valid lip bboxes in labels")
                    idx = (idx + 1) % len(self.samples)
                    continue

                # Probe total frame count of original video
                vr = VideoReader(video_path)
                total_frames = len(vr)

                # Both label and video must have enough frames
                max_start_total = min(total_frames, T_lab) - self.n_sample_frames
                if max_start_total < 0:
                    print(
                        f"⚠️ Skipping {video_path}: "
                        f"video_frames={total_frames}, label_frames={T_lab}, "
                        f"required={self.n_sample_frames}"
                    )
                    idx = (idx + 1) % len(self.samples)
                    continue

                # Randomly choose a valid start index shared by video and labels
                if max_start_total > 0:
                    start = int(
                        torch.randint(
                            0, max_start_total + 1, (1,), dtype=torch.int64
                        ).item()
                    )
                else:
                    start = 0

                H, W = self.sample_size[0], self.sample_size[1]

                video = load_video_rgb_fchw(
                    video_path,
                    (W, H),
                    start=start,
                    count=self.n_sample_frames,
                    accurate_seek=True,
                )

                # Skip samples that fail to load or are too short
                if video is None or video.shape[0] < self.n_sample_frames:
                    print(
                        f"⚠️ Skipping {video_path}: "
                        f"frames={0 if video is None else video.shape[0]}, "
                        f"required={self.n_sample_frames}"
                    )
                    idx = (idx + 1) % len(self.samples)
                    continue

                # If more frames were returned, truncate to requested count
                if video.shape[0] > self.n_sample_frames:
                    video = video[: self.n_sample_frames]

                # Audio clip aligned to the sampled RGB window
                try:
                    fps = float(vr.get_avg_fps())
                    if not np.isfinite(fps) or fps <= 0:
                        fps = 25.0
                except Exception:
                    fps = 25.0

                # Read mono audio, resampled to dataset sample_rate
                audio_waveform, _ = librosa.load(
                    video_path, sr=self.sample_rate, mono=True
                )

                # Map frame window [start, start + n_sample_frames) to audio samples
                clip_start_time = start / fps
                clip_duration = self.n_sample_frames / fps
                clip_end_time = clip_start_time + clip_duration

                start_sample = int(max(0, clip_start_time * self.sample_rate))
                end_sample = int(max(start_sample, clip_end_time * self.sample_rate))
                end_sample = min(end_sample, audio_waveform.shape[0])

                audio_clip = audio_waveform[start_sample:end_sample]
                if audio_clip.size == 0:
                    audio_clip = audio_waveform

                # Skip silent audio clips
                if _is_audio_silent(audio_clip):
                    print(f"⚠️ Skipping {video_path}: audio clip is silent")
                    idx = (idx + 1) % len(self.samples)
                    continue

                audio_input_values = self.processor(
                    audio_clip,
                    sampling_rate=self.sample_rate,
                    return_tensors="pt",
                ).input_values[0]

                # Build lip-region mask from bboxes and align to sampled window / resolution
                bboxes_window = bboxes[start : start + self.n_sample_frames]
                masks_lab = _bboxes_to_masks(bboxes_window, H_lab, W_lab)  # (F, H_lab, W_lab)

                # Resize masks to match video resolution if needed
                if (H_lab, W_lab) != (H, W):
                    resized_masks = np.zeros(
                        (self.n_sample_frames, H, W), dtype=np.float32
                    )
                    for i in range(self.n_sample_frames):
                        resized_masks[i] = cv2.resize(
                            masks_lab[i],
                            (W, H),
                            interpolation=cv2.INTER_NEAREST,
                        )
                    masks_lab = resized_masks

                face_mask = torch.from_numpy(masks_lab).unsqueeze(1).float()

                caption = self._load_caption(caption_path)

                return {
                    "pixel_values_vid": video,  # [F, C, H, W] in [-1, 1]
                    "face_mask": face_mask,  # [F, 1, H, W], 1 inside lip bbox, 0 outside
                    "caption_content": caption,
                    "prompt": caption,
                    "video_length": self.n_sample_frames,
                    "video_path": video_path,
                    "audio_input_values": audio_input_values,
                    "audio_sample_rate": self.sample_rate,
                    "audio_num_samples": int(audio_clip.shape[0]),
                    "sync_tag": sync_tag,
                }

            except Exception as e:
                print(f"⚠️ Error loading {video_path}: {e}")
                idx = (idx + 1) % len(self.samples)
                continue

        # If all trials fail, raise to signal issue upstream
        raise RuntimeError("No valid Hallo3 samples with sufficient frames found.")