new_dataset_stt / dataset.py
Elyordev's picture
Upload dataset.py
40a22e8 verified
raw
history blame
9.12 kB
# 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