File size: 25,992 Bytes
88dbfe7
 
 
 
 
 
 
 
 
 
 
3d97c3d
 
 
 
88dbfe7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d97c3d
88dbfe7
3d97c3d
88dbfe7
 
 
3d97c3d
88dbfe7
 
 
3d97c3d
88dbfe7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d97c3d
 
 
 
 
 
 
88dbfe7
 
 
 
 
 
 
 
 
 
3d97c3d
 
88dbfe7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d97c3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88dbfe7
 
 
3d97c3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88dbfe7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d97c3d
 
88dbfe7
 
 
 
 
 
 
3d97c3d
 
88dbfe7
 
3d97c3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88dbfe7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""WanFall: A Synthetic Activity Recognition Dataset

This dataset builder provides access to the WanFall synthetic activity recognition dataset,
featuring 12,000 videos with dense temporal annotations across 16 activity classes.

The dataset includes rich demographic and scene metadata, enabling research in fair and
robust activity recognition across diverse populations.
"""

import pandas as pd
import datasets
from datasets import BuilderConfig, GeneratorBasedBuilder, Features, Value, ClassLabel, SplitGenerator, Split, Sequence
import h5py
import tarfile
from pathlib import Path


# Dataset metadata
_CITATION = """\
TBD
"""

_DESCRIPTION = """\
WanFall is a large-scale synthetic activity recognition dataset designed for fall detection
and activities of daily living research. The dataset features computer-generated videos of
human actors performing various activities in controlled virtual environments.

**Key Features:**
- 12,000 video clips with dense temporal annotations
- 16 activity classes including falls, posture transitions, and static states
- 19,228 temporal segments with frame-level precision
- 5.0625 seconds per video clip (81 frames @ 16 fps)
- Rich demographic metadata (soft labels): age, gender, ethnicity, body type, height, skin tone
- Scene attributes: environment, camera angle, frame rate
- Multiple evaluation splits: random (80/10/10) and cross-demographic (age, ethnicity, BMI)

