File size: 6,499 Bytes
e3c318d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2023 GTTS (http://gtts.ehu.eus)
#
# 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
"""Basque Parliament dataset"""


import datasets
from datasets.utils.py_utils import size_str
import os
import csv
from tqdm import tqdm

from .languages import LANGUAGES
from .release_stats import STATS


_CITATION = """\
"""

_HOMEPAGE = "https://huggingface.co/datasets/gttsehu/basque_parliament_1"

_LICENSE = "https://creativecommons.org/publicdomain/zero/1.0/"

_DESCRIPTION = (
    f"Basque Parliament dataset blah blah blah..."
    f"blah blah blah..."
    f"blah blah blah..."
)

_BASE_URL = "https://huggingface.co/datasets/gttsehu/basque_parliament_1/resolve/main/"

_AUDIO_URL = _BASE_URL + "audio/{split}_{shard_idx}.tar"
_METADATA_URL =  _BASE_URL + "metadata/{split}.tsv"

class BasqueParliamentConfig(datasets.BuilderConfig):
    """BuilderConfig for BasqueParliament."""

    def __init__(self, name, version, **kwargs):
        self.language = kwargs.pop("language", None)
        self.release_date = kwargs.pop("release_date", None)
        self.num_clips = kwargs.pop("num_clips", None)
        self.num_speakers = kwargs.pop("num_speakers", None)
        self.validated_hr = kwargs.pop("validated_hr", None)
        self.total_hr = kwargs.pop("total_hr", None)
        self.size_bytes = kwargs.pop("size_bytes", None)
        self.size_human = size_str(self.size_bytes)
        description = _DESCRIPTION

        super(BasqueParliamentConfig, self).__init__(
            name = name,
            version = datasets.Version(version),
            description = _DESCRIPTION,
            **kwargs,
        )


class BasqueParliament(datasets.GeneratorBasedBuilder):
    """Basque Parliament is a free Basque-Spanish speech corpus."""

    DEFAULT_CONFIG_NAME = "all"
    
    BUILDER_CONFIGS = [
        BasqueParliamentConfig(
            name=lang,
            version=STATS["version"],
            language=LANGUAGES[lang],
            release_date=STATS["date"],
            num_clips=lang_stats["clips"],
            num_speakers=lang_stats["users"],
            total_hr=float(lang_stats["totalHrs"]) if lang_stats["totalHrs"] else None,
            size_bytes=int(lang_stats["size"]) if lang_stats["size"] else None,
        )
        for lang, lang_stats in STATS["locales"].items()
    ]

    def _info(self):
        description = (
            f"Basque Parliament dataset blah blah blah..."
            f"blah blah blah..."
            f"blah blah blah..."
        )
        features = datasets.Features(
            {
                "path": datasets.Value("string"),
                "audio": datasets.features.Audio(sampling_rate=16_000),
                "sentence": datasets.Value("string"),
                "speaker_id": datasets.Value("string"),
                "language": datasets.Value("string"),
                "PRR": datasets.Value("float32"),
                "length": datasets.Value("float32"),
            }
        )

        return datasets.DatasetInfo(
            description = _DESCRIPTION,
            features = features,
            supervised_keys = None,
            homepage = _HOMEPAGE,
            license = _LICENSE,
            citation = _CITATION,
            version = self.config.version,
        )


    def _split_generators(self, dl_manager):
        lang = self.config.name
        
        audio_urls = {}
        splits = ("train", "train_clean", "dev", "test")
        for split in splits:
            if split == "train_clean": continue
            audio_urls[split] = [
                _AUDIO_URL.format(split=split, shard_idx=i) for i in range(STATS["n_shards"][split])
            ]
        audio_urls["train_clean"]=audio_urls["train"]
        archive_paths = dl_manager.download(audio_urls)
        local_extracted_archive_paths = dl_manager.extract(archive_paths) if not dl_manager.is_streaming else {}

        metadata_urls = {split: _METADATA_URL.format(lang=lang, split=split) for split in splits}
        metadata_paths = dl_manager.download_and_extract(metadata_urls)

        split_generators = []
        split_names = {
            "train": datasets.Split.TRAIN,
            "dev": datasets.Split.VALIDATION,
            "test": datasets.Split.TEST,
        }
        for split in splits:
            split_generators.append(
                datasets.SplitGenerator(
                    name=split_names.get(split, split),
                    gen_kwargs={
                        "local_extracted_archive_paths": local_extracted_archive_paths.get(split),
                        "archives": [dl_manager.iter_archive(path) for path in archive_paths.get(split)],
                        "metadata_path": metadata_paths[split],
                    },
                ),
            )

        return split_generators

    def _generate_examples(self, local_extracted_archive_paths, archives, metadata_path):
        lang = self.config.name
        data_fields = list(self._info().features.keys())
        metadata = {}
        with open(metadata_path, encoding="utf-8") as f:
            reader = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
            metadata = { row["path"]:row for row in tqdm(reader, desc="Reading metadata...") }

        excluded = 0
        for i, audio_archive in enumerate(archives):
            for path, file in audio_archive:
                if path not in metadata :
                    excluded += 1
                    continue
                result = dict(metadata[path])
                if lang == "all" or lang == result["language"] :
                    # set the audio feature and the path to the extracted file
                    path = os.path.join(local_extracted_archive_paths[i], path) if local_extracted_archive_paths else path
                    result["audio"] = {"path": path, "bytes": file.read()}
                    result["path"] = path
                    yield path, result
        print(excluded,'audio files not found in metadata')