File size: 9,117 Bytes
40a22e8
 
 
 
 
 
 
 
 
 
5820821
40a22e8
 
5820821
 
40a22e8
 
 
 
 
 
 
 
 
 
 
 
5820821
 
 
40a22e8
 
5820821
f50b5e1
40a22e8
 
5820821
40a22e8
 
 
 
 
 
 
 
 
5820821
 
 
40a22e8
 
 
 
 
 
 
 
 
 
 
 
 
 
62eb364
40a22e8
 
5820821
62eb364
40a22e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5820821
40a22e8
 
 
 
 
 
5820821
 
40a22e8
5820821
 
40a22e8
 
 
 
 
 
 
 
5820821
40a22e8
 
5820821
 
 
 
 
40a22e8
 
 
 
 
 
5820821
 
 
40a22e8
 
5820821
 
 
62eb364
40a22e8
 
62eb364
40a22e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5820821
40a22e8
 
 
 
 
5820821
40a22e8
 
 
 
5820821
40a22e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# coding=utf-8
# Copyright 2023
#
# Licensed under the Apache License, Version 2.0 (the "License");
# http://www.apache.org/licenses/LICENSE-2.0
#
# Ushbu fayl Common Voice uslubidagi dataset loading script bo'lib,
# audio/uz/<split>/<split>.tar va transcript/uz/<split>/<split>.tsv
# fayllarni yuklab, audio+transkriptsiyani birlashtiradi.

import os
import csv
import json

import datasets
from datasets.utils.py_utils import size_str


# ------------------ 1. Metadata va sozlamalar ------------------
_CITATION = """\

@misc{yourcitation,

  title  = {Your STT dataset title},

  author = {You or your org},

  year   = {2023},

  url    = {https://huggingface.co/datasets/Elyordev/new_dataset_stt_audio}

}

"""

_DESCRIPTION = """\

Bu dataset mp3 formatdagi audio fayllar va tsv metadata fayllardan iborat.

Papka tuzilishi Common Voice uslubiga o'xshash:

audio/uz/[train|validation|test]/*.tar va transcript/uz/[train|validation|test]/*.tsv

"""

_HOMEPAGE = "https://huggingface.co/datasets/Elyordev/new_dataset_stt_audio"
_LICENSE = "Apache License 2.0"

# Bitta til: "uz" (xohlasangiz ko'paytirishingiz mumkin)
LANGUAGES = {
    "uz": {
        "language_name": "Uzbek",
        "num_clips": None,      # Agar xohlasangiz, taxminiy klip sonini kiriting
        "num_speakers": None,
        "validated_hr": None,
        "total_hr": None,
        "size_bytes": None,
    },
}

# Bizda har bir splitda 1 dona tar shard bor deb faraz qilamiz
N_SHARDS = {
    "uz": {
        "train": 1,
        "validation": 1,
        "test": 1,
    }
}

# Asosiy URL: repodagi fayllarni resolve qilish uchun
_BASE_URL = "https://huggingface.co/datasets/Elyordev/new_dataset_stt_audio/resolve/main/"

# Audio fayl yo'li: audio/uz/<split>/<split>.tar
_AUDIO_URL = _BASE_URL + "audio/{lang}/{split}/{split}.tar"

# Transcript fayl yo'li: transcript/uz/<split>/<split>.tsv
_TRANSCRIPT_URL = _BASE_URL + "transcript/{lang}/{split}/{split}.tsv"


# ------------------ 2. Config klassi ------------------
class NewDatasetSTTAudioConfig(datasets.BuilderConfig):
    """Bitta config (masalan, 'uz') - xohlasangiz ko'proq tillarni ham qo'shishingiz mumkin."""
    def __init__(self, language, **kwargs):
        super().__init__(**kwargs)
        self.language = language
        self.num_clips = LANGUAGES[language]["num_clips"]
        self.num_speakers = LANGUAGES[language]["num_speakers"]
        self.validated_hr = LANGUAGES[language]["validated_hr"]
        self.total_hr = LANGUAGES[language]["total_hr"]
        self.size_bytes = LANGUAGES[language]["size_bytes"]
        self.size_human = size_str(self.size_bytes) if self.size_bytes else None