**Use Cases:**
- Fall detection research
- Activity recognition with temporal segmentation
- Bias and fairness analysis across demographics
- Cross-demographic generalization studies
"""

_HOMEPAGE = "https://huggingface.co/datasets/simplexsigil2/wanfall"
_LICENSE = "cc-by-nc-4.0"

# Activity class labels (16 classes)
_ACTIVITY_LABELS = [
    "walk",         # 0: Walking movement
    "fall",         # 1: Falling down action
    "fallen",       # 2: Person on ground after fall
    "sit_down",     # 3: Transitioning to sitting
    "sitting",      # 4: Stationary sitting posture
    "lie_down",     # 5: Intentionally lying down
    "lying",        # 6: Stationary lying posture
    "stand_up",     # 7: Rising, mostly to standing, but also from lying to sitting.
    "standing",     # 8: Stationary standing posture
    "other",        # 9: Unclassified activities
    "kneel_down",   # 10: Transitioning to kneeling
    "kneeling",     # 11: Stationary kneeling posture
    "squat_down",   # 12: Transitioning to squatting
    "squatting",    # 13: Stationary squatting posture
    "crawl",        # 14: Crawling movement
    "jump",         # 15: Jumping action
]

# Demographic and scene metadata categories
_AGE_GROUPS = ["toddlers_1_4", "children_5_12", "teenagers_13_17",
               "young_adults_18_34", "middle_aged_35_64", "elderly_65_plus"]
_GENDERS = ["male", "female"]
_SKIN_TONES = [f"mst{i}" for i in range(1, 11)]  # Monk Skin Tone scale (1-10)
_ETHNICITIES = ["white", "black", "asian", "hispanic_latino", "aian", "nhpi", "mena"]
_BMI_BANDS = ["underweight", "normal", "overweight", "obese"]
_HEIGHT_BANDS = ["short", "avg", "tall"]
_ENVIRONMENTS = ["indoor", "outdoor"]
_CAMERA_ELEVATIONS = ["eye", "low", "high", "top"]
_CAMERA_AZIMUTHS = ["front", "rear", "left", "right"]
_CAMERA_DISTANCES = ["medium", "far"]
_CAMERA_SHOTS = ["static_wide", "static_medium_wide"]
_SPEEDS = ["24fps_rt", "25fps_rt", "30fps_rt", "std_rt"]


class WanFallConfig(BuilderConfig):
    """BuilderConfig for WanFall dataset.

    Args:
        split_type: Type of data to load ("labels", "metadata", "framewise", or split name like "random")
        paths_only: If True, only return video paths for split configs (no label merging)
        framewise: If True, load frame-wise labels from HDF5 files (81 labels per video)
        **kwargs: Keyword arguments forwarded to super.
    """

    def __init__(self, split_type="labels", paths_only=False, framewise=False, **kwargs):
        super().__init__(**kwargs)
        self.split_type = split_type
        self.paths_only = paths_only
        self.framewise = framewise


class WanFall(GeneratorBasedBuilder):
    """WanFall synthetic activity recognition dataset builder."""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIG_CLASS = WanFallConfig
    BUILDER_CONFIGS = [
        WanFallConfig(
            name="labels",
            version=VERSION,
            description="All temporal segment labels with metadata (19,228 segments)",
            split_type="labels",
        ),
        WanFallConfig(
            name="metadata",
            version=VERSION,
            description="Video-level metadata without temporal segments (12,000 videos)",
            split_type="metadata",
        ),
        WanFallConfig(
            name="random",
            version=VERSION,
            description="Random 80/10/10 train/val/test split",
            split_type="random",
        ),
        WanFallConfig(
            name="cross_age",
            version=VERSION,
            description="Cross-age evaluation: train on young/middle-aged, test on children/elderly",
            split_type="cross_age",
        ),
        WanFallConfig(
            name="cross_ethnicity",
            version=VERSION,
            description="Cross-ethnicity evaluation: train on white/asian/hispanic, test on black/mena/nhpi",
            split_type="cross_ethnicity",
        ),
        WanFallConfig(
            name="cross_bmi",
            version=VERSION,
            description="Cross-BMI evaluation: train on normal/underweight, test on obese",
            split_type="cross_bmi",
        ),
        WanFallConfig(
            name="framewise",
            version=VERSION,
            description="Frame-wise labels for all videos (81 labels per video, one per frame)",
            split_type="framewise",
            framewise=True,
        ),
    ]

    DEFAULT_CONFIG_NAME = "random"

    def _info(self):
        """Specify dataset metadata and features schema."""

        # Define features based on config type
        if self.config.split_type == "metadata":
            features = self._get_metadata_features()
        elif self.config.framewise:
            features = self._get_framewise_features()
        elif self.config.paths_only:
            features = self._get_paths_only_features()
        else:
            features = self._get_full_features()

        # Create id2label and label2id mappings
        id2label = {i: label for i, label in enumerate(_ACTIVITY_LABELS)}
        label2id = {label: i for i, label in enumerate(_ACTIVITY_LABELS)}

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
            # Note: Label mappings are accessible via dataset.info.features["label"].names
        )

    def _get_full_features(self):
        """Complete feature schema with all 19 fields (temporal segments + metadata)."""
        return Features({
            # Core identity and temporal fields
            "path": Value("string"),
            "label": ClassLabel(num_classes=16, names=_ACTIVITY_LABELS),
            "start": Value("float32"),
            "end": Value("float32"),
            "subject": Value("int32"),  # -1 for WanFall (no subject tracking)
            "cam": Value("int32"),      # -1 for WanFall (single view)
            "dataset": Value("string"), # "wanfall" constant

            # Demographic metadata
            "age_group": ClassLabel(num_classes=6, names=_AGE_GROUPS),
            "gender_presentation": ClassLabel(num_classes=2, names=_GENDERS),
            "monk_skin_tone": ClassLabel(num_classes=10, names=_SKIN_TONES),
            "race_ethnicity_omb": ClassLabel(num_classes=7, names=_ETHNICITIES),
            "bmi_band": ClassLabel(num_classes=4, names=_BMI_BANDS),
            "height_band": ClassLabel(num_classes=3, names=_HEIGHT_BANDS),

            # Scene metadata
            "environment_category": ClassLabel(num_classes=2, names=_ENVIRONMENTS),
            "camera_shot": ClassLabel(num_classes=2, names=_CAMERA_SHOTS),
            "speed": ClassLabel(num_classes=4, names=_SPEEDS),
            "camera_elevation": ClassLabel(num_classes=4, names=_CAMERA_ELEVATIONS),
            "camera_azimuth": ClassLabel(num_classes=4, names=_CAMERA_AZIMUTHS),
            "camera_distance": ClassLabel(num_classes=2, names=_CAMERA_DISTANCES),
        })

    def _get_metadata_features(self):
        """Feature schema for metadata config (video-level, no temporal segments)."""
        return Features({
            # Core identity (no temporal fields)
            "path": Value("string"),
            "dataset": Value("string"),

            # Demographic metadata
            "age_group": ClassLabel(num_classes=6, names=_AGE_GROUPS),
            "gender_presentation": ClassLabel(num_classes=2, names=_GENDERS),
            "monk_skin_tone": ClassLabel(num_classes=10, names=_SKIN_TONES),
            "race_ethnicity_omb": ClassLabel(num_classes=7, names=_ETHNICITIES),
            "bmi_band": ClassLabel(num_classes=4, names=_BMI_BANDS),
            "height_band": ClassLabel(num_classes=3, names=_HEIGHT_BANDS),

            # Scene metadata
            "environment_category": ClassLabel(num_classes=2, names=_ENVIRONMENTS),
            "camera_shot": ClassLabel(num_classes=2, names=_CAMERA_SHOTS),
            "speed": ClassLabel(num_classes=4, names=_SPEEDS),
            "camera_elevation": ClassLabel(num_classes=4, names=_CAMERA_ELEVATIONS),
            "camera_azimuth": ClassLabel(num_classes=4, names=_CAMERA_AZIMUTHS),
            "camera_distance": ClassLabel(num_classes=2, names=_CAMERA_DISTANCES),
        })

    def _get_paths_only_features(self):
        """Minimal feature schema for paths-only mode."""
        return Features({
            "path": Value("string"),
        })

    def _get_framewise_features(self):
        """Feature schema for frame-wise labels (81 labels per video)."""
        return Features({
            # Core identity
            "path": Value("string"),
            "dataset": Value("string"),

            # Frame-wise labels (81 frames @ 16fps = 5.0625 seconds)
            "frame_labels": Sequence(ClassLabel(num_classes=16, names=_ACTIVITY_LABELS), length=81),

            # Demographic metadata (same as metadata config)
            "age_group": ClassLabel(num_classes=6, names=_AGE_GROUPS),
            "gender_presentation": ClassLabel(num_classes=2, names=_GENDERS),
            "monk_skin_tone": ClassLabel(num_classes=10, names=_SKIN_TONES),
            "race_ethnicity_omb": ClassLabel(num_classes=7, names=_ETHNICITIES),
            "bmi_band": ClassLabel(num_classes=4, names=_BMI_BANDS),
            "height_band": ClassLabel(num_classes=3, names=_HEIGHT_BANDS),

            # Scene metadata
            "environment_category": ClassLabel(num_classes=2, names=_ENVIRONMENTS),
            "camera_shot": ClassLabel(num_classes=2, names=_CAMERA_SHOTS),
            "speed": ClassLabel(num_classes=4, names=_SPEEDS),
            "camera_elevation": ClassLabel(num_classes=4, names=_CAMERA_ELEVATIONS),
            "camera_azimuth": ClassLabel(num_classes=4, names=_CAMERA_AZIMUTHS),
            "camera_distance": ClassLabel(num_classes=2, names=_CAMERA_DISTANCES),
        })

    def _split_generators(self, dl_manager):
        """Define data splits and their source files."""

        # Handle framewise config - needs to download and extract HDF5 files
        if self.config.framewise:
            # Download the frame-wise labels archive
            archive_path = dl_manager.download_and_extract("data_files/frame_wise_labels.tar.zst")

            # If split_type is "framewise", return all videos in one split
            if self.config.split_type == "framewise":
                return [
                    SplitGenerator(
                        name=Split.TRAIN,
                        gen_kwargs={
                            "hdf5_dir": archive_path,
                            "metadata_path": "videos/metadata.csv",
                            "split_file": None,
                        },
                    ),
                ]
            # Otherwise, use split files (random, cross_age, etc.)
            else:
                split_dir = f"splits/{self.config.split_type}"
                return [
                    SplitGenerator(
                        name=Split.TRAIN,
                        gen_kwargs={
                            "hdf5_dir": archive_path,
                            "metadata_path": "videos/metadata.csv",
                            "split_file": f"{split_dir}/train.csv",
                        },
                    ),
                    SplitGenerator(
                        name=Split.VALIDATION,
                        gen_kwargs={
                            "hdf5_dir": archive_path,
                            "metadata_path": "videos/metadata.csv",
                            "split_file": f"{split_dir}/val.csv",
                        },
                    ),
                    SplitGenerator(
                        name=Split.TEST,
                        gen_kwargs={
                            "hdf5_dir": archive_path,
                            "metadata_path": "videos/metadata.csv",
                            "split_file": f"{split_dir}/test.csv",
                        },
                    ),
                ]

        # Handle different config types
        if self.config.split_type == "labels":
            # Labels config: single split with all temporal segments
            return [
                SplitGenerator(
                    name=Split.TRAIN,
                    gen_kwargs={
                        "filepath": "labels/wanfall.csv",
                        "split_name": "labels",
                    },
                ),
            ]

        elif self.config.split_type == "metadata":
            # Metadata config: single split with video-level metadata
            return [
                SplitGenerator(
                    name=Split.TRAIN,
                    gen_kwargs={
                        "filepath": "videos/metadata.csv",
                        "split_name": "metadata",
                    },
                ),
            ]

        else:
            # Split configs (random, cross_age, cross_ethnicity, cross_bmi)
            split_dir = f"splits/{self.config.split_type}"

            # If paths_only mode, just load split files
            # Otherwise, we need both split files and labels for merging
            base_kwargs = {
                "split_dir": split_dir,
                "labels_path": "labels/wanfall.csv" if not self.config.paths_only else None,
            }

            return [
                SplitGenerator(
                    name=Split.TRAIN,
                    gen_kwargs={
                        **base_kwargs,
                        "split_file": f"{split_dir}/train.csv",
                        "split_name": "train",
                    },
                ),
                SplitGenerator(
                    name=Split.VALIDATION,
                    gen_kwargs={
                        **base_kwargs,
                        "split_file": f"{split_dir}/val.csv",
                        "split_name": "val",
                    },
                ),
                SplitGenerator(
                    name=Split.TEST,
                    gen_kwargs={
                        **base_kwargs,
                        "split_file": f"{split_dir}/test.csv",
                        "split_name": "test",
                    },
                ),
            ]

    def _generate_examples(self, filepath=None, split_file=None, labels_path=None,
                          split_name=None, split_dir=None, hdf5_dir=None, metadata_path=None):
        """Generate examples from CSV files or HDF5 files.

        Args:
            filepath: Direct path to CSV file (for labels/metadata configs)
            split_file: Path to split file containing video paths (for split configs)
            labels_path: Path to labels file for merging (for split configs with full data)
            split_name: Name of the split being generated
            split_dir: Directory containing split files
            hdf5_dir: Directory containing extracted HDF5 files (for framewise config)
            metadata_path: Path to metadata CSV (for framewise config)
        """

        # Case 0: Frame-wise labels from HDF5 files
        if hdf5_dir is not None:
            # Load metadata
            metadata_df = pd.read_csv(metadata_path)

            # If split_file is provided, load the video paths for this split
            valid_paths = None
            if split_file is not None:
                split_df = pd.read_csv(split_file)
                valid_paths = set(split_df['path'].tolist())

            # hdf5_dir might be a tar file (if zst extraction only decompressed to tar)
            # Check if it's a tar file and handle appropriately
            hdf5_path = Path(hdf5_dir)

            if hdf5_path.is_file() and (hdf5_path.suffix == '.tar' or tarfile.is_tarfile(str(hdf5_path))):
                # It's a tar file - iterate through it directly
                idx = 0
                with tarfile.open(hdf5_path, 'r') as tar:
                    for member in tar.getmembers():
                        if not member.name.endswith('.h5'):
                            continue

                        # Extract path from tar member name
                        # e.g., "./lie_down/lie_down_yo_076.h5" or "lie_down/lie_down_yo_076.h5"
                        video_path = member.name.lstrip('./').replace('.h5', '')

                        # Skip if not in this split
                        if valid_paths is not None and video_path not in valid_paths:
                            continue

                        try:
                            # Extract H5 file to memory
                            h5_file = tar.extractfile(member)
                            if h5_file is None:
                                continue

                            # h5py can't read from file-like object directly, need temp file
                            import tempfile
                            with tempfile.NamedTemporaryFile(suffix='.h5', delete=True) as tmp:
                                tmp.write(h5_file.read())
                                tmp.flush()

                                with h5py.File(tmp.name, 'r') as f:
                                    frame_labels = f['label_indices'][:].tolist()

                            # Get metadata for this video
                            video_metadata = metadata_df[metadata_df['path'] == video_path]

                            if len(video_metadata) == 0:
                                continue

                            video_meta = video_metadata.iloc[0]

                            # Create example
                            example = {
                                "path": video_path,
                                "dataset": "wanfall",
                                "frame_labels": frame_labels,
                            }

                            # Add metadata fields
                            metadata_fields = [
                                "age_group", "gender_presentation", "monk_skin_tone",
                                "race_ethnicity_omb", "bmi_band", "height_band",
                                "environment_category", "camera_shot", "speed",
                                "camera_elevation", "camera_azimuth", "camera_distance"
                            ]
                            for field in metadata_fields:
                                if field in video_meta and pd.notna(video_meta[field]):
                                    example[field] = str(video_meta[field])

                            yield idx, example
                            idx += 1

                        except Exception as e:
                            print(f"Warning: Failed to process {member.name}: {e}")
                            continue
            else:
                # It's a directory - glob for H5 files
                hdf5_files = sorted(hdf5_path.glob("**/*.h5"))

                idx = 0
                for h5_file in hdf5_files:
                    relative_path = h5_file.relative_to(hdf5_path)
                    video_path = str(relative_path.with_suffix(''))

                    # Skip if not in this split
                    if valid_paths is not None and video_path not in valid_paths:
                        continue

                    try:
                        with h5py.File(h5_file, 'r') as f:
                            frame_labels = f['label_indices'][:].tolist()

                        video_metadata = metadata_df[metadata_df['path'] == video_path]

                        if len(video_metadata) == 0:
                            continue

                        video_meta = video_metadata.iloc[0]

                        example = {
                            "path": video_path,
                            "dataset": "wanfall",
                            "frame_labels": frame_labels,
                        }

                        metadata_fields = [
                            "age_group", "gender_presentation", "monk_skin_tone",
                            "race_ethnicity_omb", "bmi_band", "height_band",
                            "environment_category", "camera_shot", "speed",
                            "camera_elevation", "camera_azimuth", "camera_distance"
                        ]
                        for field in metadata_fields:
                            if field in video_meta and pd.notna(video_meta[field]):
                                example[field] = str(video_meta[field])

                        yield idx, example
                        idx += 1

                    except Exception as e:
                        print(f"Warning: Failed to process {h5_file}: {e}")
                        continue

            return

        # Case 1: Direct file loading (labels or metadata config)
        if filepath is not None:
            df = pd.read_csv(filepath)

            # For metadata config, filter out temporal segment columns if they exist
            if self.config.split_type == "metadata":
                # Keep only metadata columns (exclude label, start, end, subject, cam if present)
                metadata_cols = ["path", "age_group", "gender_presentation",
                               "monk_skin_tone", "race_ethnicity_omb", "bmi_band", "height_band",
                               "environment_category", "camera_shot", "speed",
                               "camera_elevation", "camera_azimuth", "camera_distance"]
                # Only keep columns that exist in the dataframe
                available_cols = [col for col in metadata_cols if col in df.columns]
                df = df[available_cols].drop_duplicates(subset=["path"]).reset_index(drop=True)
                # Add dataset column manually
                df["dataset"] = "wanfall"

            # Yield examples
            for idx, row in df.iterrows():
                yield idx, self._row_to_example(row)

        # Case 2: Split file loading with optional merging
        elif split_file is not None:
            # Load split paths
            split_df = pd.read_csv(split_file)

            # Paths-only mode: just return paths
            if self.config.paths_only or labels_path is None:
                for idx, row in split_df.iterrows():
                    yield idx, {"path": row["path"]}

            # Full mode: merge with labels
            else:
                # Load all labels
                labels_df = pd.read_csv(labels_path)

                # Merge split paths with labels
                merged_df = pd.merge(split_df, labels_df, on="path", how="left")

                # Yield examples
                for idx, row in merged_df.iterrows():
                    yield idx, self._row_to_example(row)

    def _row_to_example(self, row):
        """Convert a DataFrame row to an example dictionary with proper types.

        Args:
            row: pandas Series representing one row

        Returns:
            Dictionary with properly typed values for the features schema
        """
        example = {}

        # Always include path
        example["path"] = str(row["path"])

        # Include fields based on what's available in the row
        if "label" in row and pd.notna(row["label"]):
            example["label"] = int(row["label"])

        if "start" in row and pd.notna(row["start"]):
            example["start"] = float(row["start"])

        if "end" in row and pd.notna(row["end"]):
            example["end"] = float(row["end"])

        if "subject" in row and pd.notna(row["subject"]):
            example["subject"] = int(row["subject"])

        if "cam" in row and pd.notna(row["cam"]):
            example["cam"] = int(row["cam"])

        if "dataset" in row and pd.notna(row["dataset"]):
            example["dataset"] = str(row["dataset"])

        # Demographic metadata (categorical - keep as strings, ClassLabel handles conversion)
        demographic_fields = [
            "age_group", "gender_presentation", "monk_skin_tone",
            "race_ethnicity_omb", "bmi_band", "height_band"
        ]
        for field in demographic_fields:
            if field in row and pd.notna(row[field]):
                example[field] = str(row[field])

        # Scene metadata (categorical)
        scene_fields = [
            "environment_category", "camera_shot", "speed",
            "camera_elevation", "camera_azimuth", "camera_distance"
        ]
        for field in scene_fields:
            if field in row and pd.notna(row[field]):
                example[field] = str(row[field])

        return example