File size: 14,763 Bytes
b6b7e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1cd84e
 
 
b6b7e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1cd84e
 
 
 
 
 
 
 
 
 
 
 
 
b6b7e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bcca65
 
b6b7e3c
 
 
 
 
 
8bcca65
b6b7e3c
 
8bcca65
 
b6b7e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4689281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ea4cde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e7befd
 
 
 
 
 
 
3ea4cde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6b7e3c
 
 
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
"""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()