Download kaggle_data_collector.py from ViuAI/TTS_10M: direct link, hf CLI and curl.
- Browser
- Download file 18.8 kB
-
https://huggingface.co/ViuAI/TTS_10M/resolve/main/kaggle_data_collector.py
- Command line
-
hf download hf://ViuAI/TTS_10M/kaggle_data_collector.py
-
curl -L -o kaggle_data_collector.py https://huggingface.co/ViuAI/TTS_10M/resolve/main/kaggle_data_collector.py
18.8 kB
| """ | |
| Kaggle 50h+ Hindi Speech Dataset Curator for ViuAI. | |
| Collects, resamples (24kHz), trims silence, normalizes, and filters high-quality | |
| Hindi speech data from top open datasets (IndicTTS, IndicVoices, FLEURS), | |
| and pushes the unified dataset to Hugging Face Hub. | |
| """ | |
| import os | |
| import sys | |
| import gc | |
| import re | |
| import argparse | |
| import numpy as np | |
| import pandas as pd | |
| from typing import Optional | |
| import torch | |
| import torchaudio.transforms as T | |
| from scipy.io import wavfile | |
| from datasets import Audio, load_dataset | |
| try: | |
| from data.audio_processor import read_audio | |
| except ModuleNotFoundError as exc: | |
| if exc.name != "data": | |
| raise | |
| # The curator is also distributed as a standalone Kaggle script. | |
| def read_audio(source): | |
| import io | |
| import soundfile as sf | |
| if isinstance(source, bytes): | |
| source = io.BytesIO(source) | |
| data, rate = sf.read(source, dtype="float32", always_2d=True) | |
| return torch.from_numpy(data.T.copy()), rate | |
| from huggingface_hub import HfApi, hf_hub_download, login | |
| # Ensure UTF-8 printing | |
| if hasattr(sys.stdout, "reconfigure"): | |
| try: | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| except Exception: | |
| pass | |
| def clean_hindi_text(text: str) -> str: | |
| """Removes junk characters, normalizes Devanagari Unicode, collapses whitespace.""" | |
| if not isinstance(text, str): | |
| return "" | |
| text = re.sub(r"http\S+|www\S+|<.*?>", "", text) | |
| text = re.sub(r"[^\u0900-\u097F\s\.,!\?।0-9a-zA-Z]", "", text) | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text | |
| def trim_silence(wav: torch.Tensor, sr: int = 24000, top_db: float = 35.0, pad_ms: float = 80.0) -> torch.Tensor: | |
| """ | |
| Trims leading and trailing silence using frame-wise RMS energy relative to peak. | |
| Keeps `pad_ms` of natural breath/silence padding at edges. | |
| """ | |
| 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)) # 20ms window | |
| 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_sample = max(0, int(active[0].item()) * hop_len - pad_samples) | |
| end_sample = min(mono.numel(), int(active[-1].item()) * hop_len + frame_len + pad_samples) | |
| return mono[start_sample:end_sample] | |
| class HindiAudioCurator: | |
| def __init__( | |
| self, | |
| target_sr: int = 24000, | |
| min_sec: float = 1.5, | |
| max_sec: float = 12.0, | |
| allow_english: bool = False, | |
| output_dir: str = "/kaggle/working/hindi_50h_dataset", | |
| hf_token: Optional[str] = None, | |
| ): | |
| self.target_sr = target_sr | |
| self.min_sec = min_sec | |
| self.max_sec = max_sec | |
| self.allow_english = allow_english | |
| self.output_dir = output_dir | |
| self.audio_dir = os.path.join(output_dir, "audio") | |
| os.makedirs(self.audio_dir, exist_ok=True) | |
| self.hf_token = hf_token | |
| if hf_token: | |
| login(token=hf_token) | |
| self.resamplers = {} | |
| self.metadata = [] | |
| def get_resampler(self, orig_sr: int): | |
| if orig_sr not in self.resamplers: | |
| self.resamplers[orig_sr] = T.Resample(orig_freq=orig_sr, new_freq=self.target_sr) | |
| return self.resamplers[orig_sr] | |
| def process_and_save_audio(self, wav: torch.Tensor, orig_sr: int, text: str, speaker_id: str, sample_id: str) -> float: | |
| """Resamples, trims silence, peak-normalizes, and checks duration. Returns saved duration (0.0 if skipped).""" | |
| if wav.numel() == 0 or not torch.isfinite(wav).all(): | |
| return 0.0 | |
| if wav.dim() == 1: | |
| wav = wav.unsqueeze(0) | |
| elif wav.shape[0] > 1: | |
| wav = torch.mean(wav, dim=0, keepdim=True) | |
| if orig_sr != self.target_sr: | |
| wav = self.get_resampler(orig_sr)(wav) | |
| # Trim leading/trailing silence | |
| trimmed = trim_silence(wav.squeeze(0), sr=self.target_sr) | |
| if trimmed.numel() == 0: | |
| return 0.0 | |
| num_samples = trimmed.shape[-1] | |
| duration = num_samples / float(self.target_sr) | |
| if duration < self.min_sec or duration > self.max_sec: | |
| return 0.0 | |
| cleaned_text = clean_hindi_text(text) | |
| if len(cleaned_text) < 5: | |
| return 0.0 | |
| if not self.allow_english and not re.search(r"[\u0900-\u097F]", cleaned_text): | |
| return 0.0 | |
| max_val = torch.max(torch.abs(trimmed)) | |
| if max_val < 1e-4: | |
| return 0.0 | |
| trimmed = (trimmed / max_val) * 0.95 | |
| for component in (speaker_id, sample_id): | |
| if component in ("", ".", "..") or any(char in component for char in ("/", chr(92), ":")): | |
| raise ValueError(f"Invalid audio path component: {component!r}") | |
| spk_dir = os.path.join(self.audio_dir, speaker_id) | |
| os.makedirs(spk_dir, exist_ok=True) | |
| rel_wav_path = f"audio/{speaker_id}/{sample_id}.wav" | |
| full_wav_path = os.path.join(self.output_dir, rel_wav_path) | |
| int16_pcm = (trimmed.numpy() * 32767.0).astype(np.int16) | |
| wavfile.write(full_wav_path, self.target_sr, int16_pcm) | |
| self.metadata.append({ | |
| "audio_file": rel_wav_path, | |
| "transcript": cleaned_text, | |
| "speaker": speaker_id, | |
| "duration": round(duration, 2), | |
| "language": "hi", | |
| }) | |
| return duration | |
| def collect_from_hindi_tts_corpus(self, speaker_ids=None, speaker_id: str = "syspin_male_01", max_hours: float = 55.0): | |
| """ | |
| Downloads parquet shards directly from kalita11/Hindi-TTS-corpus and filters | |
| speaker_id(s) BEFORE audio decoding (avoids datasets streaming hangs & torchcodec crashes). | |
| Default 'syspin_male_01' provides ~49-54.5 hours of Tier-1 studio male voice. | |
| """ | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| import pyarrow.compute as pc | |
| target_speakers = list(speaker_ids) if speaker_ids else [speaker_id] | |
| repo_id = "kalita11/Hindi-TTS-corpus" | |
| print(f"\n[+] Collecting speakers {target_speakers} from {repo_id} (Direct Parquet Mode)...", flush=True) | |
| try: | |
| api = HfApi() | |
| all_files = api.list_repo_files(repo_id=repo_id, repo_type="dataset") | |
| parquet_files = sorted([f for f in all_files if f.endswith(".parquet")]) | |
| print(f" Found {len(parquet_files)} parquet shards.", flush=True) | |
| total_sec = 0.0 | |
| max_sec = max_hours * 3600.0 | |
| counts = {s: 0 for s in target_speakers} | |
| for idx, pq_file in enumerate(parquet_files, 1): | |
| if total_sec >= max_sec: | |
| break | |
| print(f" [{idx}/{len(parquet_files)}] Downloading {pq_file}...", flush=True) | |
| local_pq = hf_hub_download(repo_id=repo_id, filename=pq_file, repo_type="dataset") | |
| shard = pq.ParquetFile(local_pq) | |
| for batch in shard.iter_batches(batch_size=64, columns=["audio", "text", "speaker_id"]): | |
| mask = pc.is_in(batch.column("speaker_id"), value_set=pa.array(target_speakers)) | |
| for item in batch.filter(mask).to_pylist(): | |
| audio_info = item.get("audio") or {} | |
| if not audio_info.get("bytes"): | |
| continue | |
| spk = item["speaker_id"] | |
| wav, sr = read_audio(audio_info["bytes"]) | |
| sample_id = f"{spk}_{counts[spk]:06d}" | |
| saved = self.process_and_save_audio(wav, sr, item.get("text") or "", spk, sample_id) | |
| if saved: | |
| counts[spk] += 1 | |
| total_sec += saved | |
| if total_sec >= max_sec: | |
| break | |
| if total_sec >= max_sec: | |
| break | |
| shard.close() | |
| gc.collect() | |
| print(f" Completed {counts}: {sum(counts.values())} clips ({total_sec/3600:.2f} hours).", flush=True) | |
| except Exception as e: | |
| print(f" Warning: Could not process {repo_id} ({e}).", flush=True) | |
| gc.collect() | |
| def collect_from_indic_tts(self, max_hours_per_speaker: float = 10.0, single_speaker_only: bool = False): | |
| """Streams IIT Madras IndicTTS Hindi voices.""" | |
| sources = [ | |
| ("MatrixSpeechAI/Indic_TTS_HI_Male_Speaker_1", "indic_hi_male_1"), | |
| ("MatrixSpeechAI/Indic_TTS_HI_Male_Speaker_2", "indic_hi_male_2"), | |
| ("MatrixSpeechAI/Indic_TTS_HI_Female_Speaker_1", "indic_hi_female_1"), | |
| ("MatrixSpeechAI/Indic_TTS_HI_Female_Speaker_2", "indic_hi_female_2"), | |
| ] | |
| if single_speaker_only: | |
| sources = [sources[0]] | |
| for repo, spk in sources: | |
| print(f"\n[+] Collecting from {repo} (Speaker: {spk})...") | |
| try: | |
| ds = load_dataset(repo, split="train", streaming=True).cast_column("audio", Audio(decode=False)) | |
| total_sec = 0.0 | |
| max_sec = max_hours_per_speaker * 3600.0 | |
| count = 0 | |
| for item in ds: | |
| audio_info = item.get("audio") | |
| text = item.get("transcription") or item.get("text") or "" | |
| if not audio_info: | |
| continue | |
| wav, sr = read_audio(audio_info.get("bytes") or audio_info["path"]) | |
| sample_id = f"{spk}_{count:06d}" | |
| saved_dur = self.process_and_save_audio(wav, sr, text, spk, sample_id) | |
| if saved_dur > 0: | |
| count += 1 | |
| total_sec += saved_dur | |
| if count % 250 == 0 and count > 0: | |
| print(f" -> Processed {count} clips ({total_sec/3600:.2f} hours)") | |
| if total_sec >= max_sec: | |
| print(f" Target reached for {spk}: {total_sec/3600:.2f} hours.") | |
| break | |
| except Exception as e: | |
| print(f" Warning: Could not process {repo} ({e}). Skipping.") | |
| gc.collect() | |
| def collect_from_indicvoices(self, max_hours: float = 15.0): | |
| """Streams AI4Bharat IndicVoices Hindi subset.""" | |
| print("\n[+] Collecting from ai4bharat/indicvoices (Hindi)...") | |
| try: | |
| ds = load_dataset("ai4bharat/indicvoices", "hi", split="train", streaming=True).cast_column("audio", Audio(decode=False)) | |
| total_sec = 0.0 | |
| max_sec = max_hours * 3600.0 | |
| count = 0 | |
| for item in ds: | |
| audio_info = item.get("audio") | |
| text = item.get("text") or item.get("normalized_text") or "" | |
| spk = item.get("speaker_id") or "indicvoices_hi" | |
| if not audio_info: | |
| continue | |
| wav, sr = read_audio(audio_info.get("bytes") or audio_info["path"]) | |
| sample_id = f"iv_{count:06d}" | |
| saved_dur = self.process_and_save_audio(wav, sr, text, f"iv_{spk}", sample_id) | |
| if saved_dur > 0: | |
| count += 1 | |
| total_sec += saved_dur | |
| if count % 500 == 0 and count > 0: | |
| print(f" -> IndicVoices: {count} clips ({total_sec/3600:.2f} hours)") | |
| if total_sec >= max_sec: | |
| print(f" Target reached for IndicVoices: {total_sec/3600:.2f} hours.") | |
| break | |
| except Exception as e: | |
| print(f" Notice: IndicVoices ({e}).") | |
| gc.collect() | |
| def collect_from_fleurs(self, max_hours: float = 8.0): | |
| """Streams Google FLEURS Hindi.""" | |
| print("\n[+] Collecting from google/fleurs (Hindi hi_in)...") | |
| try: | |
| ds = load_dataset("google/fleurs", "hi_in", split="train", streaming=True).cast_column("audio", Audio(decode=False)) | |
| total_sec = 0.0 | |
| max_sec = max_hours * 3600.0 | |
| count = 0 | |
| for item in ds: | |
| audio_info = item.get("audio") | |
| text = item.get("transcription") or item.get("raw_transcription") or "" | |
| if not audio_info: | |
| continue | |
| wav, sr = read_audio(audio_info.get("bytes") or audio_info["path"]) | |
| sample_id = f"fleurs_hi_{count:06d}" | |
| saved_dur = self.process_and_save_audio(wav, sr, text, "fleurs_hi", sample_id) | |
| if saved_dur > 0: | |
| count += 1 | |
| total_sec += saved_dur | |
| if total_sec >= max_sec: | |
| break | |
| print(f" FLEURS processed: {count} clips ({total_sec/3600:.2f} hours).") | |
| except Exception as e: | |
| print(f" Notice: FLEURS ({e}).") | |
| gc.collect() | |
| def save_and_push(self, hf_repo_id: str, private: bool = False, use_parquet: bool = False): | |
| """Saves metadata.csv (or Parquet shards) and pushes dataset to Hugging Face Hub.""" | |
| if len(self.metadata) == 0: | |
| print("Warning: 0 samples collected. Skipping metadata save and Hugging Face upload.") | |
| return | |
| meta_csv = os.path.join(self.output_dir, "metadata.csv") | |
| df = pd.DataFrame(self.metadata) | |
| df.to_csv(meta_csv, sep="|", index=False, encoding="utf-8") | |
| total_hours = df["duration"].sum() / 3600.0 | |
| print("\n" + "=" * 50) | |
| print(" HINDI DATASET CURATION SUMMARY ") | |
| print("=" * 50) | |
| print(f" Total Samples Collected: {len(df):,}") | |
| print(f" Total Audio Duration: {total_hours:.2f} Hours") | |
| print(f" Speakers Breakdown:\n{df['speaker'].value_counts()}") | |
| print("=" * 50 + "\n") | |
| api = HfApi() | |
| api.create_repo(repo_id=hf_repo_id, repo_type="dataset", private=private, exist_ok=True) | |
| if use_parquet: | |
| from datasets import Dataset | |
| print(f"Packing {len(df):,} clips into Hugging Face Parquet shards (avoids 10k-file limit)...", flush=True) | |
| audio_paths = [os.path.join(self.output_dir, p) for p in df["audio_file"].tolist()] | |
| ds = Dataset.from_dict({ | |
| "audio": audio_paths, | |
| "text": df["transcript"].tolist(), | |
| "speaker": df["speaker"].tolist(), | |
| "duration": df["duration"].tolist(), | |
| "language": df["language"].tolist(), | |
| }).cast_column("audio", Audio(sampling_rate=self.target_sr)) | |
| # Remove stale loose-file metadata.csv if present so dataset.py loads Parquet directly | |
| try: | |
| api.delete_file("metadata.csv", repo_id=hf_repo_id, repo_type="dataset", | |
| commit_message="Switch to full Parquet dataset shards") | |
| except Exception: | |
| pass | |
| ds.push_to_hub(hf_repo_id, private=private, max_shard_size="400MB") | |
| else: | |
| print(f"Pushing curated dataset to Hugging Face using upload_large_folder: {hf_repo_id}...") | |
| api.upload_large_folder( | |
| folder_path=self.output_dir, | |
| allow_patterns=["audio/**/*.wav", "metadata.csv"], | |
| repo_id=hf_repo_id, | |
| repo_type="dataset", | |
| ) | |
| print(f"\n🎉 Dataset successfully published to: https://huggingface.co/datasets/{hf_repo_id}\n") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Kaggle 50h+ Hindi Dataset Curator") | |
| parser.add_argument("--repo_id", type=str, default="ViuAI/ViuAI_Hindi_TTS_50h", help="Target Hugging Face Dataset repo") | |
| parser.add_argument("--output_dir", type=str, default="/kaggle/working/hindi_50h_dataset", help="Output directory") | |
| parser.add_argument("--token", type=str, default=None, help="Hugging Face write token") | |
| parser.add_argument("--target_hours", type=float, default=70.0, help="Target total hours") | |
| parser.add_argument("--single_speaker", action="store_true", help="Collect clean Tier-1 studio Hindi speaker(s) from kalita11/Hindi-TTS-corpus") | |
| parser.add_argument("--speaker_id", type=str, default="syspin_male_01", help="Primary speaker ID") | |
| parser.add_argument("--speaker_ids", nargs="+", default=None, help="Multiple speaker IDs (e.g. syspin_male_01 rasa_male_01)") | |
| parser.add_argument("--parquet", action="store_true", help="Push as Parquet shards (recommended: avoids HF 10k-file folder cap)") | |
| parser.add_argument("--allow_english", action="store_true", help="Allow English/Hinglish transcripts without Devanagari") | |
| args = parser.parse_args() | |
| if not np.isfinite(args.target_hours) or args.target_hours <= 0: | |
| parser.error("--target_hours must be a finite positive value") | |
| token = args.token or os.environ.get("HF_TOKEN") | |
| if not token: | |
| try: | |
| from kaggle_secrets import UserSecretsClient | |
| token = UserSecretsClient().get_secret("HF_TOKEN") | |
| print("[+] Loaded HF_TOKEN from Kaggle Secrets.") | |
| except Exception: | |
| pass | |
| curator = HindiAudioCurator( | |
| output_dir=args.output_dir, | |
| hf_token=token, | |
| allow_english=args.allow_english, | |
| ) | |
| if args.single_speaker or args.speaker_ids: | |
| curator.collect_from_hindi_tts_corpus( | |
| speaker_ids=args.speaker_ids, | |
| speaker_id=args.speaker_id, | |
| max_hours=args.target_hours, | |
| ) | |
| else: | |
| # Scale source allocations proportionally to args.target_hours (default 50h -> ~32h IndicTTS, ~6h FLEURS, ~12h IndicVoices) | |
| scale = args.target_hours / 50.0 | |
| curator.collect_from_indic_tts(max_hours_per_speaker=8.0 * scale) | |
| curator.collect_from_fleurs(max_hours=6.0 * scale) | |
| curator.collect_from_indicvoices(max_hours=12.0 * scale) | |
| curator.save_and_push(hf_repo_id=args.repo_id, use_parquet=args.parquet) | |