File size: 13,445 Bytes
9654d7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177e39c
9654d7a
 
 
 
 
 
ab17375
9654d7a
 
ab17375
9654d7a
 
489486f
13203c7
0efeb82
177e39c
56bb6b0
177e39c
9654d7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
066793c
 
 
 
 
 
 
 
 
9f10971
9654d7a
 
d31329c
9fbbd6e
9654d7a
 
8b72fdf
066793c
9f10971
9654d7a
 
 
 
 
7a8567a
 
 
 
 
9654d7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab17375
9654d7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b69f9a8
9654d7a
 
56bb6b0
2fa0ad0
3aa13cd
9654d7a
 
 
 
 
 
 
 
 
 
a1468ba
 
9654d7a
 
 
ab17375
 
8bc3012
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9654d7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ba22de
9654d7a
 
 
 
 
 
 
 
 
 
ab17375
ff38499
ab17375
 
d633cf8
2800183
d633cf8
2800183
 
ab17375
af5cbcc
f060065
377b59c
1be08e5
fecae0a
8424c41
1265dc9
9654d7a
8199fea
 
 
 
 
 
 
0f0173e
ad951e6
0f0173e
6f7b13c
0f0173e
 
 
9654d7a
 
 
 
c5ccd26
9654d7a
 
 
 
 
 
 
 
369705f
1be08e5
9fbbd6e
 
6541e65
1be08e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336870f
cc849bc
a73a1b6
 
c47fe1f
 
cc849bc
56bb6b0
 
 
 
1be08e5
 
56bb6b0
1be08e5
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# 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 io import BytesIO 
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 datasets
import urllib3
import zipfile

import traceback
import fsspec as fs
import librosa

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": {
        "dev": {
            1:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_mp4_1.zip",
            2:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_mp4_2.zip",
            3:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_mp4_3.zip",
            4:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_mp4_4.zip",
            5:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_mp4_5.zip",
            6:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_mp4_6.zip",

        },
        "test": {1:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_test_mp4.zip"}
    },
    "audio1": {
        "dev": {1:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox1/vox1_dev_wav.zip"},
        "test": {1:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox1/vox1_test_wav.zip"}
    },
    "audio2": {
        "dev": 
            {1:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_aac_1.zip",2:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/vox2/vox2_aac_2.zip"},
        "test": {1:"https://huggingface.co/datasets/ProgramComputer/voxceleb/resolve/main/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["dev"], urls["dev"]), (urls["test"], (urls["test"],)))
# )


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 VoxCeleb(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.startswith("audio"):
            features["speaker_name"] = datasets.Value("string")
            features["speaker_nationality"] = datasets.Value("string")
            features["audio"] = datasets.Audio(mono=False)
        if self.config.name.startswith("video"):
            features["video"] = datasets.Value("large_binary")

        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):
        # if dl_manager.is_streaming:
        #     raise TypeError("Streaming is not supported for VoxCeleb")
        targets = (
            ["audio1", "audio2"] if self.config.name == "audio" else [self.config.name]
        )


        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.download_and_extract(
                dict(
                    (
                        placeholder_key,
                        dict(
                            (target, _URLS[target][placeholder_key])
                            for target in targets
                        ),
                    )
                    for placeholder_key in ("dev", "test")
                ))
        
     
        apply_function_recursive = lambda d, f: {k: apply_function_recursive(v, f) if isinstance(v, dict) else f(v) for k, v in d.items()}

        mapped_paths = apply_function_recursive(mapped_paths, dl_manager.iter_files)
        return [
            datasets.SplitGenerator(
                name="train",
                gen_kwargs={
                    "paths":mapped_paths["dev"],
                    "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",
            )
            for path in paths[conf].values():
                for file in path:
                    # subdirs = [x[0] for x in os.walk(path)]
                    # raise Exception(subdirs)
                    #raise Exception(file)
                    #raise Exception(os.is_symlink(path))
                    #raise Exception(os.listdir(path))
                    try:
                        t =  tuple(file.split("::")[0].split("/")[2:])
                        _,dataset_format,speaker,video_id,clip_index=  (None,) * (5 - len(t)) + t
                    except Exception:
                        raise Exception(file.split("::")[0].split("/")[2:])
                    speaker_info = meta.loc[speaker]
                    clip_index = int(Path(clip_index).stem)
                    info = {
                        "file": file,
                        "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"):
                        if dataset_format == "aac":
                            with fs.open(info["file"], 'rb') as f:
                                z = BytesIO(f.read())
                                Path('./temp.m4a').write_bytes(z.getbuffer())
                                y, sr = librosa.load('./temp.m4a')
                                #y, sr = librosa.load(f)
                                info["audio"] = {'array':y,'path':info["file"],'sampling_rate':sr}
                        else:
                            info["audio"] = info["file"]

                            
                    if conf.startswith("video"):
                        with fs.open(info["file"], 'rb') as f:
                      
                            info["video"] = BytesIO(f.read()).getvalue()
                    yield key, info
                    key += 1