wanfall / wanfall.py
simplexsigil2's picture
Upload folder using huggingface_hub
3d97c3d verified
"""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