File size: 29,489 Bytes
a1cd84e
 
 
 
 
 
 
 
 
9334950
a1cd84e
 
9334950
a1cd84e
 
 
 
 
 
 
 
 
 
9334950
 
 
 
 
a1cd84e
 
9334950
 
 
 
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baee4fc
a1cd84e
 
 
 
 
 
 
3ea4cde
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baee4fc
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9334950
 
 
 
 
 
 
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9334950
 
 
a1cd84e
 
9334950
 
a1cd84e
 
9334950
 
 
 
 
a1cd84e
 
 
9334950
 
 
 
 
 
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9334950
 
 
a1cd84e
9334950
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9334950
 
 
 
 
 
 
 
 
 
 
 
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cde
a1cd84e
3ea4cde
a1cd84e
 
 
 
 
3ea4cde
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cde
a1cd84e
 
 
 
3ea4cde
a1cd84e
 
 
 
 
 
 
3ea4cde
 
 
 
 
 
a1cd84e
 
 
4689281
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
"""Stream paired Hindi/English speech into resumable 24 kHz training shards."""

import argparse
import gzip
import hashlib
import io
import json
import math
import os
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
import re
import tempfile
import time
import unicodedata
from collections import Counter
from dataclasses import dataclass
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import torch
from datasets import Audio, Dataset, load_dataset
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
try:
    from huggingface_hub.utils import disable_progress_bars
    disable_progress_bars()
except Exception:
    pass
from scipy.io import wavfile
from scipy.signal import resample_poly
try:
    import torchaudio.transforms as _TA_T
except Exception:
    _TA_T = None

_RESAMPLERS = {}

from data.audio_processor import read_audio_bytes, read_audio_file

ROOT = "bilingual_1000h"
RATE = 24000
MIN_SECONDS = 1.5
MAX_SECONDS = 15.0


@dataclass(frozen=True)
class Source:
    name: str
    repo: str
    lang: str
    cap: float = math.inf
    config: str | None = None
    split: str = "train"
    audio: str = "audio"


SOURCES = (
    Source("hindi_kalita", "kalita11/Hindi-TTS-corpus", "hi", 150),
    Source("hindi_rasa", "ai4bharat/Rasa", "hi", 100, config="Hindi"),
    Source("hindi_indictts", "SPRINGLab/IndicTTS-Hindi", "hi", 40),
    Source("hindi_indicvoices_r", "SPRINGLab/IndicVoices-R_Hindi", "hi", 250),
    Source("hindi_female_iisc", "somu9/iisc_mono_hindi_female", "hi", 100),
    Source("hindi_female_iitm", "somu9/iitm_mono_hindi_female", "hi", 50),
    Source("hindi_female_ivr_18_30", "SayantanJoker/IndicVoices_Hindi_audio_44100_18_30_female", "hi", 100),
    Source("hindi_female_ivr_30_45", "SayantanJoker/IndicVoices_Hindi_audio_44100_30_45_female", "hi", 100),
    Source("hindi_indicvoices", "ai4bharat/IndicVoices", "hi", config="hindi", audio="audio_filepath"),
    Source("english_indictts", "SPRINGLab/IndicTTS-English", "en", 100),
    Source("english_libritts_r_100", "parler-tts/libritts_r_filtered", "en", 100, "clean", "train.clean.100"),
    Source("english_libritts_r_360", "parler-tts/libritts_r_filtered", "en", 360, "clean", "train.clean.360"),
    Source("english_mls", "parler-tts/mls_eng", "en"),
)

CARD = """---

license: other

task_categories: [text-to-speech]

language: [hi, en]

configs:

  - config_name: default

    data_files: [{split: train, path: 'bilingual_1000h/**/*.parquet'}]

  - config_name: bilingual_1000h

    data_files: [{split: train, path: 'bilingual_1000h/**/*.parquet'}]

  - config_name: hindi_v2

    data_files: [{split: train, path: 'bilingual_1000h/hindi_*/*.parquet'}]

  - config_name: english_v2

    data_files: [{split: train, path: 'bilingual_1000h/english_*/*.parquet'}]

  - config_name: hindi_50h

    data_files: [{split: train, path: 'hindi_50h/*.parquet'}]

---



# Murli speech dataset



24 kHz mono speech and paired transcripts. The source repositories and their terms

are listed in [SOURCES.md](SOURCES.md). Each subset checkpoint records saved hours and clips.

"""


