Datasets:
Download kaggle_data_collector.py from ViuAI/ViuAI_TTS_Dataset: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/datasets/ViuAI/ViuAI_TTS_Dataset/resolve/main/kaggle_data_collector.py
- Command line
-
hf download hf://datasets/ViuAI/ViuAI_TTS_Dataset/kaggle_data_collector.py
-
curl -L -o kaggle_data_collector.py https://huggingface.co/datasets/ViuAI/ViuAI_TTS_Dataset/resolve/main/kaggle_data_collector.py
11.4 kB
| """ | |
| Kaggle 50h+ Hindi Speech Dataset Curator for ViuAI. | |
| Collects, resamples (24kHz), trims, normalizes, and filters 50+ hours of 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 csv | |
| import glob | |
| import time | |
| import shutil | |
| import argparse | |
| import numpy as np | |
| import pandas as pd | |
| from typing import Optional, List, Dict | |
| import torch | |
| import torchaudio | |
| import torchaudio.transforms as T | |
| from datasets import load_dataset, Dataset, Audio | |
| from huggingface_hub import HfApi, 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 "" | |
| # Remove URL or HTML tags | |
| text = re.sub(r"http\S+|www\S+|<.*?>", "", text) | |
| # Remove weird symbols, keep Devanagari, basic punctuation, and numbers | |
| text = re.sub(r"[^\u0900-\u097F\s\.,!\?।0-9a-zA-Z]", "", text) | |
| # Collapse spaces | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text | |
| class HindiAudioCurator: | |
| def __init__( | |
| self, | |
| target_sr: int = 24000, | |
| min_sec: float = 1.5, | |
| max_sec: float = 12.0, | |
| 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.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) -> bool: | |
| """Resamples, trims silence, peak-normalizes, and checks duration.""" | |
| # Mono | |
| if wav.dim() == 1: | |
| wav = wav.unsqueeze(0) | |
| elif wav.shape[0] > 1: | |
| wav = torch.mean(wav, dim=0, keepdim=True) | |
| # Resample | |
| if orig_sr != self.target_sr: | |
| resampler = self.get_resampler(orig_sr) | |
| wav = resampler(wav) | |
| # Duration check | |
| num_samples = wav.shape[-1] | |
| duration = num_samples / self.target_sr | |
| if duration < self.min_sec or duration > self.max_sec: | |
| return False | |
| # Clean text check | |
| cleaned_text = clean_hindi_text(text) | |
| if len(cleaned_text) < 5 or not re.search(r"[\u0900-\u097F]", cleaned_text): | |
| return False # Must contain meaningful Hindi characters | |
| # Peak normalization with headroom | |
| max_val = torch.max(torch.abs(wav)) | |
| if max_val < 1e-4: | |
| return False | |
| wav = (wav / max_val) * 0.95 | |
| # Save WAV file | |
| 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) | |
| # Save via scipy int16 (100% reliable) | |
| int16_pcm = (wav.squeeze(0).numpy() * 32767.0).astype(np.int16) | |
| from scipy.io import wavfile | |
| 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 True | |
| def collect_from_indic_tts(self, max_hours_per_speaker: float = 12.0): | |
| """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"), | |
| ] | |
| for repo, spk in sources: | |
| print(f"\n[+] Collecting from {repo} (Speaker: {spk})...") | |
| try: | |
| ds = load_dataset(repo, split="train", streaming=True) | |
| total_sec = 0 | |
| max_sec = max_hours_per_speaker * 3600 | |
| 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 = torch.tensor(audio_info["array"], dtype=torch.float32) | |
| sr = audio_info["sampling_rate"] | |
| sample_id = f"{spk}_{count:06d}" | |
| if self.process_and_save_audio(wav, sr, text, spk, sample_id): | |
| count += 1 | |
| total_sec += (wav.shape[-1] / sr) | |
| 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 = 20.0): | |
| """Streams AI4Bharat IndicVoices Hindi subset.""" | |
| print("\n[+] Collecting from ai4bharat/indicvoices (Hindi)...") | |
| try: | |
| ds = load_dataset("ai4bharat/indicvoices", "hi", split="train", streaming=True) | |
| total_sec = 0 | |
| max_sec = max_hours * 3600 | |
| 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 = torch.tensor(audio_info["array"], dtype=torch.float32) | |
| sr = audio_info["sampling_rate"] | |
| sample_id = f"iv_{count:06d}" | |
| if self.process_and_save_audio(wav, sr, text, f"iv_{spk}", sample_id): | |
| count += 1 | |
| total_sec += (wav.shape[-1] / sr) | |
| 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 = 10.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) | |
| total_sec = 0 | |
| max_sec = max_hours * 3600 | |
| 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 = torch.tensor(audio_info["array"], dtype=torch.float32) | |
| sr = audio_info["sampling_rate"] | |
| sample_id = f"fleurs_hi_{count:06d}" | |
| if self.process_and_save_audio(wav, sr, text, "fleurs_hi", sample_id): | |
| count += 1 | |
| total_sec += (wav.shape[-1] / sr) | |
| 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): | |
| """Saves metadata.csv and pushes entire 50h+ dataset to Hugging Face Hub.""" | |
| 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 if "duration" in df.columns else 0.0 | |
| print("\n" + "="*50) | |
| print(" 50H+ 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") | |
| # Push to Hugging Face | |
| print(f"Pushing curated 50h+ dataset to Hugging Face: {hf_repo_id}...") | |
| api = HfApi() | |
| api.create_repo(repo_id=hf_repo_id, repo_type="dataset", private=private, exist_ok=True) | |
| api.upload_folder( | |
| folder_path=self.output_dir, | |
| repo_id=hf_repo_id, | |
| repo_type="dataset", | |
| commit_message=f"Upload {total_hours:.1f}h curated 24kHz Hindi TTS 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=50.0, help="Target total hours") | |
| args = parser.parse_args() | |
| token = args.token or os.environ.get("HF_TOKEN") | |
| curator = HindiAudioCurator(output_dir=args.output_dir, hf_token=token) | |
| # 1. Collect IndicTTS studio voices (~35-40 hours total across 4 speakers) | |
| curator.collect_from_indic_tts(max_hours_per_speaker=10.0) | |
| # 2. Collect FLEURS & IndicVoices to comfortably exceed 50+ hours | |
| curator.collect_from_fleurs(max_hours=8.0) | |
| curator.collect_from_indicvoices(max_hours=15.0) | |
| # 3. Save & Push to HF Hub | |
| curator.save_and_push(hf_repo_id=args.repo_id) | |