# ------------------ 3. Asosiy dataset builder ------------------
class NewDatasetSTTAudio(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        # Masalan, faqat "uz" config
        NewDatasetSTTAudioConfig(
            name="uz",
            version=datasets.Version("1.0.0"),
            description="Uzbek STT dataset with Common Voice-like structure",
            language="uz",
        ),
    ]
    DEFAULT_WRITER_BATCH_SIZE = 1000

    def _info(self):
        lang = self.config.language
        # O'zingiz xohlagancha izoh tuzishingiz mumkin
        description = (
            f"Common Voice uslubidagi dataset: til = {lang}. "
            f"{_DESCRIPTION}"
        )
        features = datasets.Features(
            {
                "id": datasets.Value("string"),
                "path": datasets.Value("string"),
                "audio": datasets.features.Audio(sampling_rate=16000),  # agar 16kHz bo'lsa
                "sentence": datasets.Value("string"),
                "age": datasets.Value("string"),
                "gender": datasets.Value("string"),
                "accents": datasets.Value("string"),
                "locale": datasets.Value("string"),
                "duration": datasets.Value("float"),  # agar tsv da float bo'lsa
            }
        )
        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):
        """

        Common Voice misolida bo'lgani kabi:

        train, validation, test splitlari uchun tar va tsv fayllarni yuklaymiz.

        """
        lang = self.config.language
        n_shards = N_SHARDS[lang]  # {'train':1, 'validation':1, 'test':1}
        split_generators = []

        # Bizda splits = ["train", "validation", "test"]
        for split in ["train", "validation", "test"]:
            # Audio (tar) URL lar ro'yxati (har bir splitda bitta shard)
            audio_urls = [
                _AUDIO_URL.format(lang=lang, split=split, shard_idx=i)
                for i in range(n_shards[split])
            ]
            # .tar fayllarni yuklab olamiz
            audio_paths = dl_manager.download(audio_urls)

            # .tar fayllarni streaming yoki to'liq extract qilamiz
            # Common Voice 'iter_archive' orqali stream qiladi, lekin biz local_extracted qilsak ham bo'ladi
            local_extracted_archive_paths = []
            if not dl_manager.is_streaming:
                local_extracted_archive_paths = dl_manager.extract(audio_paths)

            # Transcript (tsv) URL
            transcript_url = _TRANSCRIPT_URL.format(lang=lang, split=split)
            transcript_path = dl_manager.download_and_extract(transcript_url)

            split_generators.append(
                datasets.SplitGenerator(
                    name=getattr(datasets.Split, split.upper()),
                    gen_kwargs={
                        "archives": [
                            dl_manager.iter_archive(path) for path in audio_paths
                        ],
                        "local_extracted_archive_paths": local_extracted_archive_paths,
                        "meta_path": transcript_path,
                    },
                )
            )

        return split_generators

    def _generate_examples(self, archives, local_extracted_archive_paths, meta_path):
        """

        Har bir split uchun:

        1) transcript .tsv faylni o'qish

        2) audio tar ichidagi fayllarni "archives" orqali iteratsiya qilish

        3) tsv'dagi 'path' bilan audio fayl nomini bog'lash

        4) natijada (key, example) qaytarish

        """
        # Tsv fayl (meta_path) ni o'qib, metadata lug'atini tuzamiz
        # formati: { "filename.mp3": { ... ustunlar ... } }
        metadata = {}
        with open(meta_path, encoding="utf-8") as f:
            reader = csv.DictReader(f, delimiter="\t")
            for row in reader:
                # Ehtiyot chorasi: agar path .mp3 bilan tugamasa, qo'shamiz
                if not row["path"].endswith(".mp3"):
                    row["path"] += ".mp3"
                metadata[row["path"]] = row

        # Endi tar fayllarni o'qish
        # Common Voice misolida bir splitda bir nechta shard bo'lishi mumkin, shuning uchun ro'yxat
        for shard_idx, archive in enumerate(archives):
            # archive = dl_manager.iter_archive(path) => (path_in_tar, fileobj) generator
            for path_in_tar, fileobj in archive:
                # Masalan, path_in_tar = "common_voice_uz_12345.mp3"
                _, filename = os.path.split(path_in_tar)
                if filename in metadata:
                    # Metadata qatorini olish
                    row = metadata[filename]
                    # local_extracted_archive_paths[shard_idx] => .tar fayl extract qilingan joy
                    # Agar to'liq extract bo'lmagan bo'lsa, to'g'ridan-to'g'ri bytes bilan ham ishlasa bo'ladi
                    # Common Voice rasmiy misolida 'result["audio"] = {"path": path, "bytes": file.read()}' qilingan

                    example = dict(row)
                    # "id" ustuni bo'lmasa, idx sifatida path_in_tar dan foydalansa bo'ladi
                    if "id" not in example:
                        example["id"] = filename

                    # Audio: tar fayl ichidan o'qilgan bytes
                    # Datasets "Audio" featuri "bytes" ni o'z-o'zidan tan olmaydi,
                    # lekin "path" + "bytes" berish uslubi Common Voice scriptida ishlatilgan
                    # Keyingi bosqichda decode qilinadi
                    example["audio"] = {
                        "path": path_in_tar,
                        "bytes": fileobj.read(),
                    }

                    # Qo'shimcha ustunlarni ham row dan olamiz:
                    # sentence, age, gender, accents, locale, duration, ...
                    # Agar bo'lmasa, bo'sh qiymat kiritiladi
                    # Biz "metadata"dan oldin dict(row) deb oldik, demak "example"da hamma ustun bor.

                    yield path_in_tar, example