test / test.py
ProgramComputer's picture
Update test.py
f21aa66
raw
history blame
19.7 kB
# coding=utf-8
# Copyright 2022 The HuggingFace Datasets Authors and Arjun Barrett.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""VoxCeleb audio-visual human speech dataset."""
import json
import os
from getpass import getpass
from hashlib import sha256
from itertools import repeat
from multiprocessing import Manager, Pool, Process
from pathlib import Path
from shutil import copyfileobj
import pandas as pd
import requests
import callable
import datasets
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
_CITATION = """\
@Article{Nagrani19,
author = "Arsha Nagrani and Joon~Son Chung and Weidi Xie and Andrew Zisserman",
title = "Voxceleb: Large-scale speaker verification in the wild",
journal = "Computer Science and Language",
year = "2019",
publisher = "Elsevier",
}
@InProceedings{Chung18b,
author = "Chung, J.~S. and Nagrani, A. and Zisserman, A.",
title = "VoxCeleb2: Deep Speaker Recognition",
booktitle = "INTERSPEECH",
year = "2018",
}
@InProceedings{Nagrani17,
author = "Nagrani, A. and Chung, J.~S. and Zisserman, A.",
title = "VoxCeleb: a large-scale speaker identification dataset",
booktitle = "INTERSPEECH",
year = "2017",
}
"""
_DESCRIPTION = """\
VoxCeleb is an audio-visual dataset consisting of short clips of human speech, extracted from interview videos uploaded to YouTube
"""
_URL = "https://mm.kaist.ac.kr/datasets/voxceleb"
_URLS = {
"video": {
"placeholder": "hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partaa",
"dev": (
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partaa",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partab",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partac",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partad",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partae",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partaf",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partag",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partah",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_mp4_partai",
),
"test": "hf://datasets/ProgramComputer/voxceleb/vox2/vox2_test_mp4.zip",
},
"audio1": {
"placeholder": "hf://datasets/ProgramComputer/voxceleb/vox1/vox1_dev_wav_partaa",
"dev": (
"hf://datasets/ProgramComputer/voxceleb/vox1/vox1_dev_wav_partaa",
"hf://datasets/ProgramComputer/voxceleb/vox1/vox1_dev_wav_partab",
"hf://datasets/ProgramComputer/voxceleb/vox1/vox1_dev_wav_partac",
"hf://datasets/ProgramComputer/voxceleb/vox1/vox1_dev_wav_partad",
),
"test": "hf://datasets/ProgramComputer/voxceleb/vox1/vox1_test_wav.zip",
},
"audio2": {
"placeholder": "hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partaa",
"dev": (
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partaa",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partab",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partac",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partad",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partae",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partaf",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partag",
"hf://datasets/ProgramComputer/voxceleb/vox2/vox2_dev_aac_partah",
),
"test": "hf://datasets/ProgramComputer/voxceleb/vox2/vox2_test_aac.zip",
},
}
_DATASET_IDS = {"video": "vox2", "audio1": "vox1", "audio2": "vox2"}
_PLACEHOLDER_MAPS = dict(
value
for urls in _URLS.values()
for value in ((urls["placeholder"], urls["dev"]), (urls["test"], (urls["test"],)))
)
class NestedDataStructure:
def __init__(self, data=None):
self.data = data if data is not None else []
def flatten(self, data=None):
data = data if data is not None else self.data
if isinstance(data, dict):
return self.flatten(list(data.values()))
elif isinstance(data, (list, tuple)):
return [flattened for item in data for flattened in self.flatten(item)]
else:
return [data]
def map_nested(
function: Callable[[Any], Any],
data_struct: Any,
dict_only: bool = False,
map_list: bool = True,
map_tuple: bool = False,
map_numpy: bool = False,
num_proc: Optional[int] = None,
parallel_min_length: int = 2,
types: Optional[tuple] = None,
disable_tqdm: bool = True,
desc: Optional[str] = None,
) -> Any:
"""Apply a function recursively to each element of a nested data struct.
Use multiprocessing if num_proc > 1 and the length of data_struct is greater than or equal to
`parallel_min_length`.
<Changed version="2.5.0">
Before version 2.5.0, multiprocessing was not used if `num_proc` was greater than or equal to ``len(iterable)``.
Now, if `num_proc` is greater than or equal to ``len(iterable)``, `num_proc` is set to ``len(iterable)`` and
multiprocessing is used.
</Changed>
Args:
function (`Callable`): Function to be applied to `data_struct`.
data_struct (`Any`): Data structure to apply `function` to.
dict_only (`bool`, default `False`): Whether only apply `function` recursively to `dict` values in
`data_struct`.
map_list (`bool`, default `True`): Whether also apply `function` recursively to `list` elements (besides `dict`
values).
map_tuple (`bool`, default `False`): Whether also apply `function` recursively to `tuple` elements (besides
`dict` values).
map_numpy (`bool, default `False`): Whether also apply `function` recursively to `numpy.array` elements (besides
`dict` values).
num_proc (`int`, *optional*): Number of processes.
parallel_min_length (`int`, default `2`): Minimum length of `data_struct` required for parallel
processing.
<Added version="2.5.0"/>
types (`tuple`, *optional*): Additional types (besides `dict` values) to apply `function` recursively to their
elements.
disable_tqdm (`bool`, default `True`): Whether to disable the tqdm progressbar.
desc (`str`, *optional*): Prefix for the tqdm progressbar.
Returns:
`Any`
"""
if types is None:
types = []
if not dict_only:
if map_list:
types.append(list)
if map_tuple:
types.append(tuple)
if map_numpy:
types.append(np.ndarray)
types = tuple(types)
# Singleton
if not isinstance(data_struct, dict) and not isinstance(data_struct, types):
return function(data_struct)
disable_tqdm = disable_tqdm or not logging.is_progress_bar_enabled()
iterable = list(data_struct.values()) if isinstance(data_struct, dict) else data_struct
if num_proc is None:
num_proc = 1
if num_proc != -1 and num_proc <= 1 or len(iterable) < parallel_min_length:
mapped = [
_single_map_nested((function, obj, types, None, True, None))
for obj in logging.tqdm(iterable, disable=disable_tqdm, desc=desc)
]
else:
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message=".* is experimental and might be subject to breaking changes in the future\\.$",
category=UserWarning,
)
mapped = parallel_map(function, iterable, num_proc, types, disable_tqdm, desc, _single_map_nested)
if isinstance(data_struct, dict):
return dict(zip(data_struct.keys(), mapped))
else:
if isinstance(data_struct, list):
return mapped
elif isinstance(data_struct, tuple):
return tuple(mapped)
else:
return np.array(mapped)
def _mp_download(
url,
tmp_path,
resume_pos,
length,
queue,
):
if length == resume_pos:
return
with open(tmp_path, "ab" if resume_pos else "wb") as tmp:
headers = {}
if resume_pos != 0:
headers["Range"] = f"bytes={resume_pos}-"
response = requests.get(
url, headers=headers, stream=True
)
if response.status_code >= 200 and response.status_code < 300:
for chunk in response.iter_content(chunk_size=65536):
queue.put(len(chunk))
tmp.write(chunk)
else:
raise ConnectionError("failed to fetch dataset")
class Test(datasets.GeneratorBasedBuilder):
"""VoxCeleb is an unlabled dataset consisting of short clips of human speech from interviews on YouTube"""
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="video", version=VERSION, description="Video clips of human speech"
),
datasets.BuilderConfig(
name="audio", version=VERSION, description="Audio clips of human speech"
),
datasets.BuilderConfig(
name="audio1",
version=datasets.Version("1.0.0"),
description="Audio clips of human speech from VoxCeleb1",
),
datasets.BuilderConfig(
name="audio2",
version=datasets.Version("2.0.0"),
description="Audio clips of human speech from VoxCeleb2",
),
]
def _info(self):
features = {
"file": datasets.Value("string"),
"file_format": datasets.Value("string"),
"dataset_id": datasets.Value("string"),
"speaker_id": datasets.Value("string"),
"speaker_gender": datasets.Value("string"),
"video_id": datasets.Value("string"),
"clip_index": datasets.Value("int32"),
}
if self.config.name == "audio1":
features["speaker_name"] = datasets.Value("string")
features["speaker_nationality"] = datasets.Value("string")
if self.config.name.startswith("audio"):
features["audio"] = datasets.Audio(sampling_rate=16000)
return datasets.DatasetInfo(
description=_DESCRIPTION,
homepage=_URL,
supervised_keys=datasets.info.SupervisedKeysData("file", "speaker_id"),
features=datasets.Features(features),
citation=_CITATION,
)
def _split_generators(self, dl_manager):
targets = (
["audio1", "audio2"] if self.config.name == "audio" else [self.config.name]
)
def self_download_custom(url_or_urls, custom_download):
nonlocal dl_manager
"""
Download given urls(s) by calling `custom_download`.
Args:
url_or_urls (`str` or `list` or `dict`):
URL or `list` or `dict` of URLs to download and extract. Each URL is a `str`.
custom_download (`Callable[src_url, dst_path]`):
The source URL and destination path. For example
`tf.io.gfile.copy`, that lets you download from Google storage.
Returns:
downloaded_path(s): `str`, The downloaded paths matching the given input
`url_or_urls`.
Example:
```py
>>> downloaded_files = dl_manager.download_custom('s3://my-bucket/data.zip', custom_download_for_my_private_bucket)
```
"""
cache_dir = dl_manager.download_config.cache_dir #or config.DOWNLOADED_DATASETS_PATH
max_retries = dl_manager.download_config.max_retries
def url_to_downloaded_path(url):
return os.path.join(cache_dir, hash_url_to_filename(url))
downloaded_path_or_paths = map_nested(
url_to_downloaded_path, url_or_urls, disable_tqdm=not is_progress_bar_enabled()
)
url_or_urls = NestedDataStructure(url_or_urls)
downloaded_path_or_paths = NestedDataStructure(downloaded_path_or_paths)
for url, path in zip(url_or_urls.flatten(), downloaded_path_or_paths.flatten()):
try:
get_from_cache(
url, cache_dir=cache_dir, local_files_only=True, use_etag=False, max_retries=max_retries
)
cached = True
except FileNotFoundError:
cached = False
if not cached or dl_manager.download_config.force_download:
custom_download(url, path)
get_from_cache(
url, cache_dir=cache_dir, local_files_only=True, use_etag=False, max_retries=max_retries
)
dl_manager._record_sizes_checksums(url_or_urls, downloaded_path_or_paths)
return downloaded_path_or_paths.data
def download_custom(placeholder_url, path):
nonlocal dl_manager
sources = _PLACEHOLDER_MAPS[placeholder_url]
tmp_paths = []
lengths = []
start_positions = []
for url in sources:
head = requests.head(url,timeout=5,stream=True,allow_redirects=True,verify=False)
if head.status_code == 401:
raise ValueError("failed to authenticate with VoxCeleb host")
if head.status_code < 200 or head.status_code >= 300:
raise ValueError("failed to fetch dataset")
content_length = head.headers.get("Content-Length")
if content_length is None:
raise ValueError("expected non-empty Content-Length")
content_length = int(content_length)
tmp_path = Path(path + "." + sha256(url.encode("utf-8")).hexdigest())
tmp_paths.append(tmp_path)
lengths.append(content_length)
start_positions.append(
tmp_path.stat().st_size
if tmp_path.exists() and dl_manager.download_config.resume_download
else 0
)
def progress(q, cur, total):
with datasets.utils.logging.tqdm(
unit="B",
unit_scale=True,
total=total,
initial=cur,
desc="Downloading",
disable=not datasets.utils.logging.is_progress_bar_enabled(),
) as progress:
while cur < total:
try:
added = q.get(timeout=1)
progress.update(added)
cur += added
except:
continue
manager = Manager()
q = manager.Queue()
with Pool(len(sources)) as pool:
proc = Process(
target=progress,
args=(q, sum(start_positions), sum(lengths)),
daemon=True,
)
proc.start()
pool.starmap(
_mp_download,
zip(
sources,
tmp_paths,
start_positions,
lengths,
repeat(q),
),
)
pool.close()
proc.join()
with open(path, "wb") as out:
for tmp_path in tmp_paths:
with open(tmp_path, "rb") as tmp:
copyfileobj(tmp, out)
tmp_path.unlink()
metadata = dl_manager.download(
dict(
(
target,
f"https://mm.kaist.ac.kr/datasets/voxceleb/meta/{_DATASET_IDS[target]}_meta.csv",
)
for target in targets
)
)
mapped_paths = dl_manager.extract(self_download_custom(
dict(
(
placeholder_key,
dict(
(target, _URLS[target][placeholder_key])
for target in targets
),
)
for placeholder_key in ("placeholder", "test")
),
download_custom,
))
return [
datasets.SplitGenerator(
name="train",
gen_kwargs={
"paths": mapped_paths["placeholder"],
"meta_paths": metadata,
},
),
datasets.SplitGenerator(
name="test",
gen_kwargs={
"paths": mapped_paths["test"],
"meta_paths": metadata,
},
),
]
def _generate_examples(self, paths, meta_paths):
key = 0
for conf in paths:
dataset_id = "vox1" if conf == "audio1" else "vox2"
meta = pd.read_csv(
meta_paths[conf],
sep="\t" if conf == "audio1" else " ,",
index_col=0,
engine="python",
)
dataset_path = next(Path(paths[conf]).iterdir())
dataset_format = dataset_path.name
for speaker_path in dataset_path.iterdir():
speaker = speaker_path.name
speaker_info = meta.loc[speaker]
for video in speaker_path.iterdir():
video_id = video.name
for clip in video.iterdir():
clip_index = int(clip.stem)
info = {
"file": str(clip),
"file_format": dataset_format,
"dataset_id": dataset_id,
"speaker_id": speaker,
"speaker_gender": speaker_info["Gender"],
"video_id": video_id,
"clip_index": clip_index,
}
if dataset_id == "vox1":
info["speaker_name"] = speaker_info["VGGFace1 ID"]
info["speaker_nationality"] = speaker_info["Nationality"]
if conf.startswith("audio"):
info["audio"] = info["file"]
yield key, info
key += 1