File size: 4,102 Bytes
e8506b6 | 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 | import io
import tarfile
import json
from collections import defaultdict
import glob
import os
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, tar_files):
idx = 0
# buffer for building one sample at a time
current = None
current_key = None
for tar_path in tar_files:
with tarfile.open(tar_path, "r:*") as tar:
for member in tar:
if not member.isfile():
continue
f = tar.extractfile(member)
if f is None:
continue
name = member.name
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 |