class Reject(ValueError):
    """A row failed a named quality check."""


def metadata(row, source, features):
    fields = ("text_normalized", "text_original", "normalized", "transcription", "transcript", "text")
    text = next((row[k] for k in fields if isinstance(row.get(k), str) and row[k].strip()), "")
    text = " ".join(unicodedata.normalize("NFC", text).split())
    letters = [c for c in text if c.isalpha()]
    target_script = r"[\u0900-\u097f]" if source.lang == "hi" else r"[a-zA-Z]"
    script_letters = sum(bool(re.fullmatch(target_script, c)) for c in letters)
    if len(letters) < 2 or script_letters < len(letters) / 2:
        raise Reject("text_language")
    if re.search(r"https?://|www\.|<[^>]+>|\ufffd|\[(?:noise|music|inaudible)\]", text, re.I):
        raise Reject("text_annotation")

    def label(key):
        value = row.get(key)
        if isinstance(value, int) and hasattr(features.get(key), "int2str"):
            value = features[key].int2str(value)
        return str(value).strip().lower() if value is not None else "unknown"

    speaker = row.get("speaker_id")
    gender = label("gender")
    name = source.name
    if name == "hindi_kalita" and speaker == "syspin_male_01":
        raise Reject("v1_speaker")
    if name == "hindi_indicvoices_r":
        try:
            snr = float(row.get("snr"))
        except (TypeError, ValueError):
            raise Reject("missing_snr")
        if not math.isfinite(snr) or snr < 20:
            raise Reject("low_snr")
        if row.get("cer") is not None:
            value = str(row["cer"]).strip().removeprefix("tensor(").removesuffix(")")
            try:
                cer = float(value)
            except ValueError:
                raise Reject("invalid_cer")
            if not math.isfinite(cer) or not 0 <= cer <= 0.10:
                raise Reject("transcript_cer")
    if name == "hindi_indicvoices" and label("scenario") not in {"read", "extempore"}:
        raise Reject("conversation_or_unknown")
    if name.startswith("hindi_female_"):
        gender = "female"
    prefixes = {"hindi_kalita": "kalita", "hindi_rasa": "rasa_hi", "hindi_indictts": "indictts_hi",
                "hindi_indicvoices_r": "ivr_hi", "hindi_indicvoices": "ivr_hi",
                "hindi_female_iisc": "iisc_f", "hindi_female_iitm": "iitm_f",
                "english_mls": "mls_en"}
    prefix = "libritts" if "libritts" in name else prefixes.get(name, name)
    if speaker is None and name == "hindi_indictts":
        speaker = gender
    if speaker is None and name in ("hindi_female_iisc", "hindi_female_iitm"):
        speaker = "01"
    if speaker is None and name.startswith("hindi_female_ivr_"):
        filename = str(row.get("file_name") or "").replace("\\", "/")
        prefix = "ivr_f_" + name.removeprefix("hindi_female_ivr_")
        speaker = filename.split("/")[0] if "/" in filename else None
    return text, f"{prefix}_{speaker if speaker is not None else 'unknown'}", gender


def source_mapper(name):
    src = next(s for s in SOURCES if s.name == name)

    def map_row(row):
        try:
            return metadata(row, src, {})
        except Reject:
            return None
    return map_row


map_kalita_hindi = source_mapper("hindi_kalita")
map_indictts_hindi = source_mapper("hindi_indictts")
map_indicvoices_r_hindi = source_mapper("hindi_indicvoices_r")
map_libritts_r = source_mapper("english_libritts_r_100")
map_mls_eng = source_mapper("english_mls")


def map_female_mono_hindi(prefix):
    return source_mapper({"iisc_f": "hindi_female_iisc", "iitm_f": "hindi_female_iitm"}[prefix])


def map_female_ivr_hindi(age_bucket):
    return source_mapper("hindi_female_ivr_" + age_bucket)


