test123 / test123.py
thangylvp's picture
Add dataset loading script
1e2f665 verified
Raw
History Blame Contribute Delete
4.14 kB
import io
import tarfile
import json
from collections import defaultdict
import glob
import os
import pyzipper
from datasets import GeneratorBasedBuilder, DatasetInfo, SplitGenerator, Features, Value
TEXT_EXTS = {".txt", ".json", ".rttm"}
class Test500(GeneratorBasedBuilder):
VERSION = "1.0.0"
def _info(self):
# Flexible schema: features resolved at runtime
return DatasetInfo(
description="Sample-level tar dataset (grouped by channel + sample_id)",
features=Features(
{
"channel": Value("string"),
"id": Value("string"),
"transcribe_assembly": Value("string"),
"tokenize_vibevoice": Value("binary"),
"diarize_pyannote": Value("string"),
"transcribe_wav2vec2": Value("binary"),
}
),
)
def _split_generators(self, dl_manager):
# 1. Resolve where the files live
if self.config.data_dir is not None:
# Local testing
pattern = os.path.join(self.config.data_dir, "batch_*.tar")
tar_files = sorted(glob.glob(pattern))
else:
# HF Hub: use virtual paths, then download them
pattern = "batch_*.tar"
hf_paths = sorted(
glob.glob(os.path.join(dl_manager._base_path, pattern))
)
if not hf_paths:
raise FileNotFoundError(
f"No tar files found in HF repo cache at {dl_manager._base_path}"
)
# 🔑 THIS IS THE CRITICAL STEP
tar_files = dl_manager.download(hf_paths)
if not tar_files:
raise FileNotFoundError("No tar files resolved for dataset")
return [
SplitGenerator(
name="train",
gen_kwargs={"tar_files": tar_files},
)
]
def _generate_examples(self, zip_files):
idx = 0
# buffer for building one sample at a time
current = None
current_key = None
password = os.environ.get('HF_ZIP_PASSWORD', 'default_password').encode("utf-8")
# password = self.ZIP_PASSWORD.encode("utf-8")
for zip_path in zip_files:
with pyzipper.AESZipFile(zip_path, "r") as zf:
zf.setpassword(password)
for name in sorted(zf.namelist()):
with zf.open(name) as f:
data = f.read()
# -------- PARSE NAME --------
# format: channel$sample_id$feature.ext
try:
channel, sample_id, rest = name.split("$", 2)
feature, ext = rest.rsplit(".", 1)
ext = "." + ext
except ValueError:
# skip malformed files
continue
# print(channel, sample_id, feature, ext)
key = (channel, sample_id)
# -------- FLUSH PREVIOUS SAMPLE --------
if current_key is not None and key != current_key:
yield idx, current
idx += 1
current = None
# -------- INIT SAMPLE --------
if current is None:
current_key = key
current = {
"channel": channel,
"id": sample_id,
}
# -------- LOAD FEATURE --------
if ext in TEXT_EXTS:
try:
current[feature] = data.decode("utf-8")
except Exception:
current[feature] = data
else:
current[feature] = data
# -------- FINAL SAMPLE --------
if current is not None:
yield idx, current