Download tests/test_v2.py from ViuAI/Murli-V2-Code: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/ViuAI/Murli-V2-Code/resolve/main/tests/test_v2.py
- Command line
-
hf download hf://ViuAI/Murli-V2-Code/tests/test_v2.py
-
curl -L -o test_v2.py https://huggingface.co/ViuAI/Murli-V2-Code/resolve/main/tests/test_v2.py
14.8 kB
| """Offline verification tests for Murli V2.0 (50M+ Bilingual Hindi+English DiT TTS).""" | |
| import math | |
| import sys | |
| import unittest | |
| from pathlib import Path | |
| import torch | |
| ROOT = Path(__file__).resolve().parents[1] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from config import MurliV2Config | |
| from data.audio_processor import AudioProcessor | |
| from data.text_cleaner import BilingualTextTokenizer, hindi_word_to_ipa | |
| from models.tts_engine import MurliV2Engine | |
| class MurliV2Tests(unittest.TestCase): | |
| def test_parameter_count_above_50m(self): | |
| cfg = MurliV2Config() | |
| engine = MurliV2Engine(cfg.model, cfg.training) | |
| stats = engine.parameter_breakdown() | |
| print("\n[Murli V2 Parameter Breakdown]", {k: f"{v / 1e6:.2f}M" for k, v in stats.items()}) | |
| self.assertGreater(stats["total_trainable_acoustic"], 50_000_000) | |
| def test_bilingual_hindi_english_g2p(self): | |
| tok = BilingualTextTokenizer(use_g2p_en=False) | |
| # Contextual anusvara & retroflex / aspirated flaps | |
| self.assertIn("n̪", hindi_word_to_ipa("ईंधन")) | |
| self.assertIn("ɽʰ", hindi_word_to_ipa("बढ़ई")) | |
| self.assertIn("ɽ", hindi_word_to_ipa("लकड़ी")) | |
| # Contractions preserved & mixed Hindi + English sentence | |
| self.assertEqual(tok.english_word_to_ipa("don't"), ["d", "oʊ", "n", "t"]) | |
| tokens = tok.text_to_phonemes("नमस्ते friend, आज don't stop AI launch!") | |
| self.assertIn("<hi>", tokens) | |
| self.assertIn("<en>", tokens) | |
| ids = tok.text_to_ids("Hello world! आज हम 2026 TTS बना रहे हैं।") | |
| self.assertGreater(ids.numel(), 10) | |
| self.assertLess(int(ids.max().item()), tok.vocab_size) | |
| def test_audio_f0_and_energy_extraction(self): | |
| proc = AudioProcessor() | |
| t = torch.linspace(0.0, 1.0, 24000) | |
| wav = 0.5 * torch.sin(2.0 * math.pi * 180.0 * t) | |
| mel, log_f0, energy = proc.extract_features(wav) | |
| self.assertEqual(mel.shape[0], 100) | |
| self.assertEqual(log_f0.shape[0], mel.shape[1]) | |
| self.assertEqual(energy.shape[0], mel.shape[1]) | |
| self.assertTrue(torch.isfinite(mel).all()) | |
| self.assertTrue((log_f0 != 0).any()) | |
| def test_train_forward_backward_and_zeroshot_infer(self): | |
| cfg = MurliV2Config() | |
| # Use smaller layer count for rapid CPU backward check while keeping all paths active | |
| cfg.model.dit_layers = 2 | |
| cfg.model.text_layers = 2 | |
| cfg.model.style_layers = 1 | |
| cfg.model.prosody_layers = 2 | |
| engine = MurliV2Engine(cfg.model, cfg.training) | |
| tok = BilingualTextTokenizer(use_g2p_en=False) | |
| ids = tok.text_to_ids("Hello friend, आज weather अच्छा है।").unsqueeze(0) | |
| bsz, t_text = ids.shape | |
| t_mel = t_text * 3 + 12 | |
| text_mask = ids != 0 | |
| mel_target = torch.randn(bsz, cfg.model.n_mels, t_mel) | |
| mel_mask = torch.ones(bsz, t_mel, dtype=torch.bool) | |
| f0 = torch.zeros(bsz, t_mel) | |
| energy = torch.zeros(bsz, t_mel) | |
| ref_mel = torch.randn(bsz, cfg.model.n_mels, 64) | |
| engine.train() | |
| out = engine( | |
| token_ids=ids, | |
| text_mask=text_mask, | |
| mel_target=mel_target, | |
| mel_mask=mel_mask, | |
| ref_mel=ref_mel, | |
| f0_target=f0, | |
| energy_target=energy, | |
| ) | |
| self.assertTrue(torch.isfinite(out["loss"])) | |
| out["loss"].backward() | |
| self.assertIsNotNone(engine.text_encoder.embed.weight.grad) | |
| # Also verify training path without explicit ref_mel uses random sub-window crop cleanly | |
| out_unpaired = engine( | |
| token_ids=ids, | |
| text_mask=text_mask, | |
| mel_target=mel_target, | |
| mel_mask=mel_mask, | |
| ref_mel=None, | |
| f0_target=f0, | |
| energy_target=energy, | |
| ) | |
| self.assertTrue(torch.isfinite(out_unpaired["loss"])) | |
| out_unpaired["loss"].backward() | |
| engine.eval() | |
| gen = engine.synthesize(ids, ref_mel=ref_mel, num_steps=4, method="midpoint", return_waveform=False) | |
| self.assertEqual(gen["mel"].shape[0], 1) | |
| self.assertEqual(gen["mel"].shape[1], cfg.model.n_mels) | |
| self.assertGreater(gen["mel"].shape[2], 0) | |
| self.assertTrue(torch.isfinite(gen["mel"]).all()) | |
| def test_curator_filters_and_parquet_roundtrip(self): | |
| import io | |
| import tempfile | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from scipy.io import wavfile | |
| from data.dataset import MurliV2Dataset, v2_collate_fn | |
| from kaggle_data_collector import ( | |
| map_female_ivr_hindi, | |
| map_female_mono_hindi, | |
| map_indicvoices_r_hindi, | |
| map_kalita_hindi, | |
| map_libritts_r, | |
| trim_silence, | |
| ) | |
| # Verify V1 dedup, female mappers & SNR filters | |
| self.assertIsNone(map_kalita_hindi({"speaker_id": "syspin_male_01", "text": "नमस्ते"})) | |
| self.assertIsNotNone(map_kalita_hindi({"speaker_id": "rasa_male_01", "text": "नमस्ते", "gender": "male"})) | |
| self.assertEqual(map_female_mono_hindi("iisc_f")({"text": "नमस्ते", "speaker_id": "f1"})[2], "female") | |
| self.assertEqual(map_female_ivr_hindi("18_30")({"transcription": "नमस्ते", "file_name": "spk9/a.wav"})[2], "female") | |
| self.assertIsNone(map_indicvoices_r_hindi({"snr": 12.5, "text": "नमस्ते"})) | |
| self.assertIsNotNone(map_indicvoices_r_hindi({"snr": 28.0, "normalized": "नमस्ते", "speaker_id": "s1"})) | |
| self.assertEqual(map_libritts_r({"text_normalized": "Hello world", "speaker_id": "42"})[1], "libritts_42") | |
| # Verify Parquet shard roundtrip into MurliV2Dataset + collate | |
| buf = io.BytesIO() | |
| t = torch.linspace(0.0, 2.0, 48000) | |
| pcm16 = (0.4 * torch.sin(2.0 * math.pi * 200.0 * t).numpy() * 32767.0).astype("int16") | |
| wavfile.write(buf, 24000, pcm16) | |
| trimmed = trim_silence(torch.sin(2.0 * math.pi * 200.0 * t), sr=24000) | |
| self.assertGreater(trimmed.numel(), 24000) | |
| with tempfile.TemporaryDirectory() as tmp: | |
| p = Path(tmp) / "shard-00000.parquet" | |
| tbl = pa.table({ | |
| "audio": [{"bytes": buf.getvalue(), "path": "clip.wav"}, {"bytes": buf.getvalue(), "path": "en.wav"}], | |
| "text": ["नमस्ते दोस्त!", "Hello friend!"], | |
| "speaker_id": ["s1", "s2"], | |
| "lang": ["hi", "en"], | |
| }) | |
| pq.write_table(tbl, p) | |
| ds = MurliV2Dataset(parquet_dir=tmp) | |
| self.assertEqual(len(ds), 2) | |
| batch = v2_collate_fn([ds[0], ds[1]]) | |
| self.assertEqual(batch["token_ids"].shape[0], 2) | |
| self.assertEqual(batch["mel_target"].shape[1], 100) | |
| def test_long_form_bilingual_and_bucket_sampler(self): | |
| from unittest.mock import Mock | |
| import numpy as np | |
| from train import BucketBatchSampler | |
| from utils.long_form import split_bilingual_clauses, synthesize_bilingual_long_text | |
| sampler = BucketBatchSampler([10.0, 2.0, 9.8, 2.1], batch_size=2, seed=42) | |
| batches = list(sampler) | |
| # Short items (indices 1,3) and long items (indices 0,2) must pair together | |
| grouped = {tuple(sorted(b)) for b in batches} | |
| self.assertEqual(grouped, {(0, 2), (1, 3)}) | |
| text = "नमस्ते दोस्त! यह पहली लाइन है।\n\nHello friend, today AI works cleanly." | |
| clauses = split_bilingual_clauses("नमस्ते दोस्त! This is English.", max_clause_words=6) | |
| self.assertEqual(len(clauses), 2) | |
| tok = BilingualTextTokenizer(use_g2p_en=False) | |
| mock_model = Mock() | |
| ref = torch.randn(1, 100, 32) | |
| mock_model.synthesize.side_effect = lambda ids, ref_mel=None, generator=None, **kw: ( | |
| self.assertIs(ref_mel, ref) or {"waveform": torch.randn(1, 1200, generator=generator)} | |
| ) | |
| wav1 = synthesize_bilingual_long_text(mock_model, tok, text, torch.device("cpu"), ref_mel=ref, seed=7) | |
| wav2 = synthesize_bilingual_long_text(mock_model, tok, text, torch.device("cpu"), ref_mel=ref, seed=7) | |
| np.testing.assert_array_equal(wav1, wav2) | |
| def test_20_sentence_hinglish_suite(self): | |
| tok = BilingualTextTokenizer(use_g2p_en=False) | |
| sentences = [ | |
| # Pure Devanagari Hindi (4) | |
| "नमस्ते, आज मौसम बहुत अच्छा है।", | |
| "ईंधन और कंबल की जरूरत है।", | |
| "बढ़ई ने सुंदर लकड़ी की मेज बनाई।", | |
| "कल सुबह पांच बजे मिलते हैं।", | |
| # Pure English (4) | |
| "Hello friend, please download the audio file.", | |
| "We didn't expect the GPU server to finish today.", | |
| "The meeting is scheduled in the office at 5 PM.", | |
| "That's a good voice model for speech synthesis.", | |
| # Roman Hinglish + orthographic variants (5) | |
| "Aaj mausam bohot achha hai, lekin kal barish hogi.", | |
| "Kyaa aapka kaam abhi nahi hua hai?", | |
| "Namaste bhai, shaam ko ghar aana naheen bhoolna.", | |
| "Yeh kahani bahut accha aur pyara hai.", | |
| "Chalo dost, subah 6 baje walk par chalte hain.", | |
| # Mixed Devanagari + Roman code-switching (3) | |
| "नमस्ते friend, आज AI model launch हो रहा है!", | |
| "मेरा phone और server दोनों fast काम कर रहे हैं।", | |
| "आज office में project meeting बहुत good रही।", | |
| # Homographs + context numbers (4) | |
| "Main aaj 5 baje office me jaunga.", | |
| "I am in the main bus on my way to work.", | |
| "Bus karo yaar, ab ghar chalo!", | |
| "Meet me at 5 PM in the main conference hall.", | |
| ] | |
| self.assertEqual(len(sentences), 20) | |
| for s in sentences: | |
| ids = tok.text_to_ids(s) | |
| self.assertGreater(ids.numel(), 4, f"Empty/short tokens for: {s}") | |
| self.assertLess(int(ids.max().item()), tok.vocab_size) | |
| # Verify homograph routing: "5 baje" -> Hindi paanch (<hi>), "5 PM" -> English five (<en>) | |
| hi_num = tok.text_to_phonemes("Main aaj 5 baje jaunga.") | |
| en_num = tok.text_to_phonemes("Meet me at 5 PM in the main hall.") | |
| self.assertIn("<hi>", hi_num) | |
| self.assertIn("p", hi_num) | |
| self.assertIn("<en>", en_num) | |
| self.assertIn("f", en_num) | |
| # Verify orthographic variants collapse identically | |
| self.assertEqual(tok.text_to_phonemes("bohot achha naheen kyaa"), tok.text_to_phonemes("bahut accha nahi kya")) | |
| # Verify OOV Roman-Hindi words inherit <hi> from clause majority (no false <en> switches) | |
| s3_ipa = tok.text_to_phonemes(sentences[8]) | |
| self.assertNotIn("<en>", s3_ipa) | |
| s5_ipa = tok.text_to_phonemes(sentences[16]) | |
| self.assertEqual(s5_ipa.count("<en>"), 1) # Only 'office' should switch to <en> | |
| self.assertEqual(s5_ipa[-3], "aː") # 'jaunga' ends cleanly in Hindi aː before '.' and '<eos>' | |
| # Print 5 sample IPA tokenizations for Sprint 1 report | |
| print("\n[Sample Hinglish G2P Outputs]") | |
| for sample in [sentences[0], sentences[6], sentences[8], sentences[13], sentences[16]]: | |
| print(f" TEXT: {sample}") | |
| print(f" IPA : {' '.join(tok.text_to_phonemes(sample))}") | |
| def test_cross_utterance_ref_sampling_and_indictts_source(self): | |
| import io | |
| import tempfile | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from scipy.io import wavfile | |
| from data.dataset import MurliV2Dataset, v2_collate_fn | |
| import kaggle_data_collector as kdc | |
| # Verify SPRINGLab/IndicTTS-English source registration | |
| en_src = next(s for s in kdc.SOURCES if s.name == "english_indictts") | |
| self.assertEqual(en_src.repo, "SPRINGLab/IndicTTS-English") | |
| self.assertEqual(en_src.lang, "en") | |
| buf1, buf2 = io.BytesIO(), io.BytesIO() | |
| t = torch.linspace(0.0, 2.0, 48000) | |
| wavfile.write(buf1, 24000, (0.3 * torch.sin(2.0 * math.pi * 180.0 * t).numpy() * 32767.0).astype("int16")) | |
| wavfile.write(buf2, 24000, (0.4 * torch.sin(2.0 * math.pi * 240.0 * t).numpy() * 32767.0).astype("int16")) | |
| with tempfile.TemporaryDirectory() as tmp: | |
| p = Path(tmp) / "shard-00000.parquet" | |
| tbl = pa.table({ | |
| "audio": [ | |
| {"bytes": buf1.getvalue(), "path": "a1.wav"}, | |
| {"bytes": buf2.getvalue(), "path": "a2.wav"}, | |
| {"bytes": buf1.getvalue(), "path": "u1.wav"}, | |
| ], | |
| "text": ["नमस्ते दोस्त!", "यह अच्छा दिन है।", "Hello friend!"], | |
| "speaker_id": ["spk_known_1", "spk_known_1", "indictts_en_unknown"], | |
| "lang": ["hi", "hi", "en"], | |
| }) | |
| pq.write_table(tbl, p) | |
| ds = MurliV2Dataset(parquet_dir=tmp, cross_utterance_ref=True, min_ref_frames=60, max_ref_frames=120) | |
| s_known = ds[0] | |
| s_unknown = ds[2] | |
| self.assertIn("ref_mel", s_known) | |
| self.assertLessEqual(s_known["ref_mel"].shape[-1], 120) | |
| self.assertNotIn("ref_mel", s_unknown) | |
| batch = v2_collate_fn([s_known, s_unknown]) | |
| self.assertTrue(bool(batch["ref_mask"][0].any().item())) | |
| self.assertFalse(bool(batch["ref_mask"][1].any().item())) | |
| # Mixed-batch training forward (row 0 uses cross-utterance ref, row 1 uses SpecAugment self-crop) | |
| cfg = MurliV2Config() | |
| cfg.model.dit_layers = 2 | |
| cfg.model.text_layers = 2 | |
| cfg.model.style_layers = 1 | |
| cfg.model.prosody_layers = 2 | |
| engine = MurliV2Engine(cfg.model, cfg.training).train() | |
| out = engine( | |
| token_ids=batch["token_ids"], | |
| text_mask=batch["text_mask"], | |
| mel_target=batch["mel_target"], | |
| mel_mask=batch["mel_mask"], | |
| ref_mel=batch["ref_mel"], | |
| ref_mask=batch["ref_mask"], | |
| f0_target=batch["f0_target"], | |
| energy_target=batch["energy_target"], | |
| ) | |
| self.assertTrue(torch.isfinite(out["loss"])) | |
| out["loss"].backward() | |
| if __name__ == "__main__": | |
| unittest.main() | |