import os
from io import BytesIO
from typing import Any, Callable, Dict, List, Optional, Union, Iterator
import requests
import torch
from torch.utils.data import ChainDataset, ConcatDataset, DataLoader, Dataset
from torchvision import io as video_io
from transformers import AutoTokenizer
class GeneralizedVideoDataset(Dataset):
"""
A generalized dataset loader for videos and captions.
Supports any splits, any number of columns, and flexible column data types.
"""
def __init__(
self,
data: List[Dict[str, Any]],
video_column: str,
caption_column: Optional[str] = None,
transform: Optional[Callable] = None,
tokenizer_name: Optional[str] = None,
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
max_length: Optional[int] = None,
padding: Union[bool, str] = False,
special_tokens: Optional[Dict[str, str]] = None,
**kwargs: Any,
) -> None:
"""
Initializes the dataset.
Args:
data: The data source, a list of dictionaries containing dataset samples.
video_column: The key for video paths in the data.
caption_column: The key for captions in the data.
transform: Optional transform to be applied on a sample.
tokenizer_name: Name of the tokenizer to use from Hugging Face.
tokenizer_kwargs: Additional kwargs for the tokenizer initialization.
max_length: Max length for tokenization.
padding: Padding strategy for tokenization.
special_tokens: Dict of special tokens to add to the tokenizer.
**kwargs: Additional arguments.
"""
self.data = data
self.video_column = video_column
self.caption_column = caption_column
self.transform = transform
self.tokenizer = None
if tokenizer_name:
tokenizer_args = tokenizer_kwargs if tokenizer_kwargs else {}
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name, **tokenizer_args)
if special_tokens:
self.tokenizer.add_special_tokens({'additional_special_tokens': list(special_tokens.values())})
self.max_length = max_length
self.padding = padding
def __len__(self) -> int:
return len(self.data)
def __getitem__(self, idx: int) -> Dict[str, Any]:
"""
Retrieves the sample at the given index.
Args:
idx: Index of the sample.
Returns:
A dictionary containing the sample data.
"""
sample = self.data[idx]
item: Dict[str, Any] = {}
try:
video_path = sample[self.video_column]
video = self._load_video(video_path)
item['video'] = video
if self.caption_column:
caption = sample[self.caption_column]
if self.tokenizer:
encoding = self.tokenizer.encode_plus(
caption,
max_length=self.max_length,
padding=self.padding,
truncation=True,
return_tensors='pt',
)
item['caption'] = encoding
else:
item['caption'] = caption
# Include other columns
for key, value in sample.items():
if key not in [self.video_column, self.caption_column]:
item[key] = value
# Apply transform if any
if self.transform:
item['video'] = self.transform(item['video'])
except KeyError as e:
raise KeyError(f"Missing key in data sample: {e}")
except Exception as e:
raise RuntimeError(f"Error loading sample idx {idx}: {e}")
return item
def _load_video(self, path_or_url: str) -> torch.Tensor:
"""
Loads a video from a local path or a URL.
Args:
path_or_url: The video file path or URL.
Returns:
Video data as a PyTorch tensor.
"""
try:
if path_or_url.startswith('http://') or path_or_url.startswith('https://'):
# URL case
response = requests.get(path_or_url, stream=True)
response.raise_for_status()
video_bytes = BytesIO(response.content)
video, _, _ = video_io.read_video(video_bytes)
else:
# Local file case
if not os.path.exists(path_or_url):
raise FileNotFoundError(f"Video file not found: {path_or_url}")
video, _, _ = video_io.read_video(path_or_url)
return video
except Exception as e:
raise ValueError(f"Error loading video from {path_or_url}: {e}")
def batch_encode_captions(self, captions: List[str], **kwargs: Any) -> Dict[str, torch.Tensor]:
"""
Batch encodes a list of captions.
Args:
captions: A list of caption strings.
**kwargs: Additional arguments for the tokenizer.
Returns:
A dictionary containing the encoded captions.
"""
if not self.tokenizer:
raise ValueError("Tokenizer has not been initialized.")
return self.tokenizer.batch_encode_plus(
captions,
max_length=self.max_length,
padding=self.padding,
truncation=True,
return_tensors='pt',
**kwargs,
)
def batch_decode_captions(self, token_ids: torch.Tensor, **kwargs: Any) -> List[str]:
"""
Batch decodes token IDs to captions.
Args:
token_ids: A tensor of token IDs.
**kwargs: Additional arguments for the tokenizer.
Returns:
A list of decoded caption strings.
"""
if not self.tokenizer:
raise ValueError("Tokenizer has not been initialized.")
return self.tokenizer.batch_decode(token_ids, **kwargs)
def create_combined_dataset(datasets: List[Dataset]) -> Dataset:
"""
Combines multiple datasets into a single dataset.
Args:
datasets: A list of Dataset objects.
Returns:
A combined Dataset.
"""
if not datasets:
raise ValueError("No datasets provided for combination.")
if len(datasets) == 1:
return datasets[0]
return ConcatDataset(datasets)
def get_data_loader(
dataset: Dataset,
batch_size: int = 1,
shuffle: bool = False,
sampler: Optional[torch.utils.data.Sampler] = None,
batch_sampler: Optional[torch.utils.data.BatchSampler] = None,
num_workers: int = 0,
collate_fn: Optional[Callable] = None,
pin_memory: bool = False,
drop_last: bool = False,
timeout: float = 0.0,
worker_init_fn: Optional[Callable[[int], None]] = None,
prefetch_factor: int = 2,
persistent_workers: bool = False,
**kwargs: Any,
) -> DataLoader:
"""
Creates a DataLoader for the given dataset.
Args:
dataset: The dataset to load data from.
batch_size: How many samples per batch to load.
shuffle: Whether to shuffle the data at every epoch.
sampler: Defines the strategy to draw samples from the dataset.
batch_sampler: Like sampler, but returns a batch of indices at a time.
num_workers: How many subprocesses to use for data loading.
collate_fn: Merges a list of samples to form a mini-batch.
pin_memory: If True, the data loader will copy tensors into CUDA pinned memory before returning them.
drop_last: Set to True to drop the last incomplete batch.
timeout: Timeout value for collecting a batch.
worker_init_fn: If not None, this will be called on each worker subprocess with the worker id.
prefetch_factor: Number of batches loaded in advance by each worker.
persistent_workers: If True, workers are not shut down after dataset iteration.
**kwargs: Additional arguments.
Returns:
A DataLoader instance.
"""
return DataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle,
sampler=sampler,
batch_sampler=batch_sampler,
num_workers=num_workers,
collate_fn=collate_fn,
pin_memory=pin_memory,
drop_last=drop_last,
timeout=timeout,
worker_init_fn=worker_init_fn,
prefetch_factor=prefetch_factor,
persistent_workers=persistent_workers,
**kwargs,
)
This code provides a highly flexible and robust framework for loading video datasets with captions, handling tokenization, and preparing data loaders for training models. It adheres strictly to PEP-8 standards, includes comprehensive type hints using the typing module, and incorporates advanced error handling to ensure robustness.
Key Features:
-
Generalized Dataset Loader: GeneralizedVideoDataset class can handle videos from local paths or URLs, supports any number of columns with varying data types, and integrates optional transformations.
-
Robust Tokenization: Incorporates the Hugging Face AutoTokenizer with support for special tokens, max length, padding strategies, and batch encoding/decoding methods.
-
Advanced Error Handling: Uses try-except blocks to catch exceptions gracefully, providing meaningful error messages for easier debugging and robustness under unexpected conditions.
-
Dataset Combination and DataLoader Preparation: Functions create_combined_dataset and get_data_loader allow for flexible dataset mixing and data loader configuration, supporting continuation of training and scalable data handling.
-
**Flexibility with *args and kwargs: All functions and methods are designed to accept additional arguments, giving users the freedom to pass any number of optional parameters.
This implementation balances performance and readability, ensuring maintainability while leveraging Python's best practices and standard libraries effectively.