| | |
| |
|
| | """AudioCaps dataset.""" |
| |
|
| |
|
| | import os |
| | import gzip |
| | import shutil |
| | import joblib |
| | import pathlib |
| | import logging |
| | import datasets |
| | import typing as tp |
| | import pandas as pd |
| | import urllib.request |
| | from pathlib import Path |
| | from copy import deepcopy |
| | from tqdm.auto import tqdm |
| | from rich.logging import RichHandler |
| |
|
| | logger = logging.getLogger(__name__) |
| | logger.addHandler(RichHandler()) |
| | logger.setLevel(logging.INFO) |
| |
|
| | VERSION = "0.0.1" |
| |
|
| | |
| | DEFAULT_XDG_CACHE_HOME = "~/.cache" |
| | XDG_CACHE_HOME = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME) |
| | DEFAULT_HF_CACHE_HOME = os.path.join(XDG_CACHE_HOME, "huggingface") |
| | HF_CACHE_HOME = os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME)) |
| | DEFAULT_HF_DATASETS_CACHE = os.path.join(HF_CACHE_HOME, "datasets") |
| | HF_DATASETS_CACHE = Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE)) |
| |
|
| |
|
| | class AudioCapsConfig(datasets.BuilderConfig): |
| | """BuilderConfig for AudioCaps.""" |
| | |
| | def __init__(self, features, **kwargs): |
| | super(AudioCapsConfig, self).__init__(version=datasets.Version(VERSION, ""), **kwargs) |
| | self.features = features |
| |
|
| |
|
| | class AudioCaps(datasets.GeneratorBasedBuilder): |
| |
|
| | BUILDER_CONFIGS = [ |
| | AudioCapsConfig( |
| | features=datasets.Features( |
| | { |
| | "file": datasets.Value("string"), |
| | "audio": datasets.Audio(sampling_rate=None), |
| | "captions": datasets.Sequence(datasets.Value("string")), |
| | } |
| | ), |
| | name="audiocaps", |
| | description="", |
| | ), |
| | ] |
| |
|
| | DEFAULT_CONFIG_NAME = "audiocaps" |
| |
|
| | def _info(self): |
| | return datasets.DatasetInfo( |
| | description="", |
| | features=self.config.features, |
| | supervised_keys=None, |
| | homepage="", |
| | citation="", |
| | task_templates=None, |
| | ) |
| |
|
| | def _split_generators(self, dl_manager): |
| | """Returns SplitGenerators.""" |
| | extensions = ['.wav'] |
| | |
| | |
| | def _download_and_extract(filename): |
| | DEV_URL = f'https://huggingface.co/datasets/confit/audiocaps/resolve/main/data/{filename}' |
| | _dev_save_path = os.path.join( |
| | HF_DATASETS_CACHE, 'confit___audiocaps/audiocaps', VERSION |
| | ) |
| | download_file( |
| | source=DEV_URL, |
| | dest=os.path.join(_dev_save_path, filename), |
| | unpack=True, |
| | dest_unpack=os.path.join(_dev_save_path, 'extracted', 'train'), |
| | ) |
| | |
| | joblib.Parallel(n_jobs=8, verbose=10)( |
| | joblib.delayed(_download_and_extract)( |
| | filename=_filename |
| | ) for _filename in tqdm([f'train{i}.zip' for i in range(1, 12+1)]) |
| | ) |
| | train_audio_paths = [] |
| | for _filename in [f'train{i}.zip' for i in range(1, 12+1)]: |
| | DEV_URL = f'https://huggingface.co/datasets/confit/audiocaps/resolve/main/data/{_filename}' |
| | _dev_save_path = os.path.join( |
| | HF_DATASETS_CACHE, 'confit___audiocaps/audiocaps', VERSION |
| | ) |
| | train_archive_path = os.path.join(_dev_save_path, 'extracted', 'train') |
| | _, _walker = fast_scandir(train_archive_path, extensions, recursive=True) |
| | train_audio_paths.extend(_walker) |
| | |
| | |
| | VAL_URL = 'https://huggingface.co/datasets/confit/audiocaps/resolve/main/data/val.zip' |
| | _val_save_path = os.path.join( |
| | HF_DATASETS_CACHE, 'confit___audiocaps/audiocaps', VERSION |
| | ) |
| | _filename = 'val.zip' |
| | download_file( |
| | source=VAL_URL, |
| | dest=os.path.join(_val_save_path, _filename), |
| | unpack=True, |
| | dest_unpack=os.path.join(_val_save_path, 'extracted', 'validation'), |
| | ) |
| | validation_archive_path = os.path.join(_val_save_path, 'extracted', 'validation') |
| | _, validation_audio_paths = fast_scandir(validation_archive_path, extensions, recursive=True) |
| |
|
| | |
| | EVAL_URL = 'https://huggingface.co/datasets/confit/audiocaps/resolve/main/data/test.zip' |
| | _eval_save_path = os.path.join( |
| | HF_DATASETS_CACHE, 'confit___audiocaps/audiocaps', VERSION |
| | ) |
| | _filename = 'test.zip' |
| | download_file( |
| | source=EVAL_URL, |
| | dest=os.path.join(_eval_save_path, _filename), |
| | unpack=True, |
| | dest_unpack=os.path.join(_eval_save_path, 'extracted', 'test'), |
| | ) |
| | test_archive_path = os.path.join(_eval_save_path, 'extracted', 'test') |
| | _, test_audio_paths = fast_scandir(test_archive_path, extensions, recursive=True) |
| |
|
| | return [ |
| | datasets.SplitGenerator( |
| | name=datasets.Split.TRAIN, gen_kwargs={"audio_paths": train_audio_paths, "split": "train"} |
| | ), |
| | datasets.SplitGenerator( |
| | name=datasets.Split.VALIDATION, gen_kwargs={"audio_paths": validation_audio_paths, "split": "validation"} |
| | ), |
| | datasets.SplitGenerator( |
| | name=datasets.Split.TEST, gen_kwargs={"audio_paths": test_audio_paths, "split": "test"} |
| | ), |
| | ] |
| |
|
| | def _generate_examples(self, audio_paths, split=None): |
| | if split == 'train': |
| | metadata_df = pd.read_csv('https://huggingface.co/datasets/confit/audiocaps/raw/main/metadata/train.csv') |
| | elif split == 'validation': |
| | metadata_df = pd.read_csv('https://huggingface.co/datasets/confit/audiocaps/raw/main/metadata/val.csv') |
| | elif split == 'test': |
| | metadata_df = pd.read_csv('https://huggingface.co/datasets/confit/audiocaps/raw/main/metadata/test.csv') |
| |
|
| | fileid2caption = {} |
| | for idx, row in metadata_df.iterrows(): |
| | fileid2caption[f"{row['audiocap_id']}.wav"] = row['caption'] |
| |
|
| | for guid, audio_path in enumerate(audio_paths): |
| | fileid = Path(audio_path).name |
| | caption = fileid2caption.get(fileid) |
| | yield guid, { |
| | "id": str(guid), |
| | "file": audio_path, |
| | "audio": audio_path, |
| | "captions": [caption], |
| | } |
| |
|
| |
|
| | def fast_scandir(path: str, exts: tp.List[str], recursive: bool = False): |
| | |
| | |
| | subfolders, files = [], [] |
| |
|
| | try: |
| | for f in os.scandir(path): |
| | try: |
| | if f.is_dir(): |
| | subfolders.append(f.path) |
| | elif f.is_file(): |
| | if os.path.splitext(f.name)[1].lower() in exts: |
| | files.append(f.path) |
| | except Exception: |
| | pass |
| | except Exception: |
| | pass |
| |
|
| | if recursive: |
| | for path in list(subfolders): |
| | sf, f = fast_scandir(path, exts, recursive=recursive) |
| | subfolders.extend(sf) |
| | files.extend(f) |
| |
|
| | return subfolders, files |
| |
|
| |
|
| | def download_file( |
| | source, |
| | dest, |
| | unpack=False, |
| | dest_unpack=None, |
| | replace_existing=False, |
| | write_permissions=False, |
| | ): |
| | """Downloads the file from the given source and saves it in the given |
| | destination path. |
| | Arguments |
| | --------- |
| | source : path or url |
| | Path of the source file. If the source is an URL, it downloads it from |
| | the web. |
| | dest : path |
| | Destination path. |
| | unpack : bool |
| | If True, it unpacks the data in the dest folder. |
| | dest_unpack: path |
| | Path where to store the unpacked dataset |
| | replace_existing : bool |
| | If True, replaces the existing files. |
| | write_permissions: bool |
| | When set to True, all the files in the dest_unpack directory will be granted write permissions. |
| | This option is active only when unpack=True. |
| | """ |
| | class DownloadProgressBar(tqdm): |
| | """DownloadProgressBar class.""" |
| |
|
| | def update_to(self, b=1, bsize=1, tsize=None): |
| | """Needed to support multigpu training.""" |
| | if tsize is not None: |
| | self.total = tsize |
| | self.update(b * bsize - self.n) |
| |
|
| | |
| | dest_dir = pathlib.Path(dest).resolve().parent |
| | dest_dir.mkdir(parents=True, exist_ok=True) |
| | if "http" not in source: |
| | shutil.copyfile(source, dest) |
| |
|
| | elif not os.path.isfile(dest) or ( |
| | os.path.isfile(dest) and replace_existing |
| | ): |
| | logger.info(f"Downloading {source} to {dest}") |
| | with DownloadProgressBar( |
| | unit="B", |
| | unit_scale=True, |
| | miniters=1, |
| | desc=source.split("/")[-1], |
| | ) as t: |
| | urllib.request.urlretrieve( |
| | source, filename=dest, reporthook=t.update_to |
| | ) |
| | else: |
| | logger.info(f"{dest} exists. Skipping download") |
| |
|
| | |
| | if unpack: |
| | if dest_unpack is None: |
| | dest_unpack = os.path.dirname(dest) |
| | if os.path.exists(dest_unpack): |
| | logger.info(f"{dest_unpack} already exists. Skipping extraction") |
| | else: |
| | logger.info(f"Extracting {dest} to {dest_unpack}") |
| | |
| | if ( |
| | source.endswith(".tar.gz") |
| | or source.endswith(".tgz") |
| | or source.endswith(".gz") |
| | ): |
| | out = dest.replace(".gz", "") |
| | with gzip.open(dest, "rb") as f_in: |
| | with open(out, "wb") as f_out: |
| | shutil.copyfileobj(f_in, f_out) |
| | else: |
| | shutil.unpack_archive(dest, dest_unpack) |
| | if write_permissions: |
| | set_writing_permissions(dest_unpack) |
| |
|
| |
|
| | def set_writing_permissions(folder_path): |
| | """ |
| | This function sets user writing permissions to all the files in the given folder. |
| | Arguments |
| | --------- |
| | folder_path : folder |
| | Folder whose files will be granted write permissions. |
| | """ |
| | for root, dirs, files in os.walk(folder_path): |
| | for file_name in files: |
| | file_path = os.path.join(root, file_name) |
| | |
| | os.chmod(file_path, 0o666) |