popsign-images / create_dataset.py
AmitMY's picture
Create create_dataset.py
20da4cb verified
#!/usr/bin/env python3
"""
Create a HuggingFace dataset from PopSign data.
This script reads PopSign game and non-game subsets, extracts frames from videos
at signing segments, and creates a HuggingFace-compatible dataset with images.
"""
import argparse
import csv
import io
import json
import os
import pickle
import shutil
import tarfile
from functools import partial
from multiprocessing import Pool, cpu_count
from pathlib import Path
import cv2
import pympi
from datasets import Dataset, DatasetDict, Features, Image, Sequence, Value
from PIL import Image as PILImage
from tqdm import tqdm
from pose_utils import get_signing_time_range_from_pose
# Path to the README template
README_TEMPLATE_PATH = Path(__file__).parent / "popsign-images" / "README.md"
def get_video_duration(video_path: str) -> float:
"""Get the duration of a video in seconds."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError(f"Could not open video: {video_path}")
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)
cap.release()
if fps <= 0:
raise ValueError(f"Invalid FPS for video: {video_path}")
return frame_count / fps
def get_video_fps(video_path: str) -> float:
"""Get the FPS of a video."""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError(f"Could not open video: {video_path}")
fps = cap.get(cv2.CAP_PROP_FPS)
cap.release()
return fps
def get_sign_time_range_from_eaf(eaf_path: str) -> tuple[float, float] | None:
"""
Get the time range of the largest sign segment from an EAF file.
Returns:
Tuple of (start_time, end_time) in seconds, or None if no segments found.
"""
try:
eaf = pympi.Elan.Eaf(file_path=eaf_path)
if 'SIGN' not in eaf.get_tier_names():
return None
sign_annotations = eaf.get_annotation_data_for_tier('SIGN')
if not sign_annotations:
return None
# Find the largest segment
largest_segment = max(sign_annotations, key=lambda s: s[1] - s[0])
start_time = largest_segment[0] / 1000 # Convert ms to seconds
end_time = largest_segment[1] / 1000
return start_time, end_time
except Exception:
return None
def extract_frames_from_video(
video_path: str,
start_time: float,
end_time: float,
target_fps: float = 5,
frame_size: int = 256
) -> list[PILImage.Image]:
"""
Extract frames from a video between start and end times.
Args:
video_path: Path to the video file
start_time: Start time in seconds
end_time: End time in seconds
target_fps: Target frames per second to extract
frame_size: Size to resize frames to (square)
Returns:
List of PIL Images
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise ValueError(f"Could not open video: {video_path}")
fps = cap.get(cv2.CAP_PROP_FPS)
if fps <= 0:
cap.release()
raise ValueError(f"Invalid FPS for video: {video_path}")
duration = end_time - start_time
num_frames = max(2, int(duration * target_fps))
# Calculate frame indices to extract
start_frame = int(start_time * fps)
end_frame = int(end_time * fps)
duration_frames = end_frame - start_frame
if duration_frames <= 0:
cap.release()
return []
# Sample frames evenly across the duration
if num_frames >= duration_frames:
frame_indices = list(range(start_frame, end_frame + 1))
else:
frame_indices = [
start_frame + int(i * duration_frames / (num_frames - 1))
for i in range(num_frames - 1)
]
frame_indices.append(end_frame)
frames = []
for frame_num in frame_indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
ret, frame = cap.read()
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = PILImage.fromarray(frame_rgb)
# Resize if needed (videos should already be 256x256)
if img.size != (frame_size, frame_size):
img = img.resize((frame_size, frame_size), PILImage.Resampling.LANCZOS)
frames.append(img)
cap.release()
return frames
def process_csv_row(
row: dict,
videos_dir: str,
eaf_dir: str,
pose_dir: str,
target_fps: float = 5
) -> dict | None:
"""
Process a single CSV row and return a dataset entry.
Uses a cascading approach for segmentation:
1. First try pose-based segmentation (wrist above elbow heuristic)
2. If pose covers entire file, fall back to EAF segmentation
3. If neither works, use full video duration
Args:
row: CSV row dictionary
videos_dir: Directory containing 256x256 videos
eaf_dir: Directory containing EAF files
pose_dir: Directory containing pose files
target_fps: Target FPS for frame extraction
Returns:
Dictionary with dataset entry or None if processing failed
"""
md5 = row['md5']
video_path = os.path.join(videos_dir, f"{md5}.mp4")
pose_path = os.path.join(pose_dir, f"{md5}.pose")
eaf_path = os.path.join(eaf_dir, f"{md5}.eaf")
# Check if video exists
if not os.path.exists(video_path):
return None
# Cascading segmentation approach:
# 1. Try pose-based segmentation first
time_range = None
if os.path.exists(pose_path):
time_range = get_signing_time_range_from_pose(pose_path)
# 2. If pose covers entire file (returns None), try EAF
if time_range is None and os.path.exists(eaf_path):
time_range = get_sign_time_range_from_eaf(eaf_path)
# 3. Fall back to full video duration
if time_range is not None:
start_time, end_time = time_range
else:
try:
start_time = 0.0
end_time = get_video_duration(video_path)
except Exception:
return None
# Validate time range
if end_time <= start_time:
return None
# Extract frames
try:
frames = extract_frames_from_video(
video_path, start_time, end_time, target_fps=target_fps
)
except Exception:
return None
if not frames:
return None
return {
'file': row['file'],
'start': round(start_time, 3),
'end': round(end_time, 3),
'text': row['text'],
'images': frames
}
def load_csv_data(csv_path: str) -> dict[str, list[dict]]:
"""
Load CSV data and group by split.
Returns:
Dictionary mapping split names to lists of row dictionaries
"""
splits = {'train': [], 'validation': [], 'test': []}
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
split = row['split']
if split in splits:
splits[split].append(row)
return splits
def _process_row_wrapper(args: tuple) -> dict | None:
"""Wrapper for process_csv_row to work with multiprocessing."""
row, videos_dir, eaf_dir, pose_dir, target_fps = args
return process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps)
def create_subset_dataset(
csv_path: str,
videos_dir: str,
eaf_dir: str,
pose_dir: str,
target_fps: float = 5,
limit: int | None = None,
num_workers: int | None = None
) -> DatasetDict:
"""
Create a DatasetDict for a single subset (game or non-game).
Args:
csv_path: Path to the index.csv file
videos_dir: Directory containing 256x256 videos
eaf_dir: Directory containing EAF files
pose_dir: Directory containing pose files
target_fps: Target FPS for frame extraction
limit: Optional limit on number of samples per split (for testing)
num_workers: Number of parallel workers (default: CPU count)
Returns:
DatasetDict with train, validation, test splits
"""
splits_data = load_csv_data(csv_path)
if num_workers is None:
num_workers = cpu_count()
features = Features({
'file': Value('string'),
'start': Value('float32'),
'end': Value('float32'),
'text': Value('string'),
'images': Sequence(Image())
})
dataset_splits = {}
for split_name, rows in splits_data.items():
if not rows:
continue
if limit is not None:
rows = rows[:limit]
# Prepare arguments for parallel processing
args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in rows]
processed_data = []
if num_workers > 1:
with Pool(num_workers) as pool:
results = list(tqdm(
pool.imap(_process_row_wrapper, args_list, chunksize=100),
total=len(args_list),
desc=f"Processing {split_name}",
unit="sample"
))
processed_data = [r for r in results if r is not None]
else:
for row in tqdm(rows, desc=f"Processing {split_name}", unit="sample"):
result = process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps)
if result is not None:
processed_data.append(result)
if processed_data:
dataset_splits[split_name] = Dataset.from_list(
processed_data,
features=features
)
return DatasetDict(dataset_splits)
def create_popsign_dataset(
popsign_dir: str,
videos_dir: str,
eaf_dir: str,
pose_dir: str,
output_dir: str,
target_fps: float = 5,
limit: int | None = None,
num_workers: int | None = None
):
"""
Create the complete PopSign HuggingFace dataset with game and non-game subsets.
Args:
popsign_dir: Root directory containing game/ and non-game/ subdirectories
videos_dir: Directory containing 256x256 videos
eaf_dir: Directory containing EAF files
pose_dir: Directory containing pose files
output_dir: Output directory for the dataset
target_fps: Target FPS for frame extraction
limit: Optional limit on samples per split (for testing)
num_workers: Number of parallel workers
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
subsets = ['game', 'non-game']
for subset in subsets:
csv_path = os.path.join(popsign_dir, subset, 'index.csv')
if not os.path.exists(csv_path):
print(f"Warning: {csv_path} not found, skipping {subset}")
continue
print(f"\nProcessing {subset} subset...")
dataset_dict = create_subset_dataset(
csv_path=csv_path,
videos_dir=videos_dir,
eaf_dir=eaf_dir,
pose_dir=pose_dir,
target_fps=target_fps,
limit=limit,
num_workers=num_workers
)
# Save the subset
subset_path = output_path / subset
dataset_dict.save_to_disk(str(subset_path))
print(f"Saved {subset} to {subset_path}")
print(f"\nDataset saved to {output_dir}")
def _save_shard(shard_data: list, shard_idx: int, num_shards: int, split_name: str, subset_data_path: Path, features: Features) -> int:
"""Save a shard to parquet and return the number of samples saved."""
if not shard_data:
return 0
dataset = Dataset.from_list(shard_data, features=features)
parquet_path = subset_data_path / f"{split_name}-{shard_idx:05d}-of-{num_shards:05d}.parquet"
dataset.to_parquet(str(parquet_path))
count = len(shard_data)
print(f"\n Saved shard {shard_idx} ({count} samples) -> {parquet_path.name}", flush=True)
del dataset
return count
def save_as_parquet(
popsign_dir: str,
videos_dir: str,
eaf_dir: str,
pose_dir: str,
output_dir: str,
target_fps: float = 5,
limit: int | None = None,
shard_size: int = 10000,
num_workers: int | None = None
):
"""
Create the PopSign dataset and save in Parquet format for HuggingFace Hub upload.
Saves shards incrementally to minimize RAM usage by processing in small batches.
Directory structure:
output_dir/
├── README.md
└── data/
├── game/
│ ├── train-00000-of-NNNNN.parquet
│ └── ...
└── non-game/
└── ...
Args:
pose_dir: Directory containing pose files
shard_size: Number of samples per parquet shard (default: 10000)
num_workers: Number of parallel workers
"""
output_path = Path(output_dir)
data_path = output_path / "data"
data_path.mkdir(parents=True, exist_ok=True)
# Copy README.md to output directory (if not already there)
readme_dest = output_path / "README.md"
if README_TEMPLATE_PATH.exists() and README_TEMPLATE_PATH.resolve() != readme_dest.resolve():
shutil.copy(README_TEMPLATE_PATH, readme_dest)
print(f"Copied README.md to {readme_dest}")
if num_workers is None:
num_workers = cpu_count()
# Process in small batches to limit memory - each batch is processed in parallel,
# then results are accumulated until we have enough for a shard
batch_size = min(1000, shard_size) # Small batches to limit memory
print(f"Using {num_workers} workers, shard_size={shard_size}, batch_size={batch_size}", flush=True)
features = Features({
'file': Value('string'),
'start': Value('float32'),
'end': Value('float32'),
'text': Value('string'),
'images': Sequence(Image())
})
subsets = ['game', 'non-game']
for subset in subsets:
csv_path = os.path.join(popsign_dir, subset, 'index.csv')
if not os.path.exists(csv_path):
print(f"Warning: {csv_path} not found, skipping {subset}", flush=True)
continue
print(f"\nProcessing {subset} subset...", flush=True)
splits_data = load_csv_data(csv_path)
subset_data_path = data_path / subset
subset_data_path.mkdir(parents=True, exist_ok=True)
for split_name, rows in splits_data.items():
if not rows:
continue
if limit is not None:
rows = rows[:limit]
total_rows = len(rows)
num_shards = max(1, (total_rows + shard_size - 1) // shard_size)
print(f"Processing {split_name} ({total_rows} rows, ~{num_shards} shards)...", flush=True)
shard_data = []
shard_idx = 0
total_saved = 0
total_processed = 0
# Process in small batches to control memory
pbar = tqdm(total=total_rows, desc=f" {split_name}", unit="row")
for batch_start in range(0, total_rows, batch_size):
batch_end = min(batch_start + batch_size, total_rows)
batch_rows = rows[batch_start:batch_end]
# Process this batch
if num_workers > 1:
args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
with Pool(num_workers) as pool:
results = pool.map(_process_row_wrapper, args_list)
else:
results = [process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
# Accumulate successful results
for result in results:
if result is not None:
shard_data.append(result)
# Save shard when full
if len(shard_data) >= shard_size:
total_saved += _save_shard(shard_data, shard_idx, num_shards, split_name, subset_data_path, features)
shard_data = []
shard_idx += 1
# Free batch memory
del results
total_processed += len(batch_rows)
pbar.update(len(batch_rows))
pbar.close()
# Save any remaining data
if shard_data:
total_saved += _save_shard(shard_data, shard_idx, num_shards, split_name, subset_data_path, features)
shard_idx += 1
print(f"Saved {subset}/{split_name}: {total_saved} samples in {shard_idx} shards", flush=True)
print(f"\nDataset saved to {output_dir}", flush=True)
print("\nTo upload to HuggingFace Hub:")
print(f" huggingface-cli upload sign/popsign-images {output_dir} .")
def _save_webdataset_shard(
shard_data: list,
shard_idx: int,
num_shards: int,
split_name: str,
subset_data_path: Path,
sample_id_offset: int,
jpeg_quality: int
) -> int:
"""Save a shard to tar and return the number of samples saved."""
if not shard_data:
return 0
tar_path = subset_data_path / f"{split_name}-{shard_idx:05d}-of-{num_shards:05d}.tar"
with tarfile.open(tar_path, 'w') as tar:
for i, sample in enumerate(shard_data):
sample_id = f"{sample_id_offset + i:06d}"
# Write metadata JSON
metadata = {
'file': sample['file'],
'start': sample['start'],
'end': sample['end'],
'text': sample['text'],
'num_frames': len(sample['images'])
}
json_data = json.dumps(metadata).encode('utf-8')
json_info = tarfile.TarInfo(name=f"{sample_id}.json")
json_info.size = len(json_data)
tar.addfile(json_info, io.BytesIO(json_data))
# Write all frames as JPEG bytes in a single pickle file
frames_data = []
for img in sample['images']:
jpg_buffer = io.BytesIO()
img.save(jpg_buffer, format='JPEG', quality=jpeg_quality)
frames_data.append(jpg_buffer.getvalue())
pyd_data = pickle.dumps(frames_data)
pyd_info = tarfile.TarInfo(name=f"{sample_id}.pyd")
pyd_info.size = len(pyd_data)
tar.addfile(pyd_info, io.BytesIO(pyd_data))
count = len(shard_data)
print(f"\n Saved shard {shard_idx} ({count} samples) -> {tar_path.name}", flush=True)
return count
def save_as_webdataset(
popsign_dir: str,
videos_dir: str,
eaf_dir: str,
pose_dir: str,
output_dir: str,
target_fps: float = 5,
limit: int | None = None,
shard_size: int = 1000,
num_workers: int | None = None,
jpeg_quality: int = 90
):
"""
Create the PopSign dataset and save in WebDataset format for HuggingFace Hub upload.
Saves shards incrementally to minimize RAM usage.
Directory structure:
output_dir/
├── README.md
└── data/
├── game/
│ ├── train-00000-of-NNNNN.tar
│ └── ...
└── non-game/
└── ...
Each tar contains:
- {sample_id:06d}.json (metadata: file, start, end, text, num_frames)
- {sample_id:06d}.pyd (pickled list of JPEG bytes)
Args:
pose_dir: Directory containing pose files
shard_size: Number of samples per tar shard (default: 1000)
num_workers: Number of parallel workers
jpeg_quality: JPEG quality for saved images (default: 90)
"""
output_path = Path(output_dir)
data_path = output_path / "data"
data_path.mkdir(parents=True, exist_ok=True)
# Copy README.md to output directory (if not already there)
readme_dest = output_path / "README.md"
if README_TEMPLATE_PATH.exists() and README_TEMPLATE_PATH.resolve() != readme_dest.resolve():
shutil.copy(README_TEMPLATE_PATH, readme_dest)
print(f"Copied README.md to {readme_dest}")
if num_workers is None:
num_workers = cpu_count()
# Process in small batches to limit memory
batch_size = min(1000, shard_size)
print(f"Using {num_workers} workers, shard_size={shard_size}, batch_size={batch_size}", flush=True)
subsets = ['game', 'non-game']
for subset in subsets:
csv_path = os.path.join(popsign_dir, subset, 'index.csv')
if not os.path.exists(csv_path):
print(f"Warning: {csv_path} not found, skipping {subset}", flush=True)
continue
print(f"\nProcessing {subset} subset...", flush=True)
splits_data = load_csv_data(csv_path)
subset_data_path = data_path / subset
subset_data_path.mkdir(parents=True, exist_ok=True)
for split_name, rows in splits_data.items():
if not rows:
continue
if limit is not None:
rows = rows[:limit]
total_rows = len(rows)
num_shards = max(1, (total_rows + shard_size - 1) // shard_size)
print(f"Processing {split_name} ({total_rows} rows, ~{num_shards} shards)...", flush=True)
shard_data = []
shard_idx = 0
total_saved = 0
sample_id_offset = 0
# Process in small batches to control memory
pbar = tqdm(total=total_rows, desc=f" {split_name}", unit="row")
for batch_start in range(0, total_rows, batch_size):
batch_end = min(batch_start + batch_size, total_rows)
batch_rows = rows[batch_start:batch_end]
# Process this batch
if num_workers > 1:
args_list = [(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
with Pool(num_workers) as pool:
results = pool.map(_process_row_wrapper, args_list)
else:
results = [process_csv_row(row, videos_dir, eaf_dir, pose_dir, target_fps) for row in batch_rows]
# Accumulate successful results
for result in results:
if result is not None:
shard_data.append(result)
# Save shard when full
if len(shard_data) >= shard_size:
total_saved += _save_webdataset_shard(
shard_data, shard_idx, num_shards, split_name,
subset_data_path, sample_id_offset, jpeg_quality
)
sample_id_offset += len(shard_data)
shard_data = []
shard_idx += 1
# Free batch memory
del results
pbar.update(len(batch_rows))
pbar.close()
# Save any remaining data
if shard_data:
total_saved += _save_webdataset_shard(
shard_data, shard_idx, num_shards, split_name,
subset_data_path, sample_id_offset, jpeg_quality
)
shard_idx += 1
print(f"Saved {subset}/{split_name}: {total_saved} samples in {shard_idx} shards", flush=True)
print(f"\nDataset saved to {output_dir}", flush=True)
print("\nTo upload to HuggingFace Hub:")
print(f" huggingface-cli upload sign/popsign-images {output_dir} .")
def main():
parser = argparse.ArgumentParser(
description='Create PopSign HuggingFace dataset with images'
)
parser.add_argument(
'--popsign-dir',
type=str,
default='some-path-to/popsign/v1',
help='Root directory containing game/ and non-game/ subdirectories'
)
parser.add_argument(
'--videos-dir',
type=str,
default='some-path-to-videos/256x256',
help='Directory containing 256x256 videos named by MD5 hash'
)
parser.add_argument(
'--eaf-dir',
type=str,
default='some-path-to-segments',
help='Directory containing EAF segmentation files'
)
parser.add_argument(
'--pose-dir',
type=str,
default='some-path-to-poses',
help='Directory containing pose files for signing boundary detection'
)
parser.add_argument(
'--output-dir',
type=str,
default='/shared/popsign-images',
help='Output directory for the HuggingFace dataset'
)
parser.add_argument(
'--fps',
type=float,
default=5,
help='Target frames per second for frame extraction (default: 5)'
)
parser.add_argument(
'--limit',
type=int,
default=None,
help='Limit number of samples per split (for testing)'
)
parser.add_argument(
'--format',
type=str,
choices=['webdataset', 'parquet', 'arrow'],
default='parquet',
help='Output format: webdataset (JPEG compressed), parquet, or arrow (for local use)'
)
parser.add_argument(
'--shard-size',
type=int,
default=1000,
help='Number of samples per shard (default: 1000)'
)
parser.add_argument(
'--jpeg-quality',
type=int,
default=90,
help='JPEG quality for WebDataset format (default: 90)'
)
parser.add_argument(
'--workers',
type=int,
default=None,
help='Number of parallel workers (default: CPU count)'
)
args = parser.parse_args()
if args.format == 'webdataset':
save_as_webdataset(
popsign_dir=args.popsign_dir,
videos_dir=args.videos_dir,
eaf_dir=args.eaf_dir,
pose_dir=args.pose_dir,
output_dir=args.output_dir,
target_fps=args.fps,
limit=args.limit,
shard_size=args.shard_size,
num_workers=args.workers,
jpeg_quality=args.jpeg_quality
)
elif args.format == 'parquet':
save_as_parquet(
popsign_dir=args.popsign_dir,
videos_dir=args.videos_dir,
eaf_dir=args.eaf_dir,
pose_dir=args.pose_dir,
output_dir=args.output_dir,
target_fps=args.fps,
limit=args.limit,
shard_size=args.shard_size,
num_workers=args.workers
)
else:
create_popsign_dataset(
popsign_dir=args.popsign_dir,
videos_dir=args.videos_dir,
eaf_dir=args.eaf_dir,
pose_dir=args.pose_dir,
output_dir=args.output_dir,
target_fps=args.fps,
limit=args.limit,
num_workers=args.workers
)
if __name__ == '__main__':
main()