WLASL100 / wlasl100.py
tanthinhdt's picture
fix(builder): remove redundancies
a708d6b verified
# Copyright 2023 Thinh T. Duong
import os
import datasets
import pandas as pd
from glob import glob
logger = datasets.logging.get_logger(__name__)
_CITATION = """
"""
_DESCRIPTION = """
"""
_HOMEPAGE = "https://github.com/dxli94/WLASL"
_REPO_URL = "https://huggingface.co/datasets/VieSignLang/wlasl100/resolve/main"
_URLS = {
"meta": f"{_REPO_URL}/WLASL_v0.3.json",
"labels": f"{_REPO_URL}/folder2label_str.txt",
"rgb_videos": f"{_REPO_URL}/WLASL100/*.zip",
"rgb_frames": f"{_REPO_URL}/preprocessing" + "/{split}/frames/*.zip",
"keypoint_frames": f"{_REPO_URL}/preprocessing" + "/{split}/pose/*.zip",
}
class WLASL100Config(datasets.BuilderConfig):
"""WLASL100 configuration."""
def __init__(self, name, **kwargs):
"""
:param name: Name of subset.
:param kwargs: Arguments.
"""
super(WLASL100Config, self).__init__(
name=name,
version=datasets.Version("1.0.0"),
description=_DESCRIPTION,
**kwargs,
)
class WLASL100(datasets.GeneratorBasedBuilder):
"""WLASL100 dataset."""
BUILDER_CONFIGS = [
WLASL100Config(name="rgb_videos"),
WLASL100Config(name="rgb_frames"),
WLASL100Config(name="keypoint_frames"),
]
DEFAULT_CONFIG_NAME = "rgb_videos"
def _info(self) -> datasets.DatasetInfo:
features = datasets.Features({
"gloss": datasets.Value("string"),
"bbox": datasets.Sequence(datasets.Value("int16")),
"fps": datasets.Value("int8"),
"frame_end": datasets.Value("int32"),
"frame_start": datasets.Value("int32"),
"instance_id": datasets.Value("int32"),
"signer_id": datasets.Value("int32"),
"source": datasets.Value("string"),
"url": datasets.Value("string"),
"variation_id": datasets.Value("int8"),
"video_id": datasets.Value("int32"),
"video": datasets.Value("string"),
})
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(
self, dl_manager: datasets.DownloadManager
) -> list[datasets.SplitGenerator]:
"""
Get splits.
Parameters
----------
dl_manager : datasets.DownloadManager
Download manager.
Returns
-------
list[datasets.SplitGenerator]
Splits.
"""
raw_df = pd.read_json(dl_manager.download(_URLS["meta"])).explode("instances")
df = pd.concat(
[
raw_df[["gloss"]].reset_index(drop=True),
pd.json_normalize(raw_df.instances)
],
axis=1,
)
df = df.merge(
pd.read_csv(
dl_manager.download(_URLS["labels"]),
sep=" ",
names=["gloss_label", "gloss"],
),
on="gloss", how="right",
)
df["gloss_label"] = df["gloss_label"].astype(str)
split_dict = {
"train": datasets.Split.TRAIN,
"test": datasets.Split.TEST,
"val": datasets.Split.VALIDATION,
}
video_urls = _URLS["rgb_videos"]
if self.config.name != "rgb_videos":
split_dict.pop("val")
video_urls = _URLS[self.config.name]
return [
datasets.SplitGenerator(
name=name,
gen_kwargs={
"split_df": df[df.split == split].drop(columns=["split"]),
"video_dirs": dl_manager.download_and_extract(
glob(video_urls.format(split=split))
),
},
)
for split, name in split_dict.items()
]
def _generate_examples(
self, split_df: str,
video_dirs: list[str],
) -> tuple[int, dict]:
"""
Generate examples from metadata.
Parameters
----------
split_df : str
Split dataframe.
video_dirs : list[str]
List of video directories.
Yields
------
tuple[int, dict]
Index and example.
"""
split = datasets.Dataset.from_pandas(split_df)
for i, sample in enumerate(split):
for video_dir in video_dirs:
video_path = os.path.join(video_dir, sample["gloss_label"])
if self.config.name == "rgb_videos":
video_path = os.path.join(video_path, sample["video_id"] + ".mp4")
else:
video_path = os.path.join(video_path, sample["video_id"], "*.jpg")
if len(glob(video_path)) > 0:
yield i, {
"gloss": sample["gloss"],
"bbox": sample["bbox"],
"fps": sample["fps"],
"frame_end": sample["frame_end"],
"frame_start": sample["frame_start"],
"instance_id": sample["instance_id"],
"signer_id": sample["signer_id"],
"source": sample["source"],
"url": sample["url"],
"variation_id": sample["variation_id"],
"video_id": sample["video_id"],
"video": video_path,
}