def trim_silence(wav: torch.Tensor, sr: int = RATE, top_db: float = 35.0, pad_ms: float = 80.0) -> torch.Tensor:
    if wav.numel() == 0:
        return wav
    mono = wav.squeeze(0) if wav.dim() > 1 else wav
    peak = torch.max(torch.abs(mono)).item()
    if peak < 1e-6:
        return mono

    frame_len = max(1, int(0.02 * sr))
    hop_len = max(1, frame_len // 2)
    if mono.numel() < frame_len:
        return mono

    frames = mono.unfold(0, frame_len, hop_len)
    rms = torch.sqrt(torch.mean(frames ** 2, dim=-1) + 1e-12)
    thresh = peak * (10.0 ** (-top_db / 20.0))
    active = torch.nonzero(rms > thresh, as_tuple=False).squeeze(-1)
    if active.numel() == 0:
        return mono.new_zeros((0,))

    pad_samples = int((pad_ms / 1000.0) * sr)
    start = max(0, int(active[0].item()) * hop_len - pad_samples)
    end = min(mono.numel(), int(active[-1].item()) * hop_len + frame_len + pad_samples)
    return mono[start:end]



def legacy_wav_hash(mono, sr):
    """Match bytes produced by the original collector when replaying unpinned legacy streams."""
    if sr != RATE:
        length = max(1, round(mono.numel() * RATE / sr))
        mono = torch.nn.functional.interpolate(mono.view(1, 1, -1), size=length, mode="linear",
                                               align_corners=False).view(-1)
    trimmed = trim_silence(mono)
    if not MIN_SECONDS * RATE <= trimmed.numel() <= MAX_SECONDS * RATE:
        return None
    peak = trimmed.abs().max().item()
    if peak < 1e-4:
        return None
    pcm = ((trimmed / peak * 0.95).numpy() * 32767.0).clip(-32768, 32767).astype(np.int16)
    buf = io.BytesIO()
    wavfile.write(buf, RATE, pcm)
    return hashlib.sha256(buf.getvalue()).digest()


def prepare_audio(field, text, check_legacy=False):
    try:
        if field.get("bytes") is not None:
            wav, sr = read_audio_bytes(field["bytes"])
        else:
            wav, sr = read_audio_file(field["path"])
    except (ValueError, OSError, RuntimeError, KeyError, TypeError, AttributeError, EOFError) as exc:
        raise Reject("decode_error") from exc
    if sr < 16000 or wav.numel() == 0 or not torch.isfinite(wav).all():
        raise Reject("invalid_or_low_rate")
    mono = wav.mean(dim=0)
    if (wav.abs() >= 0.999).float().mean().item() > 0.01:
        raise Reject("clipped")
    previous_hash = legacy_wav_hash(mono, sr) if check_legacy else None
    if sr != RATE:
        if _TA_T is not None:
            resampler = _RESAMPLERS.get(sr)
            if resampler is None:
                resampler = _TA_T.Resample(orig_freq=sr, new_freq=RATE)
                _RESAMPLERS[sr] = resampler
            mono = resampler(mono.float().unsqueeze(0)).squeeze(0)
        else:
            factor = math.gcd(sr, RATE)
            mono = torch.from_numpy(resample_poly(mono.numpy(), RATE // factor, sr // factor))
    if not torch.isfinite(mono).all():
        raise Reject("invalid_or_low_rate")
    mono = trim_silence(mono)
    seconds = mono.numel() / RATE
    if not MIN_SECONDS <= seconds <= MAX_SECONDS:
        raise Reject("duration")
    if mono.std().item() < 0.001 or mono.abs().max().item() < 0.003:
        raise Reject("near_silence")
    letters = sum(c.isalpha() for c in text)
    if not 0.35 <= letters / seconds <= 45:
        raise Reject("text_duration")
    samples = (mono / mono.abs().max() * (32767 * 0.95)).round().to(torch.int16).numpy()
    out = io.BytesIO()
    wavfile.write(out, RATE, samples)
    return out.getvalue(), seconds, previous_hash


def fingerprint_keys(wav, text, source_name, speaker):
    # Avoid repeated utterances between overlapping repackagings. Keep distinct
    # speakers reading the same prompt within a source.
    digest = hashlib.sha256(wav).digest()
    family = ""
    if "indicvoices" in source_name or "female_ivr" in source_name:
        family = "indicvoices"
    elif source_name in {"hindi_indictts", "hindi_female_iitm"} or (
            source_name == "hindi_kalita" and "indictts" in speaker.lower()):
        family = "indictts"
    norm = "".join(c for c in unicodedata.normalize("NFC", text).casefold() if c.isalnum() or unicodedata.category(c).startswith("M"))
    # Standardized PCM16 WAV, binned to 100 ms. Repeated prompts of clearly
    # different duration can represent legitimate takes by different speakers.
    duration_bin = round(len(wav) / (RATE * 2 * 0.1))
    alias = hashlib.sha256(f"{family}|{duration_bin}|{norm}".encode()).digest() if family and norm else b""
    return digest, alias


def empty_state():
    return dict(next_shard=0, rows_seen=0, curated_hours=0.0, curated_clips=0, rejected={}, exhausted=False)


class CommitFailure(RuntimeError):
    """Stop on ambiguous or conflicting writes and reload Hub state on retry."""


class StreamingBilingualCurator:
    def __init__(self, target_repo, shard_target_mb, hf_token):
        self.target_repo = target_repo
        self.shard_bytes = int(shard_target_mb * 1024 * 1024)
        self.hf_token = hf_token
        self.api = HfApi(token=hf_token)
        self.states = {}
        self.seen = set()
        self.aliases = {}
        self.has_legacy = False
        self.files = set()

    def commit(self, message, entries):
        operations = [CommitOperationAdd(path_in_repo=k, path_or_fileobj=v) for k, v in entries.items()]
        try:
            result = self.api.create_commit(repo_id=self.target_repo, repo_type="dataset",
                                            parent_commit=self.head, operations=operations,
                                            commit_message=message)
        except Exception as exc:
            raise CommitFailure(f"Failed to checkpoint {message}. Restart to reload committed state.") from exc
        self.head = result.oid
        self.files.update(entries)

    def download(self, path, local_dir=None):
        return hf_hub_download(self.target_repo, path, repo_type="dataset", revision=self.head,
                               local_dir=local_dir, token=self.hf_token)

    def initialize(self):
        self.api.create_repo(self.target_repo, repo_type="dataset", exist_ok=True)
        self.head = self.api.dataset_info(self.target_repo).sha
        self.files = set(self.api.list_repo_files(self.target_repo, repo_type="dataset", revision=self.head))
        entries = {}
        sources = "# Speech sources\n\nRecordings retain their upstream terms. See each source card for attribution and use conditions.\n\n"
        for src in SOURCES:
            sources += f"- {src.name} — https://huggingface.co/datasets/{src.repo} ({src.config or 'default'}, {src.split})\n"
        sources += "- Optional V1 baseline — https://huggingface.co/datasets/ViuAI/ViuAI_Hindi_TTS_50h\n"
        if "SOURCES.md" not in self.files:
            entries["SOURCES.md"] = sources.encode()
        if "README.md" not in self.files:
            entries["README.md"] = CARD.encode()
        else:
            card = Path(self.download("README.md")).read_text(encoding="utf-8")
            header = card.split("---", 2)[1] if card.startswith("---") and card.count("---") >= 2 else ""
            if "# Murli Unified Speech Dataset" in card and "license: apache-2.0" in header:
                entries["README.md"] = (card.replace("license: apache-2.0", "license: other", 1)
                                        + "\nSee [SOURCES.md](SOURCES.md) for upstream attribution and terms.\n").encode()
        if entries:
            self.commit("Record dataset sources and upstream terms", entries)
        self.load_inventory()

    def remember(self, keys, subset):
        for digest, alias in keys:
            self.seen.add(digest)
            if alias:
                self.aliases.setdefault(alias, subset)

    @staticmethod
    def pack_index(keys):
        return gzip.compress("".join(f"{d.hex()} {a.hex()}\n" for d, a in keys).encode())

    def load_inventory(self):
        # Old shards lack hashes and atomic checkpoints. Index them one at a
        # time, recompute physical totals, then replay the source with dedup.
        for src in SOURCES:
            prefix = f"{ROOT}/{src.name}/"
            shards = sorted(p for p in self.files if p.startswith(prefix) and p.endswith(".parquet"))
            checkpoint = prefix + "_state.json"
            state = empty_state()
            if checkpoint in self.files:
                saved = json.loads(Path(self.download(checkpoint)).read_text(encoding="utf-8"))
                if saved.get("version") == 2:
                    state = saved
            legacy = state.get("version") != 2
            indexed_rows = 0
            for shard in shards:
                index_path = shard + ".idx.gz"
                if legacy or index_path not in self.files:
                    with tempfile.TemporaryDirectory() as tmp:
                        pf = pq.ParquetFile(self.download(shard, tmp))
                        keys = []
                        try:
                            for batch in pf.iter_batches(batch_size=16, columns=["audio","text","speaker_id","duration_s"]):
                                for row in batch.to_pylist():
                                    keys.append(fingerprint_keys(row["audio"]["bytes"], row["text"], src.name, row["speaker_id"]))
                                    if legacy:
                                        state["curated_clips"] += 1
                                        state["curated_hours"] += row["duration_s"] / 3600
                        finally:
                            pf.close()
                        if index_path not in self.files:
                            self.commit(f"Index existing {shard}", {index_path: self.pack_index(keys)})
                else:
                    content = gzip.decompress(Path(self.download(index_path)).read_bytes()).decode()
                    keys = [(bytes.fromhex(d), bytes.fromhex(a)) for d, a in (line.split(" ") for line in content.splitlines())]
                self.remember(keys, src.name)
                indexed_rows += len(keys)
            next_id = max((int(Path(p).stem.split("-")[-1]) + 1 for p in shards), default=0)
            if not legacy and (state["next_shard"] != next_id or state["curated_clips"] != indexed_rows):
                raise RuntimeError(f"{src.name}: checkpoint and shards disagree. Inspect repository history.")
            state["next_shard"] = next_id
            state["version"] = 2
            if legacy and shards:
                state["has_legacy"] = True
                self.commit(f"Reconcile legacy {src.name} checkpoint", {checkpoint: json.dumps(state).encode()})
            self.has_legacy |= state.get("has_legacy", False)
            self.states[src.name] = state

    def migrate_50h_to_subfolder(self, legacy_repo: str = "ViuAI/ViuAI_Hindi_TTS_50h") -> None:
        """Copy all 22 Parquet shards from legacy 50h repo into `hindi_50h/` cleanly one file at a time."""
        existing = self.files
        revision = self.api.dataset_info(legacy_repo).sha
        src_files = sorted(
            f for f in self.api.list_repo_files(legacy_repo, repo_type="dataset", revision=revision)
            if f.endswith(".parquet")
        )
        if len({os.path.basename(path) for path in src_files}) != len(src_files):
            raise ValueError("Legacy shard names collide in the destination folder")
        print(f"Found {len(src_files)} Parquet shards in {legacy_repo}. Checking hindi_50h/...")
        with tempfile.TemporaryDirectory() as tmpdir:
            for idx, src_path in enumerate(src_files, 1):
                dst_path = f"hindi_50h/{os.path.basename(src_path)}"
                if dst_path in existing:
                    print(f"  [{idx}/{len(src_files)}] Already migrated: {dst_path}")
                    continue
                local_f = hf_hub_download(
                    repo_id=legacy_repo,
                    filename=src_path,
                    repo_type="dataset",
                    local_dir=tmpdir,
                    revision=revision,
                    token=self.hf_token,
                )
                print(f"  [{idx}/{len(src_files)}] Uploading -> {dst_path}...")
                self.commit(f"Migrate {src_path}", {dst_path: local_f})
                try:
                    os.remove(local_f)
                except OSError:
                    pass
        print("50h migration into hindi_50h/ complete!")


    def flush(self, src, state, rows, keys):
        prefix = f"{ROOT}/{src.name}/"
        entries = {}
        upload_bytes = 0
        shard_name = None
        t_up = time.perf_counter()
        with tempfile.TemporaryDirectory() as tmp:
            if rows:
                shard_name = f"shard-{state['next_shard']:05d}.parquet"
                local = str(Path(tmp) / shard_name)
                ds = Dataset.from_list(rows).cast_column("audio", Audio(sampling_rate=RATE, decode=False))
                ds.to_parquet(local, batch_size=16)
                if prefix + shard_name in self.files:
                    raise CommitFailure(f"Shard already exists: {shard_name}. Reload repository state.")
                upload_bytes = os.path.getsize(local)
                entries[prefix + shard_name] = local
                entries[prefix + shard_name + ".idx.gz"] = self.pack_index(keys)
                state["next_shard"] += 1
            entries[prefix + "_state.json"] = json.dumps(state, indent=2, allow_nan=False).encode()
            self.commit(f"Checkpoint {src.name} at row {state['rows_seen']}", entries)
        if shard_name is not None and upload_bytes > 0:
            up_s = max(time.perf_counter() - t_up, 1e-3)
            mb = upload_bytes / (1024 * 1024)
            print(
                f"[Upload OK] {src.name}/{shard_name} | {mb:.1f} MB in {up_s:.1f}s ({mb / up_s:.1f} MB/s) | "
                f"total={state['curated_hours']:.2f}h ({state['curated_clips']:,} clips)",
                flush=True,
            )
        self.states[src.name] = dict(state, rejected=dict(state["rejected"]))
        self.remember(keys, src.name)
        rows.clear()
        keys.clear()

    def source_stream(self, src, state):
        if "repo" in state and (state["repo"], state["config"], state["split"]) != (src.repo, src.config, src.split):
            raise ValueError(f"{src.name}: source changed since its last checkpoint")
        revision = state.get("revision") or self.api.dataset_info(src.repo).sha
        ds = load_dataset(src.repo, src.config, split=src.split, revision=revision,
                          streaming=True, token=self.hf_token)
        features = ds.features or {}
        if src.audio not in features or not set(features).intersection(
                ("text", "normalized", "transcript", "text_normalized", "text_original", "transcription")):
            raise ValueError(f"Unexpected columns for {src.repo}: {list(features)}")
        state.update(repo=src.repo, config=src.config, split=src.split, revision=revision)
        return ds.cast_column(src.audio, Audio(decode=False)), features

    def collect(self, src, target):
        old = self.states[src.name]
        state = dict(old, rejected=Counter(old["rejected"]))
        if state["exhausted"] or state["curated_hours"] >= target:
            return
        ds, features = self.source_stream(src, state)
        rows, keys, pending = [], [], set()
        size = 0
        last_saved = state["rows_seen"]
        start_rows = last_saved
        start_hrs = state["curated_hours"]
        t_start = time.perf_counter()
        stream = iter(ds.skip(last_saved) if last_saved else ds)
        print(f"\n>>> [{src.name}] Resuming at row {last_saved:,} ({start_hrs:.2f}h / {target:.1f}h target) <<<", flush=True)
        while state["curated_hours"] < target:
            try:
                row = next(stream)
            except StopIteration:
                state["exhausted"] = True
                break
            state["rows_seen"] += 1
            try:
                text, speaker, gender = metadata(row, src, features)
                wav, seconds, previous_hash = prepare_audio(row[src.audio], text, self.has_legacy)
                digest, alias = fingerprint_keys(wav, text, src.name, speaker)
                if digest in self.seen or digest in pending or previous_hash in self.seen:
                    raise Reject("duplicate_audio")
                if alias and self.aliases.get(alias, src.name) != src.name:
                    raise Reject("overlapping_source_text")
            except Reject as exc:
                state["rejected"][str(exc)] += 1
            else:
                rows.append(dict(audio={"bytes": wav, "path": digest.hex() + ".wav"}, text=text,
                                 speaker_id=speaker, lang=src.lang, source=src.name,
                                 duration_s=seconds, gender=gender))
                pending.add(digest)
                keys.append((digest, alias))
                size += len(wav)
                state["curated_hours"] += seconds / 3600
                state["curated_clips"] += 1

            seen_now = state["rows_seen"] - start_rows
            if seen_now % 250 == 0:
                dt = max(time.perf_counter() - t_start, 1e-3)
                rate = seen_now / dt
                buf_mb = size / (1024 * 1024)
                hrs_per_min = (state["curated_hours"] - start_hrs) / (dt / 60.0)
                print(
                    f"  [{src.name}] rows={state['rows_seen']:,} | {state['curated_hours']:.2f}/{target:.1f}h "
                    f"({state['curated_clips']:,} clips) | {rate:.1f} rows/s | +{hrs_per_min:.2f}h/min | "
                    f"buf={buf_mb:.0f}/{self.shard_bytes/(1024*1024):.0f} MB",
                    flush=True,
                )

            if size >= self.shard_bytes or (not rows and state["rows_seen"] - last_saved >= 2000):
                self.flush(src, state, rows, keys)
                last_saved = state["rows_seen"]
                pending.clear()
                size = 0
        if rows or state["exhausted"] or last_saved != state["rows_seen"]:
            self.flush(src, state, rows, keys)


def load_hf_token(cli_token: str | None = None) -> str | None:
    token = cli_token or os.environ.get("HF_TOKEN")
    if token:
        return token
    try:
        from dotenv import load_dotenv
        load_dotenv()
        token = os.environ.get("HF_TOKEN")
        if token:
            return token
    except Exception:
        pass
    try:
        from kaggle_secrets import UserSecretsClient
        token = UserSecretsClient().get_secret("HF_TOKEN")
        print("[+] Loaded HF_TOKEN from Kaggle Secrets.")
        return token
    except Exception:
        return None



def run(curator, goals, only, cap_overrides=None):
    failed = []
    cap_overrides = cap_overrides or {}
    for src in SOURCES:
        if only and src.name != only:
            continue
        committed = sum(curator.states[s.name]["curated_hours"] for s in SOURCES if s.lang == src.lang)
        state = curator.states[src.name]
        eff_cap = cap_overrides.get(src.name, src.cap)
        target = min(eff_cap, state["curated_hours"] + max(0, goals[src.lang] - committed))
        if state["curated_hours"] >= target:
            continue
        try:
            curator.collect(src, target)
        except CommitFailure:
            raise
        except Exception as exc:
            failed.append(src.name)
            print(f"{src.name}: source interrupted: {type(exc).__name__}: {exc}", flush=True)
        state = curator.states[src.name]
        print(f"{src.name}: {state['curated_hours']:.3f}/{target:.3f} h, "
              f"{state['curated_clips']} clips, rejected={state['rejected']}, exhausted={state['exhausted']}")
    short = False
    for lang, goal in goals.items():
        states = [curator.states[s.name] for s in SOURCES if s.lang == lang]
        hours = sum(s["curated_hours"] for s in states)
        clips = sum(s["curated_clips"] for s in states)
        print(f"{lang}: {hours:.4f}/{goal:g} h saved, {clips} clips, {max(0, goal-hours):.4f} h short")
        if only is None and hours < goal:
            short = True
    if only:
        src = next(s for s in SOURCES if s.name == only)
        other = sum(curator.states[s.name]["curated_hours"] for s in SOURCES if s.lang == src.lang and s != src)
        short = curator.states[only]["curated_hours"] < min(src.cap, goals[src.lang] - other)
    return 1 if failed or short else 0


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--target_repo", default="ViuAI/Murli_TTS_Dataset")
    parser.add_argument("--migrate_50h", action="store_true", help="Copy the separate V1 baseline")
    parser.add_argument("--hindi_hours", type=float, default=400)
    parser.add_argument("--english_hours", type=float, default=650)
    parser.add_argument("--indictts_en_hours", type=float, default=100.0, help="Target hours for SPRINGLab/IndicTTS-English (e.g., 20 for smoke test)")
    parser.add_argument("--shard_mb", type=float, default=350, help="Buffered WAV payload per shard in MiB")
    parser.add_argument("--only", choices=[s.name for s in SOURCES])
    parser.add_argument("--token")
    args = parser.parse_args()
    if any(not math.isfinite(x) or x < 0 for x in (args.hindi_hours, args.english_hours, args.indictts_en_hours)):
        parser.error("Hour targets must be finite and nonnegative")
    if not math.isfinite(args.shard_mb) or args.shard_mb <= 0:
        parser.error("Shard size must be finite and positive")
    curator = StreamingBilingualCurator(args.target_repo, args.shard_mb, load_hf_token(args.token))
    curator.initialize()
    if args.migrate_50h:
        curator.migrate_50h_to_subfolder()
    return run(
        curator,
        {"hi": args.hindi_hours, "en": args.english_hours},
        args.only,
        cap_overrides={"english_indictts": args.indictts_en_hours},
    )


if __name__ == "__main__":
    raise SystemExit(main())