Mevearth2 commited on
Commit
65700a7
·
verified ·
1 Parent(s): 20dde8e

Backup tts_hosting 2026-04-24 16:16:42 UTC

Browse files
.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ *.log
6
+ .env
7
+ .venv/
8
+ .git/
.env.example ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model and auth
2
+ MODEL_NAME=Mevearth2/Quantized-Merged-TTS
3
+ HF_TOKEN=
4
+
5
+ # Service behavior
6
+ MAX_INFLIGHT_REQUESTS=2
7
+ TTS_TEMPERATURE=0.4
8
+ TTS_TOP_P=0.9
9
+ TTS_REPETITION_PENALTY=1.05
10
+ TTS_MAX_SEQ_LENGTH=2048
11
+ TTS_MAX_WORDS=50
12
+ TTS_DENOISE=false
.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+ .venv/
7
+ .vscode/
8
+ *.log
.source_README.md ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: snorbyte/snorTTS-Indic-v0
3
+ tags:
4
+ - text-to-speech
5
+ - tts
6
+ - transformers
7
+ - unsloth
8
+ - llama
9
+ - audio
10
+ - speech-synthesis
11
+ license: apache-2.0
12
+ language:
13
+ - hi
14
+ - gu
15
+ - mr
16
+ - pa
17
+ - bn
18
+ - te
19
+ - kn
20
+ - ml
21
+ - ta
22
+ ---
23
+
24
+ # snorTTS-Indic-v0
25
+ snorTTS-Indic-v0 is a multilingual Indic Text-to-Speech (TTS) model capable of generating speech in nine Indic languages: Hindi, Tamil, Telugu, Marathi, Kannada, Malayalam, Punjabi, Gujarati, and Bengali.
26
+
27
+ 👉 [Read the full blog: *Train a SoTA Multilingual Indic Text-to-Speech (TTS)*](https://snorbyte.com/blog/train-sota-multilingual-indic-tts) to learn how we built it.
28
+
29
+ 👉 [Try out the model in our playground](https://snorbyte.com/snortts-indic-v0).
30
+
31
+ All code, datasets, and models—both base and fine-tuned—used in this work are available below for anyone to use and build upon.
32
+
33
+ <video controls preload="metadata"
34
+ src="https://gamespaces.store/demo-142-2.mp4"
35
+ style="width:100%;border-radius:0.75rem;margin:1rem 0;">
36
+ </video>
37
+
38
+ ## Capabilities
39
+
40
+ - TTS
41
+ - Voice-Cloning
42
+ - Code Switching
43
+ - Cross-lingual Voice Cloning (Multilingual Voice Transfer)
44
+
45
+ ## Model Overview
46
+ | Item | Details |
47
+ |------------------------|----------------------------------------------------------------------------------------------------------------------------|
48
+ | **Architecture** | LLaMA-3.2-3B |
49
+ | **Base model** | `canopylabs/3b-hi-pretrain-research_release` |
50
+ | **Audio codec** | SNAC @ 24 kHz, 3 codebooks (12,288 new tokens) |
51
+ | **Languages** | Hindi, Gujarati, Marathi, Punjabi, Bengali, Telugu, Kannada, Malayalam, Tamil |
52
+
53
+
54
+ ## Training
55
+
56
+ For details about the training and dataset, please refer to [*Train a SoTA Multilingual Indic Text-to-Speech (TTS)*](https://snorbyte.com/blog/train-sota-multilingual-indic-tts).
57
+
58
+ You can find the training script (`train_orepheus.py`) in this repository. It is a single, self-contained script for fine-tuning the base model.
59
+
60
+ 👉 Dataset used for training: [snorbyte/indic-tts-sample-snac-encoded](https://huggingface.co/datasets/snorbyte/indic-tts-sample-snac-encoded)
61
+
62
+ ## Inference
63
+
64
+ 👉 To host in Modal: Check the ```modal``` folder
65
+
66
+ - Install necessary libraries for linux
67
+ ```bash
68
+ sudo apt update
69
+ ```
70
+ ```bash
71
+ sudo apt install -y sox libsox-dev
72
+ ```
73
+ - Use Python 3.10
74
+ - If you already have torch installed, uninstall it. Let unsloth take care of it.
75
+ ```bash
76
+ pip uninstall -y torch torchaudio
77
+ ```
78
+ - Install necessary packages
79
+ ```bash
80
+ pip install unsloth loguru snac deepfilternet pydub soundfile librosa torchaudio
81
+ ```
82
+
83
+ ```python
84
+ from unsloth import FastLanguageModel
85
+ from snac import SNAC
86
+ import soundfile as sf
87
+ import numpy as np
88
+ from loguru import logger
89
+ from df.enhance import init_df, enhance, save_audio
90
+ import torch
91
+ import librosa
92
+ import torchaudio
93
+ import os
94
+
95
+ #Name of the model
96
+ MODEL_NAME = 'snorbyte/snorTTS-Indic-v0'
97
+ MAX_SEQ_LENGTH = 4096
98
+ HUGGINGFACE_TOKEN = "" # ! Add your hugging face token
99
+
100
+ # Load the model and tokenizer.
101
+ model, tokenizer = FastLanguageModel.from_pretrained(
102
+ model_name=MODEL_NAME,
103
+ # load_in_4bit=True,
104
+ max_seq_length=MAX_SEQ_LENGTH,
105
+ token=HUGGINGFACE_TOKEN,
106
+ )
107
+ logger.success(f"Loaded model: {MODEL_NAME}")
108
+
109
+
110
+ # Load the end of speech token for the tokenizer.
111
+ tokeniser_length = 128256
112
+ end_of_speech_id = tokeniser_length + 2
113
+ pad_token_id = tokeniser_length + 7
114
+ audio_start_id = tokeniser_length + 10
115
+
116
+ pad_token = tokenizer.decode([pad_token_id])
117
+ logger.success("Load special tokens for the tokenizer.")
118
+
119
+ # Wrap Model for Inference
120
+ FastLanguageModel.for_inference(model)
121
+ logger.success(f"{MODEL_NAME} is ready for inference.")
122
+
123
+ # Set the padding token and padding side.
124
+ tokenizer.pad_token = pad_token
125
+ tokenizer.padding_side = "left"
126
+ logger.success("Set padding token and padding side for the tokenizer.")
127
+
128
+ # Load the SNAC model for audio decoding.
129
+ snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
130
+ logger.success("Loaded SNAC model for audio decoding.")
131
+
132
+ # Load DeepFilter for optional post processing
133
+ df_model, df_state, _ = init_df()
134
+
135
+ # Function to generate audio
136
+ def generate_audio(
137
+ row, model, tokenizer, user=False, temperature=0.4, top_p=0.9, repetition_penalty=1.05
138
+ ):
139
+ try:
140
+ if user:
141
+ prompt = row["eval_text_user"]
142
+ else:
143
+ prompt = row["eval_text_no_user"]
144
+ inputs = tokenizer(prompt, add_special_tokens=False, return_tensors="pt")
145
+ max_tokens = MAX_SEQ_LENGTH - inputs.input_ids.shape[1]
146
+ output = model.generate(
147
+ input_ids=inputs.input_ids.to("cuda"),
148
+ attention_mask=inputs.attention_mask.to("cuda"),
149
+ max_new_tokens=max_tokens,
150
+ temperature=temperature,
151
+ top_p=top_p,
152
+ repetition_penalty=repetition_penalty,
153
+ eos_token_id=end_of_speech_id,
154
+ )
155
+ audio_ids = []
156
+ for id in output[0]:
157
+ if id >= audio_start_id:
158
+ audio_ids.append(id.item())
159
+ clean_audio_ids = []
160
+ for i in range((len(audio_ids) + 1) // 7):
161
+ for j in range(7):
162
+ clean_audio_ids += [audio_ids[7 * i + j] - audio_start_id]
163
+ codes = [[], [], []]
164
+ for i in range((len(clean_audio_ids) + 1) // 7):
165
+ codes[0].append(clean_audio_ids[7 * i])
166
+ codes[1].append(clean_audio_ids[7 * i + 1] - 4096)
167
+ codes[2].append(clean_audio_ids[7 * i + 2] - (2 * 4096))
168
+ codes[2].append(clean_audio_ids[7 * i + 3] - (3 * 4096))
169
+ codes[1].append(clean_audio_ids[7 * i + 4] - (4 * 4096))
170
+ codes[2].append(clean_audio_ids[7 * i + 5] - (5 * 4096))
171
+ codes[2].append(clean_audio_ids[7 * i + 6] - (6 * 4096))
172
+ codes = [
173
+ torch.tensor(codes[0]).unsqueeze(0),
174
+ torch.tensor(codes[1]).unsqueeze(0),
175
+ torch.tensor(codes[2]).unsqueeze(0),
176
+ ]
177
+ try:
178
+ audio = snac_model.decode(codes)
179
+ except Exception as e:
180
+ logger.error(f"Error decoding audio: {e}")
181
+ return None
182
+ return audio.detach().squeeze().to("cpu").numpy()
183
+ except Exception as e:
184
+ logger.error(f"Error decoding audio: {e}")
185
+ return None
186
+
187
+ # Run inference.
188
+ # * Please refer to the training script to create prompt from SNAC tokens.
189
+ row = {
190
+ "eval_text_user": f"<custom_token_3><|begin_of_text|>kannada142: ಅಯ್ಯಯ್ಯೋ... Whitefield ಗೆ reach ಆಗೋಕೆ almost 10 hours ಆಯ್ತು you know... traffic was so terrible today <|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
191
+ }
192
+
193
+ eval_sample = generate_audio(row, model, tokenizer, True)
194
+ if eval_sample is None:
195
+ logger.error("Failed to generate audio for evaluation sample.")
196
+ else:
197
+ logger.success("Audio Generated. Post Processing Started")
198
+
199
+ ## post-processing settings
200
+ filename = "eval.wav"
201
+ speed = 1.05 #add speed up according to speaker
202
+ denoise = False #denoise if you want
203
+ output = eval_sample.astype(np.float32)
204
+
205
+ #speed up
206
+ if abs(speed - 1.0) > 1e-4:
207
+ output_t = torch.from_numpy(output).unsqueeze(0)
208
+ output_speed, _ = torchaudio.sox_effects.apply_effects_tensor(output_t, 24_000, effects=[["tempo", f"{speed}"]])
209
+ output = output_speed.squeeze(0).cpu().numpy()
210
+
211
+ #denoise
212
+ if denoise:
213
+ resampled_48k = librosa.resample(output, orig_sr=24_000, target_sr=48_000)
214
+ resampled_48k = torch.from_numpy(resampled_48k).unsqueeze(0)
215
+ output_48k = enhance(df_model, df_state, resampled_48k)
216
+ output_48k = output_48k.squeeze(0).cpu().numpy()
217
+ output = librosa.resample(output_48k, orig_sr=48_000, target_sr=24_000)
218
+
219
+ logger.success("Saving Final Output...")
220
+
221
+ #save
222
+ sf.write(filename, output, 24_000)
223
+
224
+ logger.success(f"Generated and saved evaluation sample audio as {filename}.")
225
+ ```
226
+
227
+ ## Prompts
228
+
229
+ - **Standard**
230
+
231
+ ```python
232
+ {
233
+ "eval_text_no_user": f"<custom_token_3><|begin_of_text|>{utterance}<|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
234
+ }
235
+ ```
236
+
237
+ ```python
238
+ {
239
+ "eval_text_no_user": f"<custom_token_3><|begin_of_text|>நிச்சயமா. ரோம் ல் இரவு நேரம் ரொம்ப அழகா இருக்கு—piazzaகள் சுத்துறதுக்கு நல்ல நேரம்.<|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
240
+ },
241
+ ```
242
+
243
+ - **Speaker Specific**: (Recommended)
244
+
245
+ ```python
246
+ {
247
+ "eval_text_user": f"<custom_token_3><|begin_of_text|>{language}{speaker_id}: {utterance}<|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
248
+ }
249
+ ```
250
+
251
+ > 📝 `utterance` can be in native language of the speaker, multi-lingual, or code-switched as well.
252
+
253
+ ```python
254
+ {
255
+ "eval_text_user": f"<custom_token_3><|begin_of_text|>hindi159: चलते रहो इस सफर में बिना रुके, क्योंकि मंज़िलें खुद राह दिखाने लगती हैं <|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
256
+ }
257
+ ```
258
+
259
+ ```python
260
+ {
261
+ "eval_text_user": f"<custom_token_3><|begin_of_text|>bengali125: मुझे तो लगा वो आएगा, ஆனா அவன் வந்து full drama பண்ணிட்டான், আর শেষে আবার আমাকে দোষ দিচ্ছে <|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
262
+ }
263
+ ```
264
+
265
+
266
+ ### Speaker IDs
267
+
268
+ | Language | Speakers | Recommended Speedup |
269
+ |-----------|------------------|----------------------|
270
+ | Hindi | [159,49,43] | [1.05,1.1,1.1] |
271
+ | Tamil | [188,128,176] | [1.1,1.15,1.1] |
272
+ | Bengali | [125] | [1.1] |
273
+ | Malayalam | [189,124] | [1.1,1.1] |
274
+ | Kannada | [142,138,131,59] | [1.05,1.1,1.1,1.1] |
275
+ | Telugu | [69,133] | [1.1,1.1] |
276
+ | Punjabi | [191,67,201] | [1.08,1.06,1.1] |
277
+ | Gujarati | [62,190] | [1.15,1.25] |
278
+ | Marathi | [205,82,199,203] | [1.05,1.05,1.1,1.15] |
279
+
280
+ ## Contact Us
281
+ 👉 Mail: [founders@snorbyte.com](mailto:founders@snorbyte.com)
282
+
283
+ 👉 Website: [https://snorbyte.com](https://snorbyte.com)
284
+
285
+ ## Citation
286
+
287
+ BibTeX:
288
+
289
+ ```bibtex
290
+ @misc{indictextaudio2025,
291
+ title={snorTTS-Indic-v0: Multilingual Indic TTS},
292
+ author={snorbyte},
293
+ year={2025},
294
+ howpublished={\url{snorbyte/snorTTS-Indic-v0}},
295
+ note={Apache-2.0}
296
+ }
297
+ ```
.source_modal__snorTTS_Indic_v0_server.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # * Install Modal.
2
+ # uv run pip install modal
3
+
4
+ # * Setup Modal.
5
+ # uv run modal setup
6
+
7
+ # * Run to deploy the Modal app.
8
+ # uv run modal deploy scripts/modal/snorTTS_Indic_v0_server.py
9
+
10
+ # * Test.
11
+ # curl -X 'POST' \
12
+ # 'https://snorbyte--snortts-indic-v0-server-prod-ttsserver-serve.modal.run/?utterance=%E0%A4%95%E0%A4%B2%20%E0%A4%AE%E0%A5%88%E0%A4%82%E0%A4%A8%E0%A5%87%20%E0%A4%B8%E0%A4%BF%E0%A4%B0%E0%A5%8D%E0%A4%AB%20%E2%82%B9500%20%E0%A4%AE%E0%A5%87%E0%A4%82%20%E0%A4%8F%E0%A4%95%20cool%20headphones%20%E0%A4%B2%E0%A5%87%20%E0%A4%B2%E0%A4%BF%E0%A4%8F%2C%20%E0%A4%AC%E0%A4%B9%E0%A5%81%E0%A4%A4%20%E0%A4%AC%E0%A4%A2%E0%A4%BC%E0%A4%BF%E0%A4%AF%E0%A4%BE%20deal%20%E0%A4%A5%E0%A4%BE%20%E0%A4%AF%E0%A4%BE%E0%A4%B0%21&user_id=159&language=hindi&temperature=0.4&top_p=0.9&repetition_penalty=1.05&speed=1.05&denoise=true&stream=false' \
13
+ # -H 'accept: audio/mpeg' \
14
+ # -d '' \
15
+ # --output outputs/output_non_stream.mp3
16
+
17
+ # curl -X 'POST' \
18
+ # 'https://snorbyte--snortts-indic-v0-server-prod-ttsserver-serve.modal.run/?utterance=%E0%A4%95%E0%A4%B2%20%E0%A4%AE%E0%A5%88%E0%A4%82%E0%A4%A8%E0%A5%87%20%E0%A4%B8%E0%A4%BF%E0%A4%B0%E0%A5%8D%E0%A4%AB%20%E2%82%B9500%20%E0%A4%AE%E0%A5%87%E0%A4%82%20%E0%A4%8F%E0%A4%95%20cool%20headphones%20%E0%A4%B2%E0%A5%87%20%E0%A4%B2%E0%A4%BF%E0%A4%8F%2C%20%E0%A4%AC%E0%A4%B9%E0%A5%81%E0%A4%A4%20%E0%A4%AC%E0%A4%A2%E0%A4%BC%E0%A4%BF%E0%A4%AF%E0%A4%BE%20deal%20%E0%A4%A5%E0%A4%BE%20%E0%A4%AF%E0%A4%BE%E0%A4%B0%21&user_id=159&language=hindi&temperature=0.4&top_p=0.9&repetition_penalty=1.05&speed=1.05&denoise=true&stream=true' \
19
+ # -H 'accept: audio/mpeg' \
20
+ # -d '' \
21
+ # --output outputs/output_stream.mp3
22
+
23
+ # Import Modal.
24
+ import modal
25
+
26
+
27
+ # Define constants.
28
+ APP_NAME = "snorTTS-Indic-v0-server-prod"
29
+ SCALEDOWN_WINDOW = 15 * 60
30
+ TIMEOUT = 10 * 60
31
+ MIN_CONTAINERS = 1
32
+ MAX_CONTAINERS = 1
33
+ MAX_CONCURRENT_REQUESTS = 5
34
+
35
+
36
+ # Define the Docker image.
37
+ image = (
38
+ modal.Image.debian_slim(python_version="3.12")
39
+ .apt_install(
40
+ "curl", # Install curl for downloading files.
41
+ "ffmpeg", # Install ffmpeg for audio processing.
42
+ "git", # Install git for version control.
43
+ "libsox-dev", # Install SoX for audio processing.
44
+ )
45
+ .run_commands(
46
+ "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y", # Install Rust.
47
+ )
48
+ .env(
49
+ {
50
+ "PATH": "/root/.cargo/bin:${PATH}", # Add Rust to PATH.
51
+ "HF_HUB_ENABLE_HF_TRANSFER": "1", # Set `HF_HUB_ENABLE_HF_TRANSFER` for fast model transfers.
52
+ }
53
+ )
54
+ .pip_install(
55
+ "deepfilternet", # Install DeepFilterNet for audio denoising.
56
+ "fastapi[standard]", # Install FastAPI for building the API.
57
+ "hf_transfer", # Install Hugging Face transfer for fast model transfers.
58
+ "loguru", # Install Loguru for logging.
59
+ "numpy", # Install NumPy for numerical operations.
60
+ "pydub", # Install Pydub for audio processing.
61
+ "snac", # Install SNAC for audio decoding.
62
+ "torchaudio", # Install Torchaudio for audio processing.
63
+ "transformers", # Install Transformers for model handling.
64
+ )
65
+ )
66
+
67
+ # Create the Modal app.
68
+ app = modal.App(APP_NAME, image=image)
69
+
70
+ with image.imports():
71
+ # Import necessary libraries for the remote function.
72
+ from typing import Any
73
+ import aiohttp
74
+ import io
75
+ import json
76
+
77
+ from df.enhance import init_df, enhance
78
+ from fastapi.responses import StreamingResponse
79
+ from loguru import logger
80
+ from pydub import AudioSegment
81
+ from snac import SNAC
82
+ from transformers import AutoTokenizer
83
+ import numpy as np
84
+ import torch
85
+ import torchaudio as ta
86
+
87
+
88
+ @app.cls(
89
+ cpu=4.0, # Set number of CPU cores.
90
+ memory=8192, # Set memory in MiB.
91
+ scaledown_window=SCALEDOWN_WINDOW, # Set how long should we stay up with no requests.
92
+ timeout=TIMEOUT, # Set the timeout for the function.
93
+ enable_memory_snapshot=True, # Enable memory snapshot for better cold boot times.
94
+ min_containers=MIN_CONTAINERS, # Minimum number of containers to keep running.
95
+ max_containers=MAX_CONTAINERS, # Maximum number of containers to run.
96
+ )
97
+ @modal.concurrent(
98
+ max_inputs=MAX_CONCURRENT_REQUESTS
99
+ ) # Limit the number of concurrent requests.
100
+ class TTSServer:
101
+ @modal.enter()
102
+ def load(self) -> None:
103
+ # Load the tokenizer.
104
+ self.tokenizer = AutoTokenizer.from_pretrained("snorbyte/snorTTS-Indic-v0")
105
+ logger.success("Loaded tokenizer from snorbyte/snorTTS-Indic-v0.")
106
+
107
+ # Token related bookkeeping.
108
+ # Set the tokenizer length.
109
+ self.tokeniser_length = 128256
110
+ logger.success("Set tokenizer length.")
111
+
112
+ # Set the end of speech ID, pad token ID, and audio start ID.
113
+ self.end_of_speech_id = self.tokeniser_length + 2
114
+ self.pad_token_id = self.tokeniser_length + 7
115
+ self.audio_start_id = self.tokeniser_length + 10
116
+ logger.success("Set end of speech ID, pad token ID, and audio start ID.")
117
+
118
+ # Decode the pad token.
119
+ self.pad_token = self.tokenizer.decode([self.pad_token_id])
120
+ logger.success("Decoded pad token.")
121
+
122
+ # Set the padding token and padding side.
123
+ self.tokenizer.pad_token = self.pad_token
124
+ self.tokenizer.padding_side = "left"
125
+ logger.success("Set padding token and padding side for the tokenizer.")
126
+
127
+ # Models.
128
+ # Load the SNAC model for audio decoding.
129
+ self.snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
130
+ logger.success("Loaded SNAC model for audio decoding.")
131
+
132
+ # Initialize the DF model for audio denoising.
133
+ self.df_model, self.df_state, _ = init_df()
134
+ logger.success("Initialized DF model for audio denoising.")
135
+
136
+ async def _decode_audio(self, audio_ids: list[int], speed: float, denoise: bool):
137
+ # Offset the audio tokens by the audio start ID.
138
+ snac_audio_ids = []
139
+ for i in range((len(audio_ids) + 1) // 7):
140
+ for j in range(7):
141
+ snac_audio_ids += [audio_ids[7 * i + j] - self.audio_start_id]
142
+
143
+ # Prepare the codes for SNAC decoding.
144
+ # ! Please note: codes cannot be negative. If the model generates incorrect codes
145
+ # ! at the wrong positions, audio generation will fail.
146
+ codes = [[], [], []]
147
+ for i in range((len(snac_audio_ids) + 1) // 7):
148
+ codes[0].append(snac_audio_ids[7 * i])
149
+ codes[1].append(snac_audio_ids[7 * i + 1] - 4096)
150
+ codes[2].append(snac_audio_ids[7 * i + 2] - (2 * 4096))
151
+ codes[2].append(snac_audio_ids[7 * i + 3] - (3 * 4096))
152
+ codes[1].append(snac_audio_ids[7 * i + 4] - (4 * 4096))
153
+ codes[2].append(snac_audio_ids[7 * i + 5] - (5 * 4096))
154
+ codes[2].append(snac_audio_ids[7 * i + 6] - (6 * 4096))
155
+ codes = [
156
+ torch.tensor(codes[0]).unsqueeze(0),
157
+ torch.tensor(codes[1]).unsqueeze(0),
158
+ torch.tensor(codes[2]).unsqueeze(0),
159
+ ]
160
+
161
+ try:
162
+ # Decode the audio using SNAC.
163
+ audio = self.snac_model.decode(codes).reshape(1, -1)
164
+ logger.success(f"Decoded {len(snac_audio_ids)} SNAC tokens to audio.")
165
+ except Exception as e:
166
+ logger.error(f"Error decoding audio: {e}")
167
+ return None
168
+
169
+ # Speed up or slow down the audio.
170
+ if abs(speed - 1.0) > 1e-4:
171
+ try:
172
+ audio, _ = ta.sox_effects.apply_effects_tensor(
173
+ audio, 24_000, effects=[["tempo", f"{speed}"]]
174
+ )
175
+ logger.success(
176
+ f"Applied speed effect to audio with speed factor {speed}."
177
+ )
178
+ except Exception as e:
179
+ logger.error(f"Error applying speed effect: {e}")
180
+ return None
181
+
182
+ # Denoise the audio.
183
+ if denoise:
184
+ try:
185
+ audio = ta.transforms.Resample(orig_freq=24_000, new_freq=48_000)(audio)
186
+ audio = enhance(self.df_model, self.df_state, audio)
187
+ audio = ta.transforms.Resample(orig_freq=48_000, new_freq=24_000)(audio)
188
+ logger.success("Denoised audio using DeepFilterNet.")
189
+ except Exception as e:
190
+ logger.error(f"Error denoising audio: {e}")
191
+ return None
192
+
193
+ # Move the audio to CPU and convert to numpy array.
194
+ audio = audio.detach().squeeze().cpu().numpy()
195
+
196
+ return audio
197
+
198
+ async def _generate(
199
+ self,
200
+ utterance: str,
201
+ user_id: str = 159,
202
+ language: str = "hindi",
203
+ temperature: float = 0.4,
204
+ top_p: float = 0.9,
205
+ repetition_penalty: float = 1.05,
206
+ speed: float = 1.05,
207
+ denoise: bool = False,
208
+ stream: bool = True,
209
+ ):
210
+ try:
211
+ # Limit the utterance length to 50 words.
212
+ utterance = " ".join(utterance.split(" ")[:50])
213
+
214
+ logger.info(
215
+ f"Generating audio for utterance, {utterance}, user_id, {user_id}, language, {language}, "
216
+ f"temperature, {temperature}, top_p, {top_p}, repetition_penalty, {repetition_penalty}, "
217
+ f"speed, {speed}, denoise, {denoise} and stream, {stream}."
218
+ )
219
+
220
+ # Create the prompt.
221
+ prompt = f"<custom_token_3><|begin_of_text|>{language}{user_id}: {utterance}<|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
222
+
223
+ # Tokenize the prompt.
224
+ inputs = self.tokenizer(prompt, add_special_tokens=False)
225
+
226
+ # Set max audio tokens to generate.
227
+ max_tokens = 2048 - len(inputs.input_ids)
228
+
229
+ # Generate the output.
230
+ async with aiohttp.ClientSession(
231
+ base_url="https://snorbyte--snortts-indic-v0-vllm-prod-serve.modal.run"
232
+ ) as session:
233
+ # Prepare the payload for the vLLM server.
234
+ # ! Without type hinting the vLLM server will not recognize the request.
235
+ payload: dict[str, Any] = {
236
+ "prompt": prompt,
237
+ "model": "llm",
238
+ "stream": True,
239
+ "temperature": 0.4,
240
+ "top_p": 0.9,
241
+ "max_tokens": max_tokens,
242
+ "repetition_penalty": 1.05,
243
+ "add_special_tokens": False,
244
+ "stop_token_ids": [128258],
245
+ }
246
+
247
+ # Set the headers for the request.
248
+ headers = {
249
+ "Content-Type": "application/json",
250
+ "Accept": "text/event-stream",
251
+ }
252
+
253
+ # Initialize the audio tokens list.
254
+ audio_ids = []
255
+
256
+ # Send the request to the vLLM server to generate audio.
257
+ async with session.post(
258
+ "/v1/completions",
259
+ json=payload,
260
+ headers=headers,
261
+ timeout=1 * 60,
262
+ ) as resp:
263
+ # Maintine a buffer for the audio data.
264
+ buffer = io.BytesIO()
265
+
266
+ # Stream the vLLM response.
267
+ async for raw in resp.content:
268
+ # Check if the response is successful.
269
+ resp.raise_for_status()
270
+
271
+ # Decode bytes.
272
+ line = raw.decode().strip()
273
+
274
+ # Skip empty lines and end of stream.
275
+ if not line or line == "data: [DONE]":
276
+ continue
277
+
278
+ # Remove the "data: " prefix if present.
279
+ if line.startswith("data: "):
280
+ line = line[len("data: ") :]
281
+
282
+ # Parse the JSON response.
283
+ chunk = json.loads(line)
284
+
285
+ # Tokenize the generated tokens.
286
+ output = self.tokenizer(
287
+ chunk["choices"][0]["text"], add_special_tokens=False
288
+ ).input_ids
289
+
290
+ # Extract audio tokens from the output.
291
+ for id in output:
292
+ if id >= self.audio_start_id:
293
+ audio_ids.append(id)
294
+
295
+ # If streaming is enabled and the audio_ids list has more than 168 tokens,
296
+ # decode and yield the audio.
297
+ # ! This will lead to jittering in the audio stream.
298
+ if stream and len(audio_ids) > 168:
299
+ # Decode tokens to audio.
300
+ audio = await self._decode_audio(audio_ids, speed, denoise)
301
+
302
+ if audio is not None:
303
+ # Write the audio to the buffer.
304
+ # Convert to int16 PCM format expected by AudioSegment.
305
+ audio_int16 = (audio * 32767).astype(np.int16)
306
+
307
+ # Create raw audio segment.
308
+ raw_audio = AudioSegment(
309
+ audio_int16.tobytes(),
310
+ frame_rate=24000,
311
+ sample_width=2,
312
+ channels=1,
313
+ )
314
+
315
+ # Export the audio to the buffer in MP3 format.
316
+ raw_audio.export(buffer, format="mp3", bitrate="96k")
317
+
318
+ # Reset the buffer's internal pointer to the beginning of the stream.
319
+ # This allows reading the entire content from the start.
320
+ buffer.seek(0)
321
+
322
+ # Read the entire contents of the buffer into the `data` variable.
323
+ audio_data = buffer.read()
324
+
325
+ # Move the buffer's internal pointer back to the beginning again.
326
+ # This is done to prepare it for clearing.
327
+ buffer.seek(0)
328
+
329
+ # Truncate the buffer, effectively removing all contents.
330
+ # This clears it for reuse with new audio data.
331
+ buffer.truncate(0)
332
+
333
+ # Yield the audio data.
334
+ yield audio_data
335
+
336
+ # Keep the last incomplete frame.
337
+ last_index = len(audio_ids) % 7
338
+ if last_index == 0:
339
+ audio_ids = []
340
+ else:
341
+ audio_ids = audio_ids[-last_index:]
342
+
343
+ # Check if there are any remaining audio tokens to process.
344
+ if audio_ids:
345
+ # Decode tokens to audio.
346
+ audio = await self._decode_audio(audio_ids, speed, denoise)
347
+
348
+ if audio is not None:
349
+ # Write the audio to the buffer.
350
+ # Convert to int16 PCM format expected by AudioSegment.
351
+ audio_int16 = (audio * 32767).astype(np.int16)
352
+
353
+ # Create raw audio segment.
354
+ raw_audio = AudioSegment(
355
+ audio_int16.tobytes(),
356
+ frame_rate=24000,
357
+ sample_width=2,
358
+ channels=1,
359
+ )
360
+
361
+ # Export the audio to the buffer in MP3 format.
362
+ raw_audio.export(buffer, format="mp3", bitrate="96k")
363
+
364
+ # Reset the buffer's internal pointer to the beginning of the stream.
365
+ # This allows reading the entire content from the start.
366
+ buffer.seek(0)
367
+
368
+ # Read the entire contents of the buffer into the `data` variable.
369
+ audio_data = buffer.read()
370
+
371
+ # Move the buffer's internal pointer back to the beginning again.
372
+ # This is done to prepare it for clearing.
373
+ buffer.seek(0)
374
+
375
+ # Truncate the buffer, effectively removing all contents.
376
+ # This clears it for reuse with new audio data.
377
+ buffer.truncate(0)
378
+
379
+ # Yield the audio data.
380
+ yield audio_data
381
+ except Exception as e:
382
+ logger.exception(f"Error during audio generation: {e}")
383
+
384
+ @modal.fastapi_endpoint(
385
+ docs=True, method="POST"
386
+ ) # Define a FastAPI endpoint for TTS.
387
+ async def serve(
388
+ self,
389
+ utterance: str,
390
+ user_id: str = 159,
391
+ language: str = "hindi",
392
+ temperature: float = 0.4,
393
+ top_p: float = 0.9,
394
+ repetition_penalty: float = 1.05,
395
+ speed: float = 1.05,
396
+ denoise: bool = False,
397
+ stream: bool = True,
398
+ ):
399
+ # Stream the generated audio as an MP3 response.
400
+ return StreamingResponse(
401
+ self._generate(
402
+ utterance,
403
+ user_id=user_id,
404
+ language=language,
405
+ temperature=temperature,
406
+ top_p=top_p,
407
+ repetition_penalty=repetition_penalty,
408
+ speed=speed,
409
+ denoise=denoise,
410
+ stream=stream,
411
+ ),
412
+ media_type="audio/mpeg",
413
+ )
.source_modal__snorTTS_Indic_v0_vllm.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # * Install Modal.
2
+ # uv run pip install modal
3
+
4
+ # * Setup Modal.
5
+ # uv run modal setup
6
+
7
+ # * Run to deploy the Modal app.
8
+ # uv run modal deploy scripts/modal/snorTTS_Indic_v0_vllm.py
9
+
10
+ # Import Modal.
11
+ import modal
12
+
13
+
14
+ # Define constants.
15
+ MODEL_NAME = "snorbyte/snorTTS-Indic-v0"
16
+ MAX_SEQ_LEN = 2048
17
+ MAX_CONCURRENT_SEQS = 5
18
+ APP_NAME = "snorTTS-Indic-v0-vllm-prod"
19
+ SCALEDOWN_WINDOW = 15 * 60
20
+ TIMEOUT = 10 * 60
21
+ VLLM_PORT = 8000
22
+ GPU = "T4"
23
+ MIN_CONTAINERS = 1
24
+ MAX_CONTAINERS = 1
25
+ MAX_CONCURRENT_REQUESTS = MAX_CONCURRENT_SEQS
26
+
27
+ # Define the Docker image.
28
+ image = (
29
+ modal.Image.debian_slim(python_version="3.12")
30
+ .pip_install(
31
+ "vllm==0.9.1", # Install vLLM for serving models.
32
+ "huggingface_hub[hf_transfer]==0.32.0", # Install Hugging Face transfer for fast model transfers.
33
+ "flashinfer-python==0.2.6.post1", # Install FlashInfer for optimized inference.
34
+ extra_index_url="https://download.pytorch.org/whl/cu128", # Use pytorch's extra index url for flashinfer.
35
+ )
36
+ .env(
37
+ {
38
+ "HF_HUB_ENABLE_HF_TRANSFER": "1", # Set `HF_HUB_ENABLE_HF_TRANSFER` for fast model transfers.
39
+ }
40
+ )
41
+ )
42
+
43
+ # Setup volumes for cache.
44
+ hf_cache_vol = modal.Volume.from_name("huggingface-cache", create_if_missing=True)
45
+ vllm_cache_vol = modal.Volume.from_name("vllm-cache", create_if_missing=True)
46
+
47
+ # Create the Modal app.
48
+ app = modal.App(APP_NAME)
49
+
50
+
51
+ with image.imports():
52
+ # Import necessary libraries for the remote function.
53
+ import subprocess
54
+
55
+
56
+ # Define the function to start the VLLM server.
57
+ @app.function(
58
+ image=image, # Set the image for the function.
59
+ gpu=GPU, # Set the GPU type for the instance.
60
+ scaledown_window=SCALEDOWN_WINDOW, # Set how we long should we stay up with no requests.
61
+ timeout=TIMEOUT, # Set the timeout for the function.
62
+ volumes={
63
+ "/root/.cache/huggingface": hf_cache_vol,
64
+ "/root/.cache/vllm": vllm_cache_vol,
65
+ }, # Set the volumes for cache.
66
+ min_containers=MIN_CONTAINERS, # Minimum number of containers to keep running.
67
+ max_containers=MAX_CONTAINERS, # Maximum number of containers to run.
68
+ )
69
+ @modal.concurrent(
70
+ max_inputs=MAX_CONCURRENT_REQUESTS
71
+ ) # Limit the number of concurrent requests.
72
+ @modal.web_server(
73
+ port=VLLM_PORT, startup_timeout=TIMEOUT
74
+ ) # Expose the VLLM server on the specified port.
75
+ def serve():
76
+ # Create the command to start the VLLM server.
77
+ cmd = [
78
+ "vllm",
79
+ "serve",
80
+ "--uvicorn-log-level=info",
81
+ MODEL_NAME,
82
+ "--served-model-name",
83
+ MODEL_NAME,
84
+ "llm",
85
+ "--max-model-len",
86
+ str(MAX_SEQ_LEN),
87
+ "--max-num-seqs",
88
+ str(MAX_CONCURRENT_SEQS),
89
+ "--host",
90
+ "0.0.0.0",
91
+ "--port",
92
+ str(VLLM_PORT),
93
+ ]
94
+
95
+ # Start the VLLM server using subprocess.
96
+ subprocess.Popen(" ".join(cmd), shell=True)
.source_train_llama.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # * This script was not rigorously tested, so it may not work as expected. We would suggest to
2
+ # * edit the script to follow Orpheus training script.
3
+
4
+ # * Install unsloth, PEFT, Weights & Biases, SNAC, pandas, soundfile and loguru.
5
+ # !pip install unsloth peft==0.15.2 wandb snac pandas soundfile loguru
6
+
7
+ # * Login to Weights & Biases.
8
+ # !wandb login
9
+
10
+ # Import necessary libraries.
11
+ # * unsloth import should always be at the top.
12
+ from unsloth import FastLanguageModel
13
+
14
+ import os
15
+
16
+ from datasets import load_dataset
17
+ from huggingface_hub import login
18
+ from loguru import logger
19
+ from snac import SNAC
20
+ from trl import SFTConfig, SFTTrainer
21
+ import soundfile as sf
22
+ import torch
23
+ import wandb
24
+
25
+
26
+ # Set up constants and configurations.
27
+ HUGGINGFACE_USERNAME = "" # ! Fill.
28
+ BASE_MODEL = "meta-llama/Llama-3.2-3B-Instruct"
29
+ TRAIN_CSV_PATH = "data/data_stage_1.csv"
30
+ VALID_CSV_PATH = "data/data_eval.csv"
31
+ TRAIN_NUM_SAMPLES = None
32
+ EVAL_NUM_SAMPLES = None
33
+ MAX_SEQ_LENGTH = 2048
34
+ N_CODEBOOKS, CODEBOOK_SIZE = 3, 4096
35
+ FIELDS = [
36
+ "user",
37
+ "gender",
38
+ "age",
39
+ "language",
40
+ "utterance",
41
+ "audio",
42
+ ]
43
+ START_OF_SPECIAL_TOKENS = {field: f"<|start_of_{field}|>" for field in FIELDS}
44
+ END_OF_SPECIAL_TOKENS = {field: f"<|end_of_{field}|>" for field in FIELDS}
45
+ SNAC_TOKENS = [
46
+ f"<|snac_{i}_{j}|>" for i in range(N_CODEBOOKS) for j in range(CODEBOOK_SIZE)
47
+ ]
48
+ PER_DEVICE_TRAIN_BATCH_SIZE = 8
49
+ GRADIENT_ACCUMULATION_STEPS = 4
50
+ FULL_FINETUNING = True # Set to False for LoRA training.
51
+ MODEL_NAME = "indic-tts-lora-training"
52
+ WANDB_USERNAME = "" # ! Fill.
53
+ WANDB_PROJECT = "indic-tts-lora-training"
54
+ WANDB_LOG_MODEL = "checkpoint"
55
+ WANDB_RUN_NAME = None
56
+ WANDB_RUN_ID = None
57
+ SEED = 3407
58
+ HUGGINGFACE_TOKEN = "" # ! Fill.
59
+ WANDB_TOKEN = "" # ! Fill.
60
+
61
+ # * Use the following command to start the training: python train_llama.py
62
+
63
+ # Login to Hugging Face.
64
+ login(token=HUGGINGFACE_TOKEN)
65
+
66
+ # Login to Weights & Biases.
67
+ wandb.login(key=WANDB_TOKEN)
68
+
69
+ # Set up environment variables for Weights & Biases.
70
+ os.environ["WANDB_PROJECT"] = WANDB_PROJECT
71
+ os.environ["WANDB_LOG_MODEL"] = WANDB_LOG_MODEL
72
+
73
+ # Load the model and tokenizer.
74
+ model, tokenizer = FastLanguageModel.from_pretrained(
75
+ model_name=BASE_MODEL,
76
+ load_in_4bit=not FULL_FINETUNING,
77
+ max_seq_length=MAX_SEQ_LENGTH,
78
+ full_finetuning=FULL_FINETUNING,
79
+ )
80
+ logger.success(f"Loaded model: {BASE_MODEL}")
81
+
82
+ # Set the end of sequence token.
83
+ EOS_TOKEN = tokenizer.eos_token
84
+
85
+ # Add new special tokens to the tokenizer.
86
+ new_special_tokens = (
87
+ list(START_OF_SPECIAL_TOKENS.values())
88
+ + list(END_OF_SPECIAL_TOKENS.values())
89
+ + SNAC_TOKENS
90
+ )
91
+ tokenizer.add_tokens(new_special_tokens, special_tokens=True)
92
+ model.resize_token_embeddings(len(tokenizer))
93
+ snac_offset = len(tokenizer.get_vocab()) - len(SNAC_TOKENS)
94
+ logger.success("Added new special tokens to the tokenizer.")
95
+
96
+ if not FULL_FINETUNING:
97
+ # Get parameter efficient fine-tuning model.
98
+ model = FastLanguageModel.get_peft_model(
99
+ model,
100
+ r=192,
101
+ target_modules=[
102
+ "q_proj",
103
+ "k_proj",
104
+ "v_proj",
105
+ "o_proj",
106
+ "up_proj",
107
+ "down_proj",
108
+ "gate_proj",
109
+ "lm_head",
110
+ "embed_tokens",
111
+ ],
112
+ lora_alpha=384,
113
+ random_state=SEED,
114
+ )
115
+ logger.success("Initialized parameter efficient fine-tuning model.")
116
+
117
+ # Load training and validation datasets.
118
+ # The dataset should be in CSV format with columns user (str), language (str), utterance (str), and snac_codes (list).
119
+ train_dataset = load_dataset("csv", data_files=TRAIN_CSV_PATH)["train"]
120
+ eval_dataset = load_dataset("csv", data_files=VALID_CSV_PATH)["train"]
121
+
122
+ if TRAIN_NUM_SAMPLES:
123
+ train_dataset = train_dataset.shuffle(seed=SEED).select(
124
+ range(min(TRAIN_NUM_SAMPLES, len(train_dataset)))
125
+ )
126
+
127
+ if EVAL_NUM_SAMPLES:
128
+ eval_dataset = eval_dataset.shuffle(seed=SEED).select(
129
+ range(min(EVAL_NUM_SAMPLES, len(eval_dataset)))
130
+ )
131
+
132
+ logger.success(
133
+ f"Loaded datasets: {len(train_dataset)} training samples, {len(eval_dataset)} evaluation samples."
134
+ )
135
+
136
+
137
+ # Format SNAC audio codes.
138
+ def format_snac_audio_codes(row):
139
+ audio_codes = row["snac_codes"]
140
+ if isinstance(audio_codes, str):
141
+ audio_codes = eval(audio_codes)
142
+ snac_tokens = [[], [], []]
143
+ for i, layer in enumerate(audio_codes):
144
+ for code in layer:
145
+ snac_tokens[i].append(f"<|snac_{i}_{code}|>")
146
+ row["snac_tokens"] = snac_tokens
147
+ return row
148
+
149
+
150
+ train_dataset = train_dataset.map(format_snac_audio_codes)
151
+ eval_dataset = eval_dataset.map(format_snac_audio_codes)
152
+ logger.success("Formatted SNAC audio codes.")
153
+
154
+
155
+ # Flatten SNAC audio codes.
156
+ def flatten_audio_codes(row):
157
+ audio_codes = row["snac_tokens"]
158
+ flattened_codes = []
159
+ for i in range(len(audio_codes[0])):
160
+ flattened_codes.append(audio_codes[0][i])
161
+ flattened_codes.append(audio_codes[1][2 * i])
162
+ flattened_codes.append(audio_codes[2][4 * i])
163
+ flattened_codes.append(audio_codes[2][(4 * i) + 1])
164
+ flattened_codes.append(audio_codes[1][(2 * i) + 1])
165
+ flattened_codes.append(audio_codes[2][(4 * i) + 2])
166
+ flattened_codes.append(audio_codes[2][(4 * i) + 3])
167
+ row["snac_tokens_list"] = flattened_codes
168
+ return row
169
+
170
+
171
+ train_dataset = train_dataset.map(flatten_audio_codes)
172
+ eval_dataset = eval_dataset.map(flatten_audio_codes)
173
+ logger.success("Flattened SNAC audio codes.")
174
+
175
+
176
+ # Remove duplicate frames from the audio codes.
177
+ def remove_duplicate_frames(row):
178
+ vals = row["snac_tokens_list"]
179
+ if len(vals) % 7 != 0:
180
+ raise ValueError("Input list length must be divisible by 7")
181
+ result = vals[:7]
182
+ for i in range(7, len(vals), 7):
183
+ current_first = vals[i]
184
+ previous_first = result[-7]
185
+ if current_first != previous_first:
186
+ result.extend(vals[i : i + 7])
187
+ row["snac_tokens_list"] = result
188
+ return row
189
+
190
+
191
+ train_dataset = train_dataset.map(remove_duplicate_frames)
192
+ eval_dataset = eval_dataset.map(remove_duplicate_frames)
193
+ logger.success("Removed duplicate frames from audio codes.")
194
+
195
+
196
+ # Define a function to format the prompt for each row in the dataset.
197
+ def format_text(row):
198
+ input_parts = ""
199
+ output_part = ""
200
+ for field in FIELDS:
201
+ if field != "audio":
202
+ part = f"{START_OF_SPECIAL_TOKENS[field]} {row[field]} {END_OF_SPECIAL_TOKENS[field]}"
203
+ input_parts += part + " "
204
+ else:
205
+ output_part = f"{START_OF_SPECIAL_TOKENS[field]} {' '.join(row['snac_tokens_list'])} {END_OF_SPECIAL_TOKENS[field]}"
206
+ text = f"{input_parts.strip()} {output_part} {EOS_TOKEN}"
207
+ eval_text = f"{input_parts.strip()} {START_OF_SPECIAL_TOKENS['audio']} "
208
+ row["text"] = text
209
+ row["eval_text"] = eval_text
210
+ return row
211
+
212
+
213
+ train_dataset = train_dataset.map(format_text)
214
+ eval_dataset = eval_dataset.map(format_text)
215
+ logger.success("Formatted text for training and evaluation datasets.")
216
+
217
+ # Set training arguments.
218
+ training_args = SFTConfig(
219
+ num_train_epochs=2,
220
+ per_device_train_batch_size=PER_DEVICE_TRAIN_BATCH_SIZE,
221
+ gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
222
+ optim="adamw_8bit",
223
+ learning_rate=5e-5 if FULL_FINETUNING else 2e-4,
224
+ lr_scheduler_type="cosine",
225
+ warmup_ratio=0.02,
226
+ do_eval=True,
227
+ eval_strategy="steps",
228
+ eval_steps=50,
229
+ logging_strategy="steps",
230
+ logging_steps=1,
231
+ save_strategy="steps",
232
+ save_only_model=True,
233
+ save_steps=1250,
234
+ output_dir="outputs",
235
+ report_to="wandb",
236
+ run_name=WANDB_RUN_NAME,
237
+ seed=SEED,
238
+ )
239
+
240
+ # Initialize the SFTTrainer.
241
+ trainer = SFTTrainer(
242
+ model=model,
243
+ tokenizer=tokenizer,
244
+ train_dataset=train_dataset,
245
+ eval_dataset=eval_dataset,
246
+ dataset_text_field="text",
247
+ max_seq_length=MAX_SEQ_LENGTH,
248
+ dataset_num_proc=2,
249
+ packing=True,
250
+ args=training_args,
251
+ )
252
+
253
+ logger.success("Initialized SFTTrainer with the specified configuration.")
254
+
255
+ # Start the training process.
256
+ logger.info("Starting the training process...")
257
+
258
+ run = wandb.init()
259
+
260
+ if WANDB_RUN_ID:
261
+ logger.info(f"Resuming from Weights & Biases run ID: {WANDB_RUN_ID}")
262
+
263
+ artifact = run.use_artifact(
264
+ f"{WANDB_USERNAME}/{WANDB_PROJECT}/{WANDB_RUN_ID}", type="model"
265
+ )
266
+
267
+ artifact_dir = artifact.download()
268
+
269
+ trainer.train(resume_from_checkpoint=artifact_dir)
270
+ else:
271
+ try:
272
+ logger.info("Attempting to resume training from the last checkpoint...")
273
+
274
+ trainer.train(resume_from_checkpoint=True)
275
+ except Exception as err:
276
+ trainer.train()
277
+
278
+ # Finish the Weights & Biases run.
279
+ wandb.finish()
280
+
281
+ logger.success("Training completed successfully.")
282
+
283
+ # ! Saving and loading model doesn't work.
284
+ # # Save the model and tokenizer.
285
+ # model.save_pretrained_merged(
286
+ # f"{HUGGINGFACE_USERNAME}/{MODEL_NAME}",
287
+ # tokenizer,
288
+ # save_method="merged_16bit",
289
+ # )
290
+ # logger.success("Saved the model and tokenizer locally.")
291
+
292
+ # model.push_to_hub_merged(
293
+ # f"{HUGGINGFACE_USERNAME}/{MODEL_NAME}",
294
+ # tokenizer,
295
+ # save_method="merged_16bit",
296
+ # token=HUGGINGFACE_TOKEN,
297
+ # )
298
+ # logger.success("Pushed the model and tokenizer to the Hugging Face Hub.")
299
+
300
+ # del trainer, model, tokenizer
301
+
302
+ # # Inference with the trained model.
303
+ # # Load the model and tokenizer.
304
+ # model, tokenizer = FastLanguageModel.from_pretrained(
305
+ # model_name=f"{HUGGINGFACE_USERNAME}/{MODEL_NAME}",
306
+ # load_in_4bit=True,
307
+ # max_seq_length=MAX_SEQ_LENGTH,
308
+ # )
309
+
310
+ FastLanguageModel.for_inference(model)
311
+
312
+ logger.success(f"Loaded model for inference: {HUGGINGFACE_USERNAME}/{MODEL_NAME}")
313
+
314
+ # Load the SNAC model for audio decoding.
315
+ snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
316
+ logger.success("Loaded SNAC model for audio decoding.")
317
+
318
+
319
+ # Function to generate audio from a dataset row.
320
+ def generate_audio(
321
+ row, model, tokenizer, temperature=0.4, top_p=0.9, repetition_penalty=1.05
322
+ ):
323
+ prompt = row["eval_text"]
324
+ inputs = tokenizer(prompt, return_tensors="pt")
325
+ max_tokens = MAX_SEQ_LENGTH - inputs.input_ids.shape[1]
326
+ output = model.generate(
327
+ input_ids=inputs.input_ids.to("cuda"),
328
+ attention_mask=inputs.attention_mask.to("cuda"),
329
+ max_new_tokens=max_tokens,
330
+ temperature=temperature,
331
+ top_p=top_p,
332
+ repetition_penalty=repetition_penalty,
333
+ )
334
+ audio_ids = []
335
+ for id in output[0]:
336
+ if id >= snac_offset:
337
+ audio_ids.append(id.item())
338
+ clean_audio_ids = []
339
+ for i in range((len(audio_ids) + 1) // 7):
340
+ for j in range(7):
341
+ clean_audio_ids += [audio_ids[7 * i + j], 220]
342
+ audio_tokens = tokenizer.decode(clean_audio_ids).strip().split(" ")
343
+ codes = [[], [], []]
344
+ for i in range((len(audio_tokens) + 1) // 7):
345
+ frame = []
346
+ for j in range(7):
347
+ _, _, code = audio_tokens[7 * i + j].split("_")
348
+ code = int(code[:-2])
349
+ frame.append(code)
350
+ codes[0].append(frame[0])
351
+ codes[1].append(frame[1])
352
+ codes[2].append(frame[2])
353
+ codes[2].append(frame[3])
354
+ codes[1].append(frame[4])
355
+ codes[2].append(frame[5])
356
+ codes[2].append(frame[6])
357
+ codes = [
358
+ torch.tensor(codes[0]).unsqueeze(0),
359
+ torch.tensor(codes[1]).unsqueeze(0),
360
+ torch.tensor(codes[2]).unsqueeze(0),
361
+ ]
362
+ try:
363
+ audio = snac_model.decode(codes)
364
+ except Exception as e:
365
+ logger.error(f"Error decoding audio: {e}")
366
+ return None
367
+ return audio.detach().squeeze().to("cpu").numpy()
368
+
369
+
370
+ # Generate and save some examples.
371
+ train_sample = generate_audio(train_dataset[0], model, tokenizer)
372
+ if train_sample is None:
373
+ logger.error("Failed to generate audio for training sample.")
374
+ else:
375
+ sf.write("train.wav", train_sample, 24000)
376
+ logger.success("Generated and saved training sample audio.")
377
+
378
+ eval_sample = generate_audio(eval_dataset[0], model, tokenizer)
379
+ if eval_sample is None:
380
+ logger.error("Failed to generate audio for evaluation sample.")
381
+ else:
382
+ sf.write("eval.wav", eval_sample, 24000)
383
+ logger.success("Generated and saved evaluation sample audio.")
.source_train_orpheus.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # * Install unsloth, PEFT, Weights & Biases, SNAC, pandas, soundfile and loguru.
2
+ # !pip install unsloth peft==0.15.2 wandb snac pandas soundfile loguru
3
+
4
+ # Import necessary libraries.
5
+ # * unsloth import should always be at the top.
6
+ from unsloth import FastLanguageModel
7
+
8
+ import os
9
+
10
+ from datasets import load_dataset
11
+ from huggingface_hub import login
12
+ from loguru import logger
13
+ from snac import SNAC
14
+ from trl import SFTConfig, SFTTrainer
15
+ import soundfile as sf
16
+ import torch
17
+ import wandb
18
+
19
+
20
+ # Set up constants and configurations.
21
+ STAGE = 1
22
+ HUGGINGFACE_USERNAME = "" # ! Fill.
23
+
24
+ if STAGE == 1:
25
+ # * You need to request access to the model at https://huggingface.co/canopylabs/3b-hi-pretrain-research_release.
26
+ BASE_MODEL = "canopylabs/3b-hi-pretrain-research_release"
27
+ TARGET_MODULES = [
28
+ "q_proj",
29
+ "k_proj",
30
+ "v_proj",
31
+ "o_proj",
32
+ "up_proj",
33
+ "down_proj",
34
+ "gate_proj",
35
+ "lm_head",
36
+ "embed_tokens",
37
+ ]
38
+ TRAIN_CSV_PATH = "data/data_stage_1.csv"
39
+ VALID_CSV_PATH = "data/data_eval.csv"
40
+ LR = 2e-4
41
+ EPOCHS = 2
42
+ MODEL_NAME = f"snorTTS-indicv0-stage-{STAGE}"
43
+ else:
44
+ BASE_MODEL = f"{HUGGINGFACE_USERNAME}/snorTTS-indicv0-stage-1"
45
+ TARGET_MODULES = [
46
+ "q_proj",
47
+ "k_proj",
48
+ "v_proj",
49
+ "o_proj",
50
+ "up_proj",
51
+ "down_proj",
52
+ "gate_proj",
53
+ ]
54
+ TRAIN_CSV_PATH = "data/data_stage_2.csv"
55
+ VALID_CSV_PATH = "data/data_eval.csv"
56
+ LR = 2e-4
57
+ EPOCHS = 2
58
+ MODEL_NAME = f"snorTTS-indicv0-stage-{STAGE}"
59
+
60
+ TRAIN_NUM_SAMPLES = None
61
+ EVAL_NUM_SAMPLES = 250
62
+ MAX_SEQ_LENGTH = 2048
63
+ PER_DEVICE_TRAIN_BATCH_SIZE = 8
64
+ GRADIENT_ACCUMULATION_STEPS = 4
65
+ WANDB_USERNAME = "" # ! Fill.
66
+ WANDB_PROJECT = MODEL_NAME
67
+ WANDB_LOG_MODEL = "checkpoint"
68
+ WANDB_RUN_NAME = f"{MODEL_NAME}-training"
69
+ WANDB_RUN_ID = None
70
+ SEED = 3407
71
+ HUGGINGFACE_TOKEN = "" # ! Fill.
72
+ WANDB_TOKEN = "" # ! Fill.
73
+
74
+ # * Use the following command to start the training: python train_orpheus.py
75
+
76
+ # Login to Hugging Face.
77
+ login(token=HUGGINGFACE_TOKEN)
78
+
79
+ # Login to Weights & Biases.
80
+ wandb.login(key=WANDB_TOKEN)
81
+
82
+ # Set up environment variables for Weights & Biases.
83
+ os.environ["WANDB_PROJECT"] = WANDB_PROJECT
84
+ os.environ["WANDB_LOG_MODEL"] = WANDB_LOG_MODEL
85
+
86
+ # Load the model and tokenizer.
87
+ model, tokenizer = FastLanguageModel.from_pretrained(
88
+ model_name=BASE_MODEL,
89
+ load_in_4bit=True,
90
+ max_seq_length=MAX_SEQ_LENGTH,
91
+ token=HUGGINGFACE_TOKEN,
92
+ )
93
+ logger.success(f"Loaded model: {BASE_MODEL}")
94
+
95
+ # Load the special tokens for the tokenizer.
96
+ tokeniser_length = 128256
97
+
98
+ start_of_text_id = 128000
99
+ end_of_text_id = 128009
100
+ start_of_speech_id = tokeniser_length + 1
101
+ end_of_speech_id = tokeniser_length + 2
102
+ start_of_human_id = tokeniser_length + 3
103
+ end_of_human_id = tokeniser_length + 4
104
+ start_of_ai_id = tokeniser_length + 5
105
+ end_of_ai_id = tokeniser_length + 6
106
+ pad_token_id = tokeniser_length + 7
107
+ audio_start_id = tokeniser_length + 10
108
+
109
+ start_of_text_token = tokenizer.decode([start_of_text_id])
110
+ end_of_text_token = tokenizer.decode([end_of_text_id])
111
+ start_of_speech_token = tokenizer.decode([start_of_speech_id])
112
+ end_of_speech_token = tokenizer.decode([end_of_speech_id])
113
+ start_of_human_token = tokenizer.decode([start_of_human_id])
114
+ end_of_human_token = tokenizer.decode([end_of_human_id])
115
+ start_of_ai_token = tokenizer.decode([start_of_ai_id])
116
+ end_of_ai_token = tokenizer.decode([end_of_ai_id])
117
+ pad_token = tokenizer.decode([pad_token_id])
118
+ audio_start_token = tokenizer.decode([audio_start_id])
119
+
120
+ logger.success("Load special tokens for the tokenizer.")
121
+
122
+ # Set the padding token and padding side.
123
+ tokenizer.pad_token = pad_token
124
+ tokenizer.padding_side = "left"
125
+ logger.success("Set padding token and padding side for the tokenizer.")
126
+
127
+ # Get parameter efficient fine-tuning model.
128
+ model = FastLanguageModel.get_peft_model(
129
+ model,
130
+ r=192,
131
+ target_modules=TARGET_MODULES,
132
+ lora_alpha=384,
133
+ random_state=SEED,
134
+ )
135
+ logger.success("Initialized parameter efficient fine-tuning model.")
136
+
137
+ # Load training and validation datasets.
138
+ # The dataset should be in CSV format with columns user (str), language (str), utterance (str), and snac_codes (list of lists).
139
+ train_dataset = load_dataset("csv", data_files=TRAIN_CSV_PATH)["train"]
140
+ eval_dataset = load_dataset("csv", data_files=VALID_CSV_PATH)["train"]
141
+
142
+ if TRAIN_NUM_SAMPLES:
143
+ train_dataset = train_dataset.shuffle(seed=SEED).select(
144
+ range(min(TRAIN_NUM_SAMPLES, len(train_dataset)))
145
+ )
146
+
147
+ if EVAL_NUM_SAMPLES:
148
+ eval_dataset = eval_dataset.shuffle(seed=SEED).select(
149
+ range(min(EVAL_NUM_SAMPLES, len(eval_dataset)))
150
+ )
151
+
152
+ logger.success(
153
+ f"Loaded datasets: {len(train_dataset)} training samples, {len(eval_dataset)} evaluation samples."
154
+ )
155
+
156
+
157
+ # Flatten and get SNAC token IDs from the audio codes.
158
+ def flatten_and_get_audio_input_ids(row):
159
+ audio_codes = row["snac_codes"]
160
+ if isinstance(audio_codes, str):
161
+ audio_codes = eval(audio_codes)
162
+ snac_token_ids = []
163
+ for i in range(len(audio_codes[0])):
164
+ snac_token_ids.append(audio_codes[0][i] + 128266)
165
+ snac_token_ids.append(audio_codes[1][2 * i] + 128266 + 4096)
166
+ snac_token_ids.append(audio_codes[2][4 * i] + 128266 + (2 * 4096))
167
+ snac_token_ids.append(audio_codes[2][(4 * i) + 1] + 128266 + (3 * 4096))
168
+ snac_token_ids.append(audio_codes[1][(2 * i) + 1] + 128266 + (4 * 4096))
169
+ snac_token_ids.append(audio_codes[2][(4 * i) + 2] + 128266 + (5 * 4096))
170
+ snac_token_ids.append(audio_codes[2][(4 * i) + 3] + 128266 + (6 * 4096))
171
+ row["snac_token_ids"] = snac_token_ids
172
+ return row
173
+
174
+
175
+ train_dataset = train_dataset.map(flatten_and_get_audio_input_ids)
176
+ eval_dataset = eval_dataset.map(flatten_and_get_audio_input_ids)
177
+ logger.success("Flattened and extracted SNAC token IDs from audio codes.")
178
+
179
+ # Filter out rows with empty or None audio codes.
180
+ train_dataset = train_dataset.filter(
181
+ lambda x: x["snac_token_ids"] is not None and len(x["snac_token_ids"]) > 0
182
+ )
183
+ eval_dataset = eval_dataset.filter(
184
+ lambda x: x["snac_token_ids"] is not None and len(x["snac_token_ids"]) > 0
185
+ )
186
+ logger.success("Filtered datasets to remove rows with empty or None audio codes.")
187
+
188
+
189
+ # Remove duplicate frames from the audio codes.
190
+ def remove_duplicate_frames(row):
191
+ vals = row["snac_token_ids"]
192
+ if len(vals) % 7 != 0:
193
+ raise ValueError("Input list length must be divisible by 7")
194
+ result = vals[:7]
195
+ for i in range(7, len(vals), 7):
196
+ current_first = vals[i]
197
+ previous_first = result[-7]
198
+ if current_first != previous_first:
199
+ result.extend(vals[i : i + 7])
200
+ row["snac_token_ids"] = result
201
+ return row
202
+
203
+
204
+ train_dataset = train_dataset.map(remove_duplicate_frames)
205
+ eval_dataset = eval_dataset.map(remove_duplicate_frames)
206
+ logger.success("Removed duplicate frames from audio codes.")
207
+
208
+
209
+ # Define a function to format the prompt for each row in the dataset.
210
+ def format_text(row):
211
+ text = (
212
+ f"{start_of_human_token}{start_of_text_token}{row['language']}{row['user']}: {row['utterance']}{end_of_text_token}"
213
+ f"{end_of_human_token}{start_of_ai_token}{start_of_speech_token}"
214
+ f"{tokenizer.decode(row['snac_token_ids'])}{end_of_speech_token}{end_of_ai_token}"
215
+ )
216
+ eval_text_user = (
217
+ f"{start_of_human_token}{start_of_text_token}{row['language']}{row['user']}: {row['utterance']}{end_of_text_token}"
218
+ f"{end_of_human_token}{start_of_ai_token}{start_of_speech_token}"
219
+ )
220
+ eval_text_no_user = (
221
+ f"{start_of_human_token}{start_of_text_token}{row['utterance']}{end_of_text_token}"
222
+ f"{end_of_human_token}{start_of_ai_token}{start_of_speech_token}"
223
+ )
224
+ row["text"] = text
225
+ row["eval_text_user"] = eval_text_user
226
+ row["eval_text_no_user"] = eval_text_no_user
227
+ return row
228
+
229
+
230
+ train_dataset = train_dataset.map(format_text)
231
+ eval_dataset = eval_dataset.map(format_text)
232
+ logger.success("Formatted text for training and evaluation datasets.")
233
+
234
+
235
+ # Tokenize the text in the datasets without adding special tokens.
236
+ def tokenize_function(example):
237
+ return tokenizer(
238
+ example["text"],
239
+ add_special_tokens=False,
240
+ truncation=True,
241
+ max_length=MAX_SEQ_LENGTH,
242
+ )
243
+
244
+
245
+ train_dataset = train_dataset.map(tokenize_function)
246
+ eval_dataset = eval_dataset.map(tokenize_function)
247
+ logger.success("Tokenized text in the datasets without adding special tokens.")
248
+
249
+ # Set training arguments.
250
+ training_args = SFTConfig(
251
+ num_train_epochs=EPOCHS,
252
+ per_device_train_batch_size=PER_DEVICE_TRAIN_BATCH_SIZE,
253
+ gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS,
254
+ optim="adamw_8bit",
255
+ learning_rate=LR,
256
+ lr_scheduler_type="cosine",
257
+ warmup_ratio=0.02,
258
+ do_eval=True,
259
+ eval_strategy="steps",
260
+ eval_steps=50,
261
+ logging_strategy="steps",
262
+ logging_steps=1,
263
+ save_strategy="steps",
264
+ save_only_model=True,
265
+ save_steps=1250,
266
+ output_dir="outputs",
267
+ report_to="wandb",
268
+ run_name=WANDB_RUN_NAME,
269
+ seed=SEED,
270
+ )
271
+
272
+ # Initialize the SFTTrainer.
273
+ trainer = SFTTrainer(
274
+ model=model,
275
+ tokenizer=tokenizer,
276
+ train_dataset=train_dataset,
277
+ eval_dataset=eval_dataset,
278
+ max_seq_length=MAX_SEQ_LENGTH,
279
+ dataset_num_proc=2,
280
+ packing=True,
281
+ args=training_args,
282
+ )
283
+
284
+ logger.success("Initialized SFTTrainer with the specified configuration.")
285
+
286
+ # Start the training process.
287
+ logger.info("Starting the training process...")
288
+
289
+ run = wandb.init()
290
+
291
+ if WANDB_RUN_ID:
292
+ logger.info(f"Resuming from Weights & Biases run ID: {WANDB_RUN_ID}")
293
+
294
+ artifact = run.use_artifact(
295
+ f"{WANDB_USERNAME}/{WANDB_PROJECT}/{WANDB_RUN_ID}", type="model"
296
+ )
297
+
298
+ artifact_dir = artifact.download()
299
+
300
+ trainer.train(resume_from_checkpoint=artifact_dir)
301
+ else:
302
+ try:
303
+ logger.info("Attempting to resume training from the last checkpoint...")
304
+
305
+ trainer.train(resume_from_checkpoint=True)
306
+ except Exception as err:
307
+ trainer.train()
308
+
309
+ # Finish the Weights & Biases run.
310
+ wandb.finish()
311
+
312
+ logger.success("Training completed successfully.")
313
+
314
+ # Inference with the trained model.
315
+ FastLanguageModel.for_inference(model)
316
+ logger.success(f"Model {MODEL_NAME} is ready for inference.")
317
+
318
+ # Load the SNAC model for audio decoding.
319
+ snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
320
+ logger.success("Loaded SNAC model for audio decoding.")
321
+
322
+
323
+ # Function to generate audio from a dataset row.
324
+ def generate_audio(
325
+ row,
326
+ model,
327
+ tokenizer,
328
+ user=False,
329
+ temperature=0.4,
330
+ top_p=0.9,
331
+ repetition_penalty=1.05,
332
+ ):
333
+ try:
334
+ if user:
335
+ prompt = row["eval_text_user"]
336
+ else:
337
+ prompt = row["eval_text_no_user"]
338
+ inputs = tokenizer(prompt, add_special_tokens=False, return_tensors="pt")
339
+ max_tokens = MAX_SEQ_LENGTH - inputs.input_ids.shape[1]
340
+ output = model.generate(
341
+ input_ids=inputs.input_ids.to("cuda"),
342
+ attention_mask=inputs.attention_mask.to("cuda"),
343
+ max_new_tokens=max_tokens,
344
+ temperature=temperature,
345
+ top_p=top_p,
346
+ repetition_penalty=repetition_penalty,
347
+ eos_token_id=end_of_speech_id,
348
+ )
349
+ audio_ids = []
350
+ for id in output[0]:
351
+ if id >= audio_start_id:
352
+ audio_ids.append(id.item())
353
+ clean_audio_ids = []
354
+ for i in range((len(audio_ids) + 1) // 7):
355
+ for j in range(7):
356
+ clean_audio_ids += [audio_ids[7 * i + j] - audio_start_id]
357
+ codes = [[], [], []]
358
+ for i in range((len(clean_audio_ids) + 1) // 7):
359
+ codes[0].append(clean_audio_ids[7 * i])
360
+ codes[1].append(clean_audio_ids[7 * i + 1] - 4096)
361
+ codes[2].append(clean_audio_ids[7 * i + 2] - (2 * 4096))
362
+ codes[2].append(clean_audio_ids[7 * i + 3] - (3 * 4096))
363
+ codes[1].append(clean_audio_ids[7 * i + 4] - (4 * 4096))
364
+ codes[2].append(clean_audio_ids[7 * i + 5] - (5 * 4096))
365
+ codes[2].append(clean_audio_ids[7 * i + 6] - (6 * 4096))
366
+ codes = [
367
+ torch.tensor(codes[0]).unsqueeze(0),
368
+ torch.tensor(codes[1]).unsqueeze(0),
369
+ torch.tensor(codes[2]).unsqueeze(0),
370
+ ]
371
+ audio = snac_model.decode(codes)
372
+ return audio.detach().squeeze().to("cpu").numpy()
373
+ except Exception as e:
374
+ logger.error(f"Error decoding audio: {e}")
375
+ return None
376
+
377
+
378
+ # Generate and save some examples.
379
+ train_sample = generate_audio(train_dataset[0], model, tokenizer, True)
380
+ if train_sample is None:
381
+ logger.error("Failed to generate audio for training sample.")
382
+ else:
383
+ sf.write(f"train_{STAGE}.wav", train_sample, 24000)
384
+ logger.success("Generated and saved training sample audio.")
385
+
386
+
387
+ dir_ = f"eval_{STAGE}/"
388
+ os.makedirs(dir_, exist_ok=True)
389
+ for i in range(10):
390
+ eval_sample = generate_audio(eval_dataset[i], model, tokenizer, True)
391
+ if eval_sample is None:
392
+ logger.error(f"Failed to generate audio for evaluation sample {i}.")
393
+ else:
394
+ filename = dir_ + f"eval_{i}.wav"
395
+ sf.write(filename, eval_sample, 24000)
396
+ logger.success(f"Generated and saved evaluation sample audio as {filename}.")
397
+
398
+ # Save the model and tokenizer.
399
+ model.save_pretrained_merged(
400
+ f"{HUGGINGFACE_USERNAME}/{MODEL_NAME}",
401
+ tokenizer,
402
+ save_method="merged_16bit",
403
+ )
404
+ logger.success("Saved the model and tokenizer locally.")
405
+
406
+ model.push_to_hub_merged(
407
+ f"{HUGGINGFACE_USERNAME}/{MODEL_NAME}",
408
+ tokenizer,
409
+ save_method="merged_16bit",
410
+ token=HUGGINGFACE_TOKEN,
411
+ )
412
+ logger.success("Pushed the model and tokenizer to the Hugging Face Hub.")
Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.5.1-cuda12.1-cudnn9-runtime
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+ ENV PYTHONDONTWRITEBYTECODE=1
5
+ ENV PYTHONUNBUFFERED=1
6
+ ENV PIP_DISABLE_PIP_VERSION_CHECK=1
7
+ ENV PIP_DEFAULT_TIMEOUT=180
8
+
9
+ RUN apt-get update && apt-get install -y --no-install-recommends \
10
+ ffmpeg \
11
+ sox \
12
+ libsox-dev \
13
+ libsndfile1 \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ WORKDIR /app
17
+ COPY requirements.txt /app/requirements.txt
18
+ RUN bash -lc 'set -e; \
19
+ for i in 1 2 3 4 5; do \
20
+ echo "pip install attempt $i/5"; \
21
+ pip install --no-cache-dir --retries 25 --timeout 240 --prefer-binary -r /app/requirements.txt && exit 0; \
22
+ echo "pip install failed, retrying in 15s..."; \
23
+ sleep 15; \
24
+ done; \
25
+ echo "pip install failed after 5 attempts"; \
26
+ exit 1'
27
+
28
+ COPY app /app/app
29
+ EXPOSE 8000
30
+
31
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
README.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # snorTTS Hosting Pipeline (RunPod + Load Testing)
2
+
3
+ This folder contains a complete starter pipeline for hosting your TTS model with a simple API and testing parallel load.
4
+
5
+ ## 1) What users get
6
+
7
+ - A single HTTP endpoint: `POST /v1/tts`
8
+ - Inputs: `utterance`, `language`, `user_id`
9
+ - Defaults are server-side tuned.
10
+ - Optional options endpoint for dropdowns: `GET /v1/options`
11
+
12
+ ## 2) API Contract
13
+
14
+ ### POST /v1/tts
15
+
16
+ Request body:
17
+
18
+ ```json
19
+ {
20
+ "utterance": "नमस्ते, आप कैसे हैं?",
21
+ "language": "hindi",
22
+ "user_id": "159"
23
+ }
24
+ ```
25
+
26
+ Response modes:
27
+
28
+ - `response_mode=wav` (default): returns `audio/wav`
29
+ - `response_mode=json`: returns base64 audio and metadata
30
+
31
+ Example:
32
+
33
+ ```bash
34
+ curl -X POST "http://localhost:8000/v1/tts?response_mode=wav" \
35
+ -H "Content-Type: application/json" \
36
+ -d '{"utterance":"नमस्ते, आप कैसे हैं?","language":"hindi","user_id":"159"}' \
37
+ --output out.wav
38
+ ```
39
+
40
+ ### GET /v1/options
41
+
42
+ Returns dropdown-compatible language/speaker map and defaults.
43
+
44
+ ### GET /health
45
+
46
+ Simple liveness check.
47
+
48
+ ### GET /ready
49
+
50
+ True once model and decoder are loaded.
51
+
52
+ ## 3) Local run (before RunPod)
53
+
54
+ 1. Copy env:
55
+
56
+ ```bash
57
+ cp .env.example .env
58
+ ```
59
+
60
+ 2. Set `HF_TOKEN` in `.env`.
61
+
62
+ 3. Build image:
63
+
64
+ ```bash
65
+ docker build -t snortts-api:latest .
66
+ ```
67
+
68
+ 4. Run container:
69
+
70
+ ```bash
71
+ docker run --gpus all --env-file .env -p 8000:8000 snortts-api:latest
72
+ ```
73
+
74
+ Optional (only if you want denoise enabled in production image):
75
+
76
+ ```bash
77
+ # Add these to requirements and rebuild only if needed
78
+ pip install librosa==0.11.0 deepfilternet==0.5.6
79
+ ```
80
+
81
+ 5. Smoke test:
82
+
83
+ ```bash
84
+ curl http://localhost:8000/ready
85
+ ```
86
+
87
+ ## 4) RunPod deployment steps
88
+
89
+ 1. Push image to Docker Hub or GHCR.
90
+ 2. Create RunPod GPU Pod.
91
+ 3. Set container image to your pushed tag.
92
+ 4. Expose port `8000`.
93
+ 5. Add env vars from `.env.example` in RunPod UI.
94
+ 6. Wait for startup, then test `/ready`.
95
+ 7. Test `/v1/tts`.
96
+
97
+ ## 4B) RunPod without Docker (recommended if image build is flaky)
98
+
99
+ You can deploy directly on a standard RunPod PyTorch pod without building an image.
100
+
101
+ 1. Create a GPU Pod from a PyTorch template (CUDA 12.1 compatible).
102
+ 2. Expose port `8000`.
103
+ 3. In Pod terminal, clone or upload this `tts_hosting` folder under `/workspace/tts_hosting`.
104
+ 4. Create `.env` (copy from `.env.example`) and set at least `HF_TOKEN`.
105
+ 5. Run setup once:
106
+
107
+ ```bash
108
+ cd /workspace/tts_hosting
109
+ bash scripts/runpod_setup.sh
110
+ ```
111
+
112
+ Note: setup installs `torch` and `torchaudio` from the CUDA 12.8 index for better compatibility with newer GPUs (including RTX 5090-class pods).
113
+
114
+ 6. Start API server:
115
+
116
+ ```bash
117
+ cd /workspace/tts_hosting
118
+ bash scripts/runpod_start.sh
119
+ ```
120
+
121
+ 7. Check readiness from your local machine:
122
+
123
+ ```bash
124
+ curl http://<runpod-public-ip-or-url>:8000/ready
125
+ ```
126
+
127
+ 8. Test generation:
128
+
129
+ ```bash
130
+ curl -X POST "http://<runpod-public-ip-or-url>:8000/v1/tts?response_mode=wav" \
131
+ -H "Content-Type: application/json" \
132
+ -d '{"utterance":"नमस्ते, आप कैसे हैं?","language":"hindi","user_id":"159"}' \
133
+ --output out.wav
134
+ ```
135
+
136
+ Tip: if the pod restarts often, keep code and venv under `/workspace` so it persists.
137
+
138
+ ## 5) Load testing with Locust
139
+
140
+ From this directory:
141
+
142
+ ```bash
143
+ pip install -r loadtest/requirements.txt
144
+ ```
145
+
146
+ Then run:
147
+
148
+ ```bash
149
+ locust -f loadtest/locustfile.py --host http://<your-runpod-url>
150
+ ```
151
+
152
+ Or headless:
153
+
154
+ ```bash
155
+ locust -f loadtest/locustfile.py --host http://<your-runpod-url> \
156
+ --users 10 --spawn-rate 2 --run-time 5m --headless
157
+ ```
158
+
159
+ ## 6) Suggested test plan
160
+
161
+ - Step 1: users 1, 2, 4, 8, 12
162
+ - Step 2: record p50, p95, p99 latency
163
+ - Step 3: record failure rate and GPU memory usage
164
+ - Step 4: choose safe `MAX_INFLIGHT_REQUESTS`
165
+
166
+ ## 7) Key files
167
+
168
+ - `app/main.py`: FastAPI endpoints
169
+ - `app/runtime.py`: model load and synthesis runtime
170
+ - `app/speaker_map.py`: language -> speaker IDs + default speed
171
+ - `loadtest/locustfile.py`: parallel load test script
172
+ - `Dockerfile`: deployable image for RunPod
173
+
174
+ ## 8) Persistence checklist (before stopping pod)
175
+
176
+ Use this quick checklist before stopping or recreating your pod:
177
+
178
+ 1. Confirm critical artifacts are pushed to Hugging Face:
179
+ - model repos
180
+ - adapter checkpoints
181
+ - sample audio datasets (if needed)
182
+ 2. Confirm runtime config is saved in project files:
183
+ - `.env`
184
+ - `app/speaker_map.py`
185
+ 3. Keep project under `/workspace/tts_hosting` (network volume).
186
+ 4. Do not rely on root filesystem paths outside `/workspace` for anything critical.
187
+
188
+ What usually persists:
189
+ - `/workspace/*`
190
+ - remote artifacts (Hugging Face, Git)
191
+
192
+ What may not persist across image/pod recreation:
193
+ - global apt installs
194
+ - global pip installs
195
+ - temporary files under root filesystem
196
+
197
+ ## 9) Fast recovery setup (if some data is lost)
198
+
199
+ If your environment is partially reset but `/workspace/tts_hosting` still exists:
200
+
201
+ 1. Reinstall runtime deps and venv:
202
+
203
+ ```bash
204
+ cd /workspace/tts_hosting
205
+ bash scripts/runpod_setup.sh
206
+ ```
207
+
208
+ 2. Restore `.env` values (especially `HF_TOKEN` and `MODEL_NAME`).
209
+
210
+ 3. Start service:
211
+
212
+ ```bash
213
+ cd /workspace/tts_hosting
214
+ bash scripts/runpod_start.sh
215
+ ```
216
+
217
+ 4. Verify locally:
218
+
219
+ ```bash
220
+ curl http://127.0.0.1:8000/health
221
+ curl http://127.0.0.1:8000/ready
222
+ curl http://127.0.0.1:8000/v1/options
223
+ ```
224
+
225
+ 5. Verify public URL (if HTTP port 8000 is exposed):
226
+
227
+ ```bash
228
+ curl https://<pod-id>-8000.proxy.runpod.net/health
229
+ ```
230
+
231
+ 6. Smoke-test synthesis:
232
+
233
+ ```bash
234
+ curl -X POST "http://127.0.0.1:8000/v1/tts?response_mode=wav" \
235
+ -H "Content-Type: application/json" \
236
+ -d '{"utterance":"नमस्ते, आप कैसे हैं?","language":"hindi","user_id":"159"}' \
237
+ --output out.wav
238
+ ```
239
+
240
+ ## 10) Optional backup command
241
+
242
+ Create a lightweight backup archive (without virtualenv and cache):
243
+
244
+ ```bash
245
+ cd /workspace
246
+ tar --exclude='.git' --exclude='.venv-tts' --exclude='__pycache__' \
247
+ -czf tts_hosting_backup_$(date +%F_%H%M).tar.gz tts_hosting
248
+ ```
README_EXPLAINER.md ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # README_EXPLAINER
2
+
3
+ Purpose: give strong project context to humans and Copilot agents running on a RunPod pod.
4
+
5
+ ## Project summary
6
+
7
+ This project hosts an Indic multilingual TTS model behind an HTTP API, with a small input surface for end users:
8
+ - utterance
9
+ - language
10
+ - user_id
11
+
12
+ The service applies tuned inference defaults server-side and returns generated audio.
13
+
14
+ ## Source model and pipeline context
15
+
16
+ Base model details:
17
+ - Model lineage is based on `snorbyte/snorTTS-Indic-v0`
18
+ - Hosted checkpoint currently used by this project: `Mevearth2/Quantized-Merged-TTS`
19
+ - Architecture family: LLaMA-style causal LM generating audio tokens
20
+ - Audio decode backend: SNAC (`hubertsiuzdak/snac_24khz`)
21
+
22
+ High-level generation flow:
23
+ 1. Build prompt with language + speaker id + utterance
24
+ 2. Generate SNAC token ids with the LM
25
+ 3. Convert token stream into SNAC codebooks
26
+ 4. Decode to 24 kHz waveform
27
+ 5. Apply optional post-process (speed, denoise)
28
+
29
+ Prompt format used:
30
+ `<custom_token_3><|begin_of_text|>{language}{user_id}: {utterance}<|eot_id|><custom_token_4><custom_token_5><custom_token_1>`
31
+
32
+ ## Data context (important for future finetuning)
33
+
34
+ Training dataset reference:
35
+ - HF dataset: `snorbyte/indic-tts-sample-snac-encoded`
36
+
37
+ Observed splits:
38
+ - `stage_1`
39
+ - `stage_2`
40
+ - `eval`
41
+
42
+ Common columns in all splits:
43
+ - utterance
44
+ - language
45
+ - emotion
46
+ - type
47
+ - act
48
+ - rating
49
+ - gender
50
+ - age
51
+ - environment
52
+ - user
53
+ - snac_codes
54
+ - stage
55
+
56
+ Language set:
57
+ - hindi
58
+ - tamil
59
+ - telugu
60
+ - marathi
61
+ - kannada
62
+ - malayalam
63
+ - punjabi
64
+ - gujarati
65
+ - bengali
66
+
67
+ Note for retraining work:
68
+ - The hosted dataset split names are not `train/valid/test`; scripts should use `stage_1`, `stage_2`, `eval` explicitly.
69
+
70
+ ## Speaker mapping context
71
+
72
+ This project includes language-speaker validation and recommended speed defaults in `app/speaker_map.py`.
73
+
74
+ Current practical mapping by language:
75
+ - hindi: 159, 49, 43
76
+ - tamil: 188, 128, 176
77
+ - bengali: 125
78
+ - malayalam: 189, 124
79
+ - kannada: 142, 138, 131, 59
80
+ - telugu: 69, 133
81
+ - punjabi: 191, 67, 201
82
+ - gujarati: 62, 190
83
+ - marathi: 205, 82, 199, 203
84
+
85
+ ## What has already been implemented
86
+
87
+ Production starter API:
88
+ - `app/main.py`
89
+ - `POST /v1/tts` (inputs: utterance, language, user_id)
90
+ - `GET /v1/options` (dropdown data for UI)
91
+ - `GET /health`
92
+ - `GET /ready`
93
+
94
+ Inference runtime:
95
+ - `app/runtime.py`
96
+ - one-time model load
97
+ - runtime defaults for generation
98
+ - prompt construction
99
+ - token-to-audio decode
100
+ - wav bytes response
101
+
102
+ Schemas:
103
+ - `app/schemas.py`
104
+
105
+ Speaker map and validation:
106
+ - `app/speaker_map.py`
107
+
108
+ Load test starter:
109
+ - `loadtest/locustfile.py`
110
+ - `loadtest/requirements.txt`
111
+
112
+ RunPod no-docker scripts:
113
+ - `scripts/runpod_setup.sh`
114
+ - `scripts/runpod_start.sh`
115
+
116
+ ## Important environment variables
117
+
118
+ Main:
119
+ - `MODEL_NAME` (default `Mevearth2/Quantized-Merged-TTS`)
120
+ - `HF_TOKEN`
121
+
122
+ Service behavior:
123
+ - `MAX_INFLIGHT_REQUESTS`
124
+ - `TTS_TEMPERATURE`
125
+ - `TTS_TOP_P`
126
+ - `TTS_REPETITION_PENALTY`
127
+ - `TTS_MAX_SEQ_LENGTH`
128
+ - `TTS_MAX_WORDS`
129
+ - `TTS_DENOISE`
130
+
131
+ Template file:
132
+ - `.env.example` (no secrets)
133
+ Actual runtime secrets:
134
+ - `.env` (do not commit)
135
+
136
+ ## Why no-docker path exists
137
+
138
+ Docker image builds were unstable due to slow network/timeouts while downloading large Python wheels in some environments.
139
+
140
+ Current recommended fast path:
141
+ 1. Open RunPod PyTorch pod
142
+ 2. Clone `tts_hosting` into `/workspace/tts_hosting`
143
+ 3. Run `scripts/runpod_setup.sh`
144
+ 4. Run `scripts/runpod_start.sh`
145
+
146
+ ## Current known constraints
147
+
148
+ - Generation can be slow for long utterances, so word limits are enforced.
149
+ - Denoise dependencies are intentionally optional to reduce deployment friction.
150
+ - 5090 GPUs require newer PyTorch builds; verify pod torch compatibility first.
151
+
152
+ ## What to do next (execution plan)
153
+
154
+ Phase 1: Stabilize endpoint
155
+ 1. Deploy via no-docker RunPod path
156
+ 2. Verify `/ready` and sample `/v1/tts` calls
157
+ 3. Confirm language-user validation behavior
158
+
159
+ Phase 2: Frontend readiness
160
+ 1. Use `/v1/options` for language and speaker dropdowns
161
+ 2. Keep only 3 user inputs in UI
162
+ 3. Keep generation knobs hidden on backend defaults
163
+
164
+ Phase 3: Load testing
165
+ 1. Run Locust against pod URL
166
+ 2. Sweep concurrency: 1, 2, 4, 8, 12
167
+ 3. Track p50/p95/p99 latency and error rate
168
+ 4. Set stable `MAX_INFLIGHT_REQUESTS`
169
+
170
+ Phase 4: Production hardening
171
+ 1. Add API authentication
172
+ 2. Add structured logs and metrics
173
+ 3. Add queue/backpressure policy and request timeout policy
174
+ 4. Add autoscaling strategy and cost-per-request reporting
175
+
176
+ ## For Copilot agents on pod
177
+
178
+ When helping on this repo, prioritize:
179
+ 1. Reliability over feature creep
180
+ 2. Keeping API input surface simple
181
+ 3. Preserving speaker/language validation
182
+ 4. Avoiding dependency bloat unless requested
183
+ 5. Not committing secrets from `.env`
184
+
185
+ If modifying runtime behavior, always keep:
186
+ - prompt format compatibility
187
+ - speaker mapping checks
188
+ - deterministic server defaults unless explicitly changed
app/__init__.py ADDED
File without changes
app/main.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import base64
3
+ import os
4
+ import uuid
5
+ from contextlib import asynccontextmanager
6
+ from pathlib import Path
7
+
8
+ from fastapi import FastAPI, HTTPException
9
+ from fastapi.responses import FileResponse, Response
10
+ from loguru import logger
11
+
12
+ from app.runtime import TTSRuntime, SAMPLE_RATE
13
+ from app.schemas import HealthResponse, OptionsResponse, ReadyResponse, TTSJSONResponse, TTSRequest
14
+ from app.speaker_map import SUPPORTED_SPEAKERS, validate_language_user
15
+
16
+ MAX_INFLIGHT = int(os.getenv("MAX_INFLIGHT_REQUESTS", "2"))
17
+ runtime = TTSRuntime()
18
+ semaphore = asyncio.Semaphore(MAX_INFLIGHT)
19
+
20
+
21
+ @asynccontextmanager
22
+ async def lifespan(app: FastAPI):
23
+ runtime.load()
24
+ yield
25
+
26
+
27
+ app = FastAPI(title="snorTTS Hosting API", version="1.0.0", lifespan=lifespan)
28
+
29
+
30
+ @app.get("/")
31
+ def root() -> dict:
32
+ return {
33
+ "service": "snorTTS Hosting API",
34
+ "routes": ["/health", "/ready", "/v1/options", "/v1/tts", "/ui"],
35
+ }
36
+
37
+
38
+ @app.get("/ui")
39
+ def ui() -> FileResponse:
40
+ return FileResponse(Path(__file__).with_name("ui.html"))
41
+
42
+
43
+ @app.get("/health", response_model=HealthResponse)
44
+ def health() -> HealthResponse:
45
+ return HealthResponse()
46
+
47
+
48
+ @app.get("/ready", response_model=ReadyResponse)
49
+ def ready() -> ReadyResponse:
50
+ return ReadyResponse(ready=runtime.is_ready)
51
+
52
+
53
+ @app.get("/v1/options", response_model=OptionsResponse)
54
+ def options() -> OptionsResponse:
55
+ defaults = {
56
+ "temperature": float(os.getenv("TTS_TEMPERATURE", "0.4")),
57
+ "top_p": float(os.getenv("TTS_TOP_P", "0.9")),
58
+ "repetition_penalty": float(os.getenv("TTS_REPETITION_PENALTY", "1.05")),
59
+ }
60
+ return OptionsResponse(speakers=SUPPORTED_SPEAKERS, defaults=defaults)
61
+
62
+
63
+ @app.post("/v1/tts", response_class=Response)
64
+ async def tts(req: TTSRequest, response_mode: str = "wav"):
65
+ if not validate_language_user(req.language, req.user_id):
66
+ raise HTTPException(
67
+ status_code=400,
68
+ detail=f"Invalid user_id '{req.user_id}' for language '{req.language}'",
69
+ )
70
+
71
+ async with semaphore:
72
+ try:
73
+ wav_bytes, duration_ms = await asyncio.to_thread(
74
+ runtime.synthesize_wav_bytes,
75
+ req.utterance,
76
+ req.language,
77
+ req.user_id,
78
+ )
79
+ except RuntimeError as exc:
80
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
81
+ except Exception as exc:
82
+ logger.exception("TTS inference failed")
83
+ raise HTTPException(status_code=500, detail=f"Inference failed: {exc}") from exc
84
+
85
+ request_id = str(uuid.uuid4())
86
+ if response_mode == "json":
87
+ payload = TTSJSONResponse(
88
+ request_id=request_id,
89
+ sample_rate=SAMPLE_RATE,
90
+ duration_ms=duration_ms,
91
+ audio_base64=base64.b64encode(wav_bytes).decode("ascii"),
92
+ )
93
+ return payload
94
+
95
+ headers = {
96
+ "X-Request-Id": request_id,
97
+ "X-Duration-Ms": str(duration_ms),
98
+ }
99
+ return Response(content=wav_bytes, media_type="audio/wav", headers=headers)
app/runtime.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import threading
4
+ import time
5
+ from typing import Optional
6
+
7
+ import numpy as np
8
+ import soundfile as sf
9
+ import torch
10
+ import torchaudio
11
+ from huggingface_hub import login as hf_login
12
+ from loguru import logger
13
+ from snac import SNAC
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer
15
+
16
+ from app.speaker_map import recommended_speed
17
+
18
+
19
+ TOKENISER_LENGTH = 128256
20
+ END_OF_SPEECH_ID = TOKENISER_LENGTH + 2
21
+ PAD_TOKEN_ID = TOKENISER_LENGTH + 7
22
+ AUDIO_START_ID = TOKENISER_LENGTH + 10
23
+ SAMPLE_RATE = 24000
24
+
25
+ DEFAULTS = {
26
+ "temperature": float(os.getenv("TTS_TEMPERATURE", "0.4")),
27
+ "top_p": float(os.getenv("TTS_TOP_P", "0.9")),
28
+ "repetition_penalty": float(os.getenv("TTS_REPETITION_PENALTY", "1.05")),
29
+ "max_seq_length": int(os.getenv("TTS_MAX_SEQ_LENGTH", "2048")),
30
+ "max_words": int(os.getenv("TTS_MAX_WORDS", "50")),
31
+ "denoise": os.getenv("TTS_DENOISE", "false").lower() == "true",
32
+ }
33
+
34
+
35
+ class TTSRuntime:
36
+ def __init__(self) -> None:
37
+ self._model = None
38
+ self._tokenizer = None
39
+ self._snac = None
40
+ self._df_model = None
41
+ self._df_state = None
42
+ self._device = "cuda" if torch.cuda.is_available() else "cpu"
43
+ self._loaded = False
44
+ self._lock = threading.Lock()
45
+
46
+ @property
47
+ def is_ready(self) -> bool:
48
+ return self._loaded
49
+
50
+ @staticmethod
51
+ def _resolve_hf_token(cli_token: Optional[str]) -> Optional[str]:
52
+ if cli_token:
53
+ return cli_token
54
+ return (
55
+ os.getenv("HF_TOKEN")
56
+ or os.getenv("HUGGINGFACE_TOKEN")
57
+ or os.getenv("HUGGING_FACE_HUB_TOKEN")
58
+ )
59
+
60
+ def load(self, model_name: Optional[str] = None, hf_token: Optional[str] = None) -> None:
61
+ with self._lock:
62
+ if self._loaded:
63
+ return
64
+
65
+ # Some environments set HF fast transfer globally without
66
+ # installing hf_transfer, which breaks all downloads.
67
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0"
68
+
69
+ model_name = model_name or os.getenv("MODEL_NAME", "Mevearth2/Quantized-Merged-TTS")
70
+ token = self._resolve_hf_token(hf_token)
71
+
72
+ if token:
73
+ try:
74
+ hf_login(token=token, add_to_git_credential=False)
75
+ logger.info("HF auth success")
76
+ except Exception as exc:
77
+ logger.warning(f"HF login warning: {exc}")
78
+
79
+ logger.info(f"Loading tokenizer/model from {model_name}")
80
+ self._tokenizer = AutoTokenizer.from_pretrained(model_name, token=token)
81
+ self._model = AutoModelForCausalLM.from_pretrained(
82
+ model_name,
83
+ token=token,
84
+ torch_dtype=torch.float16 if self._device == "cuda" else torch.float32,
85
+ )
86
+ self._model.to(self._device)
87
+ self._model.eval()
88
+
89
+ pad_token = self._tokenizer.decode([PAD_TOKEN_ID])
90
+ self._tokenizer.pad_token = pad_token
91
+ self._tokenizer.padding_side = "left"
92
+
93
+ try:
94
+ from unsloth import FastLanguageModel
95
+
96
+ FastLanguageModel.for_inference(self._model)
97
+ logger.info("Unsloth inference enabled")
98
+ except Exception:
99
+ logger.info("Unsloth not enabled")
100
+
101
+ logger.info("Loading SNAC decoder")
102
+ self._snac = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
103
+
104
+ if DEFAULTS["denoise"]:
105
+ try:
106
+ from df.enhance import init_df
107
+
108
+ self._df_model, self._df_state, _ = init_df()
109
+ logger.info("DeepFilter initialized")
110
+ except Exception as exc:
111
+ logger.warning(f"DeepFilter unavailable: {exc}")
112
+
113
+ self._loaded = True
114
+
115
+ @staticmethod
116
+ def _build_prompt(utterance: str, language: str, user_id: str) -> str:
117
+ return (
118
+ "<custom_token_3><|begin_of_text|>"
119
+ f"{language}{user_id}: {utterance}"
120
+ "<|eot_id|><custom_token_4><custom_token_5><custom_token_1>"
121
+ )
122
+
123
+ @staticmethod
124
+ def _extract_audio_ids(output_ids: torch.Tensor) -> list[int]:
125
+ raw_audio_ids = [tok.item() for tok in output_ids if tok.item() >= AUDIO_START_ID]
126
+ clean = []
127
+ full_groups = len(raw_audio_ids) // 7
128
+ for i in range(full_groups):
129
+ base = i * 7
130
+ for j in range(7):
131
+ clean.append(raw_audio_ids[base + j] - AUDIO_START_ID)
132
+ return clean
133
+
134
+ @staticmethod
135
+ def _snac_tokens_to_codebooks(clean_audio_ids: list[int]):
136
+ codes = [[], [], []]
137
+ full_groups = len(clean_audio_ids) // 7
138
+
139
+ for i in range(full_groups):
140
+ b = i * 7
141
+ codes[0].append(clean_audio_ids[b + 0])
142
+ codes[1].append(clean_audio_ids[b + 1] - 4096)
143
+ codes[2].append(clean_audio_ids[b + 2] - (2 * 4096))
144
+ codes[2].append(clean_audio_ids[b + 3] - (3 * 4096))
145
+ codes[1].append(clean_audio_ids[b + 4] - (4 * 4096))
146
+ codes[2].append(clean_audio_ids[b + 5] - (5 * 4096))
147
+ codes[2].append(clean_audio_ids[b + 6] - (6 * 4096))
148
+
149
+ if len(codes[0]) == 0 or len(codes[1]) == 0 or len(codes[2]) == 0:
150
+ return None
151
+
152
+ return [
153
+ torch.tensor(codes[0]).unsqueeze(0),
154
+ torch.tensor(codes[1]).unsqueeze(0),
155
+ torch.tensor(codes[2]).unsqueeze(0),
156
+ ]
157
+
158
+ @staticmethod
159
+ def _apply_speed(audio: np.ndarray, speed: float) -> np.ndarray:
160
+ if abs(speed - 1.0) <= 1e-4:
161
+ return audio
162
+ # Prefer Sox tempo when available; some runtime builds omit sox_effects.
163
+ if hasattr(torchaudio, "sox_effects") and hasattr(torchaudio.sox_effects, "apply_effects_tensor"):
164
+ audio_t = torch.from_numpy(audio).unsqueeze(0)
165
+ out_t, _ = torchaudio.sox_effects.apply_effects_tensor(
166
+ audio_t,
167
+ SAMPLE_RATE,
168
+ effects=[["tempo", f"{speed}"]],
169
+ )
170
+ return out_t.squeeze(0).cpu().numpy()
171
+
172
+ # Fallback: lightweight time-stretch via interpolation.
173
+ # This keeps service functional even without Sox bindings.
174
+ in_len = int(audio.shape[0])
175
+ out_len = max(1, int(round(in_len / speed)))
176
+ x_old = np.linspace(0.0, 1.0, num=in_len, dtype=np.float64)
177
+ x_new = np.linspace(0.0, 1.0, num=out_len, dtype=np.float64)
178
+ stretched = np.interp(x_new, x_old, audio.astype(np.float64))
179
+ return stretched.astype(np.float32)
180
+
181
+ def _apply_denoise(self, audio: np.ndarray) -> np.ndarray:
182
+ if self._df_model is None or self._df_state is None:
183
+ return audio
184
+ try:
185
+ import librosa
186
+ from df.enhance import enhance
187
+
188
+ audio_48k = librosa.resample(audio, orig_sr=SAMPLE_RATE, target_sr=48000)
189
+ audio_48k_t = torch.from_numpy(audio_48k).unsqueeze(0)
190
+ denoised = enhance(self._df_model, self._df_state, audio_48k_t)
191
+ denoised_np = denoised.squeeze(0).cpu().numpy()
192
+ return librosa.resample(denoised_np, orig_sr=48000, target_sr=SAMPLE_RATE)
193
+ except Exception as exc:
194
+ logger.warning(f"Denoise failed: {exc}")
195
+ return audio
196
+
197
+ def synthesize_wav_bytes(self, utterance: str, language: str, user_id: str) -> tuple[bytes, int]:
198
+ if not self._loaded:
199
+ raise RuntimeError("Runtime is not loaded")
200
+
201
+ start = time.perf_counter()
202
+ safe_utterance = " ".join(utterance.split()[: DEFAULTS["max_words"]])
203
+ prompt = self._build_prompt(safe_utterance, language, user_id)
204
+ inputs = self._tokenizer(prompt, add_special_tokens=False, return_tensors="pt")
205
+
206
+ input_ids = inputs.input_ids.to(self._device)
207
+ attention_mask = inputs.attention_mask.to(self._device)
208
+ max_new_tokens = max(32, DEFAULTS["max_seq_length"] - input_ids.shape[1])
209
+
210
+ with torch.inference_mode():
211
+ output = self._model.generate(
212
+ input_ids=input_ids,
213
+ attention_mask=attention_mask,
214
+ max_new_tokens=max_new_tokens,
215
+ do_sample=True,
216
+ temperature=DEFAULTS["temperature"],
217
+ top_p=DEFAULTS["top_p"],
218
+ repetition_penalty=DEFAULTS["repetition_penalty"],
219
+ eos_token_id=END_OF_SPEECH_ID,
220
+ )
221
+
222
+ clean_audio_ids = self._extract_audio_ids(output[0])
223
+ if not clean_audio_ids:
224
+ raise RuntimeError("No audio token IDs generated")
225
+
226
+ codes = self._snac_tokens_to_codebooks(clean_audio_ids)
227
+ if codes is None:
228
+ raise RuntimeError("Insufficient audio token IDs for SNAC decode")
229
+
230
+ with torch.inference_mode():
231
+ audio = self._snac.decode(codes)
232
+
233
+ audio_np = audio.detach().squeeze().cpu().numpy().astype(np.float32)
234
+ audio_np = self._apply_speed(audio_np, recommended_speed(language, str(user_id)))
235
+ audio_np = self._apply_denoise(audio_np)
236
+
237
+ wav_buf = io.BytesIO()
238
+ sf.write(wav_buf, audio_np, SAMPLE_RATE, format="WAV")
239
+ wav_bytes = wav_buf.getvalue()
240
+ duration_ms = int((time.perf_counter() - start) * 1000)
241
+ return wav_bytes, duration_ms
app/schemas.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal, Optional
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class TTSRequest(BaseModel):
7
+ utterance: str = Field(min_length=1, max_length=500)
8
+ language: Literal[
9
+ "hindi",
10
+ "tamil",
11
+ "telugu",
12
+ "marathi",
13
+ "kannada",
14
+ "malayalam",
15
+ "punjabi",
16
+ "gujarati",
17
+ "bengali",
18
+ ]
19
+ user_id: str = Field(min_length=1, max_length=8)
20
+
21
+
22
+ class TTSJSONResponse(BaseModel):
23
+ request_id: str
24
+ sample_rate: int
25
+ duration_ms: int
26
+ audio_base64: str
27
+ output_format: Literal["wav_base64"] = "wav_base64"
28
+
29
+
30
+ class HealthResponse(BaseModel):
31
+ status: Literal["ok"] = "ok"
32
+
33
+
34
+ class ReadyResponse(BaseModel):
35
+ ready: bool
36
+
37
+
38
+ class OptionsResponse(BaseModel):
39
+ speakers: dict
40
+ defaults: dict
app/speaker_map.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SUPPORTED_SPEAKERS = {
2
+ "hindi": {
3
+ "159": {"speed": 1.05},
4
+ "49": {"speed": 1.10},
5
+ "43": {"speed": 1.10},
6
+ },
7
+ "tamil": {
8
+ "188": {"speed": 1.10},
9
+ "128": {"speed": 1.15},
10
+ "176": {"speed": 1.10},
11
+ },
12
+ "bengali": {
13
+ "125": {"speed": 1.10},
14
+ },
15
+ "malayalam": {
16
+ "189": {"speed": 1.10},
17
+ "124": {"speed": 1.10},
18
+ },
19
+ "kannada": {
20
+ "142": {"speed": 1.05},
21
+ "138": {"speed": 1.10},
22
+ "131": {"speed": 1.10},
23
+ "59": {"speed": 1.10},
24
+ },
25
+ "telugu": {
26
+ "69": {"speed": 1.10},
27
+ "133": {"speed": 1.10},
28
+ },
29
+ "punjabi": {
30
+ "191": {"speed": 1.08},
31
+ "67": {"speed": 1.06},
32
+ "201": {"speed": 1.10},
33
+ },
34
+ "gujarati": {
35
+ "62": {"speed": 1.15},
36
+ "190": {"speed": 1.25},
37
+ },
38
+ "marathi": {
39
+ "205": {"speed": 1.05},
40
+ "82": {"speed": 1.05},
41
+ "199": {"speed": 1.10},
42
+ "203": {"speed": 1.15},
43
+ },
44
+ }
45
+
46
+
47
+ def validate_language_user(language: str, user_id: str) -> bool:
48
+ if language not in SUPPORTED_SPEAKERS:
49
+ return False
50
+ return str(user_id) in SUPPORTED_SPEAKERS[language]
51
+
52
+
53
+ def recommended_speed(language: str, user_id: str, default: float = 1.05) -> float:
54
+ if not validate_language_user(language, str(user_id)):
55
+ return default
56
+ return float(SUPPORTED_SPEAKERS[language][str(user_id)]["speed"])
app/ui.html ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>snorTTS UI</title>
7
+ <style>
8
+ :root {
9
+ --bg: #0f172a;
10
+ --panel: #111827;
11
+ --text: #e5e7eb;
12
+ --muted: #9ca3af;
13
+ --accent: #22c55e;
14
+ --accent-2: #06b6d4;
15
+ --danger: #ef4444;
16
+ }
17
+ * { box-sizing: border-box; }
18
+ body {
19
+ margin: 0;
20
+ font-family: "IBM Plex Sans", "Segoe UI", sans-serif;
21
+ color: var(--text);
22
+ background: radial-gradient(1000px 500px at 10% 0%, #1f2937, var(--bg));
23
+ min-height: 100vh;
24
+ padding: 24px;
25
+ }
26
+ .card {
27
+ max-width: 920px;
28
+ margin: 0 auto;
29
+ background: linear-gradient(180deg, #0b1220, var(--panel));
30
+ border: 1px solid #1f2937;
31
+ border-radius: 16px;
32
+ padding: 20px;
33
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.35);
34
+ }
35
+ h1 { margin: 0 0 4px; font-size: 1.6rem; }
36
+ p { margin: 0 0 16px; color: var(--muted); }
37
+ .grid {
38
+ display: grid;
39
+ grid-template-columns: 1fr 1fr;
40
+ gap: 12px;
41
+ }
42
+ .full { grid-column: 1 / -1; }
43
+ label { display: block; font-size: 0.9rem; margin-bottom: 6px; color: #cbd5e1; }
44
+ select, textarea, button {
45
+ width: 100%;
46
+ border-radius: 10px;
47
+ border: 1px solid #334155;
48
+ background: #0b1020;
49
+ color: var(--text);
50
+ padding: 10px 12px;
51
+ font-size: 0.95rem;
52
+ }
53
+ textarea { min-height: 110px; resize: vertical; }
54
+ .actions {
55
+ display: flex;
56
+ gap: 10px;
57
+ margin-top: 12px;
58
+ }
59
+ button {
60
+ cursor: pointer;
61
+ font-weight: 600;
62
+ background: linear-gradient(90deg, var(--accent), var(--accent-2));
63
+ color: #001018;
64
+ border: 0;
65
+ }
66
+ button.secondary {
67
+ background: #1f2937;
68
+ color: #cbd5e1;
69
+ border: 1px solid #334155;
70
+ }
71
+ .status { margin-top: 10px; font-size: 0.92rem; color: var(--muted); }
72
+ .error { color: var(--danger); }
73
+ .ok { color: #4ade80; }
74
+ audio { width: 100%; margin-top: 14px; }
75
+ code { color: #7dd3fc; }
76
+ @media (max-width: 760px) {
77
+ .grid { grid-template-columns: 1fr; }
78
+ }
79
+ </style>
80
+ </head>
81
+ <body>
82
+ <div class="card">
83
+ <h1>Synth TTS endpoint</h1>
84
+ <p>Generates audio from <code>/v1/tts</code> using server-side defaults.</p>
85
+
86
+ <div class="grid">
87
+ <div>
88
+ <label for="language">Language</label>
89
+ <select id="language"></select>
90
+ </div>
91
+ <div>
92
+ <label for="user_id">User ID</label>
93
+ <select id="user_id"></select>
94
+ </div>
95
+ <div class="full">
96
+ <label for="utterance">Utterance</label>
97
+ <textarea id="utterance" placeholder="Type text to synthesize...">नमस्ते, आज आप कैसे हैं?</textarea>
98
+ </div>
99
+ </div>
100
+
101
+ <div class="actions">
102
+ <button id="generate">Generate Audio</button>
103
+ <button class="secondary" id="copyCurl">Copy cURL</button>
104
+ </div>
105
+
106
+ <div id="status" class="status"></div>
107
+ <audio id="player" controls></audio>
108
+ </div>
109
+
110
+ <script>
111
+ const state = { speakers: {} };
112
+ const $ = (id) => document.getElementById(id);
113
+
114
+ async function loadOptions() {
115
+ const res = await fetch('/v1/options');
116
+ if (!res.ok) throw new Error('Failed to load options');
117
+ const data = await res.json();
118
+ state.speakers = data.speakers || {};
119
+ const langSel = $('language');
120
+ langSel.innerHTML = '';
121
+ Object.keys(state.speakers).forEach((lang) => {
122
+ const opt = document.createElement('option');
123
+ opt.value = lang;
124
+ opt.textContent = lang;
125
+ langSel.appendChild(opt);
126
+ });
127
+ updateUsers();
128
+ langSel.addEventListener('change', updateUsers);
129
+ }
130
+
131
+ function updateUsers() {
132
+ const lang = $('language').value;
133
+ const users = Object.keys(state.speakers[lang] || {});
134
+ const userSel = $('user_id');
135
+ userSel.innerHTML = '';
136
+ users.forEach((u) => {
137
+ const opt = document.createElement('option');
138
+ opt.value = u;
139
+ opt.textContent = u;
140
+ userSel.appendChild(opt);
141
+ });
142
+ }
143
+
144
+ function setStatus(text, cls = '') {
145
+ const el = $('status');
146
+ el.className = `status ${cls}`.trim();
147
+ el.textContent = text;
148
+ }
149
+
150
+ async function generate() {
151
+ const payload = {
152
+ utterance: $('utterance').value.trim(),
153
+ language: $('language').value,
154
+ user_id: $('user_id').value,
155
+ };
156
+ if (!payload.utterance) {
157
+ setStatus('Utterance is required.', 'error');
158
+ return;
159
+ }
160
+
161
+ setStatus('Generating...');
162
+ $('generate').disabled = true;
163
+
164
+ try {
165
+ const res = await fetch('/v1/tts?response_mode=wav', {
166
+ method: 'POST',
167
+ headers: { 'Content-Type': 'application/json' },
168
+ body: JSON.stringify(payload),
169
+ });
170
+
171
+ if (!res.ok) {
172
+ const txt = await res.text();
173
+ throw new Error(`${res.status} ${txt}`);
174
+ }
175
+
176
+ const blob = await res.blob();
177
+ const url = URL.createObjectURL(blob);
178
+ const player = $('player');
179
+ player.src = url;
180
+ await player.play().catch(() => {});
181
+ setStatus('Audio generated successfully.', 'ok');
182
+ } catch (err) {
183
+ setStatus(`Failed: ${err.message}`, 'error');
184
+ } finally {
185
+ $('generate').disabled = false;
186
+ }
187
+ }
188
+
189
+ function copyCurl() {
190
+ const payload = {
191
+ utterance: $('utterance').value.trim(),
192
+ language: $('language').value,
193
+ user_id: $('user_id').value,
194
+ };
195
+ const cmd = `curl -X POST 'http://127.0.0.1:8000/v1/tts?response_mode=wav' -H 'Content-Type: application/json' -d '${JSON.stringify(payload)}' --output tts.wav`;
196
+ navigator.clipboard.writeText(cmd)
197
+ .then(() => setStatus('cURL copied to clipboard.', 'ok'))
198
+ .catch(() => setStatus('Could not copy cURL.', 'error'));
199
+ }
200
+
201
+ $('generate').addEventListener('click', generate);
202
+ $('copyCurl').addEventListener('click', copyCurl);
203
+ loadOptions().catch((e) => setStatus(e.message, 'error'));
204
+ </script>
205
+ </body>
206
+ </html>
loadtest/locustfile.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import random
4
+
5
+ from locust import HttpUser, between, task
6
+
7
+
8
+ LANGUAGE_SPEAKER = {
9
+ "hindi": ["159", "49", "43"],
10
+ "tamil": ["188", "128", "176"],
11
+ "bengali": ["125"],
12
+ "malayalam": ["189", "124"],
13
+ "kannada": ["142", "138", "131", "59"],
14
+ "telugu": ["69", "133"],
15
+ "punjabi": ["191", "67", "201"],
16
+ "gujarati": ["62", "190"],
17
+ "marathi": ["205", "82", "199", "203"],
18
+ }
19
+
20
+ SAMPLE_TEXT = {
21
+ "hindi": "नमस्ते, आज आप कैसे हैं?",
22
+ "tamil": "வணக்கம், இன்று எப்படி இருக்கீங்க?",
23
+ "bengali": "হ্যালো, আজ তুমি কেমন আছো?",
24
+ "malayalam": "നമസ്കാരം, ഇന്ന് എങ്ങനെയുണ്ട്?",
25
+ "kannada": "ನಮಸ್ಕಾರ, ಇಂದು ಹೇಗಿದ್ದೀರಿ?",
26
+ "telugu": "నమస్కారం, ఈరోజు ఎలా ఉన్నారు?",
27
+ "punjabi": "ਸਤ ਸ੍ਰੀ ਅਕਾਲ, ਅੱਜ ਤੁਸੀਂ ਕਿਵੇਂ ਹੋ?",
28
+ "gujarati": "નમસ્તે, આજે તમે કેમ છો?",
29
+ "marathi": "नमस्कार, आज तुम्ही कसे आहात?",
30
+ }
31
+
32
+
33
+ class TTSUser(HttpUser):
34
+ wait_time = between(0.2, 1.0)
35
+ host = os.getenv("LOCUST_HOST", "http://localhost:8000")
36
+
37
+ @task
38
+ def generate_tts(self):
39
+ language = random.choice(list(LANGUAGE_SPEAKER.keys()))
40
+ payload = {
41
+ "utterance": SAMPLE_TEXT[language],
42
+ "language": language,
43
+ "user_id": random.choice(LANGUAGE_SPEAKER[language]),
44
+ }
45
+ with self.client.post(
46
+ "/v1/tts?response_mode=wav",
47
+ data=json.dumps(payload),
48
+ headers={"Content-Type": "application/json"},
49
+ catch_response=True,
50
+ timeout=180,
51
+ ) as response:
52
+ if response.status_code != 200:
53
+ response.failure(f"status={response.status_code} body={response.text[:200]}")
54
+ elif not response.content:
55
+ response.failure("empty audio response")
56
+ else:
57
+ response.success()
loadtest/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ locust==2.37.2
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.115.12
2
+ uvicorn[standard]==0.34.2
3
+ pydantic==2.11.3
4
+ numpy==1.26.4
5
+ soundfile==0.13.1
6
+ loguru==0.7.3
7
+ huggingface_hub==0.31.1
8
+ transformers==4.51.3
9
+ snac==1.2.1
scripts/runpod_setup.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ ROOT_DIR="${ROOT_DIR:-/workspace/tts_hosting}"
5
+ VENV_PATH="${VENV_PATH:-/workspace/.venv-tts}"
6
+ PYTHON_BIN="${PYTHON_BIN:-python3}"
7
+ TORCH_INDEX_URL="${TORCH_INDEX_URL:-https://download.pytorch.org/whl/cu128}"
8
+
9
+ if [[ ! -d "$ROOT_DIR" ]]; then
10
+ echo "ERROR: ROOT_DIR '$ROOT_DIR' does not exist."
11
+ echo "Clone/copy tts_hosting there first."
12
+ exit 1
13
+ fi
14
+
15
+ retry_pip_install() {
16
+ local install_target="$1"
17
+ for i in 1 2 3 4 5; do
18
+ echo "pip install attempt ${i}/5"
19
+ if pip install --retries 20 --timeout 240 --prefer-binary $install_target; then
20
+ return 0
21
+ fi
22
+ echo "pip install failed, retrying in 20s..."
23
+ sleep 20
24
+ done
25
+ echo "pip install failed after 5 attempts"
26
+ return 1
27
+ }
28
+
29
+ sudo apt-get update
30
+ sudo apt-get install -y --no-install-recommends ffmpeg sox libsox-dev libsndfile1
31
+
32
+ $PYTHON_BIN -m venv "$VENV_PATH"
33
+ source "$VENV_PATH/bin/activate"
34
+
35
+ pip install --upgrade pip setuptools wheel
36
+
37
+ # Explicit torch install for modern RunPod GPUs (including RTX 5090).
38
+ retry_pip_install "--index-url $TORCH_INDEX_URL torch torchaudio"
39
+
40
+ # Install the remaining app dependencies.
41
+ retry_pip_install "-r $ROOT_DIR/requirements.txt"
42
+
43
+ echo "Setup complete."
44
+ echo "Activate with: source $VENV_PATH/bin/activate"
scripts/runpod_start.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ ROOT_DIR="${ROOT_DIR:-/workspace/tts_hosting}"
5
+ VENV_PATH="${VENV_PATH:-/workspace/.venv-tts}"
6
+ PORT="${PORT:-8000}"
7
+
8
+ if [[ ! -d "$ROOT_DIR" ]]; then
9
+ echo "ERROR: ROOT_DIR '$ROOT_DIR' does not exist."
10
+ exit 1
11
+ fi
12
+
13
+ if [[ ! -f "$VENV_PATH/bin/activate" ]]; then
14
+ echo "ERROR: virtual env not found at '$VENV_PATH'."
15
+ echo "Run scripts/runpod_setup.sh first."
16
+ exit 1
17
+ fi
18
+
19
+ cd "$ROOT_DIR"
20
+ source "$VENV_PATH/bin/activate"
21
+
22
+ if [[ -f ".env" ]]; then
23
+ set -a
24
+ source .env
25
+ set +a
26
+ fi
27
+
28
+ # Some pod images set this globally but do not ship hf_transfer,
29
+ # which breaks model downloads at startup.
30
+ export HF_HUB_ENABLE_HF_TRANSFER="0"
31
+
32
+ exec uvicorn app.main:app --host 0.0.0.0 --port "$PORT"