"""
Hugging Face Model Hub Exporter.
Packages 10M TTS weights, configs, and generates an official Model Card README.md,
then uploads everything cleanly to Hugging Face Model Hub.
"""
import os
import json
import tempfile
import argparse
from huggingface_hub import HfApi, login, create_repo
from config import TTS10MConfig
APACHE_2_0_LICENSE = """Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
def generate_model_card(repo_id: str) -> str:
return f"""---
language:
- hi
license: apache-2.0
license_link: LICENSE
pipeline_tag: text-to-speech
datasets:
- ViuAI/ViuAI_Hindi_TTS_50h
tags:
- murli
- murli-v1
- text-to-speech
- tts
- hindi
- flow-matching
- ot-cfm
- vocos
- edge-ai
---
# Murli V1.0
**Murli V1.0** is an ultra-lightweight Hindi text-to-speech (TTS) model trained with Optimal Transport Conditional Flow Matching (OT-CFM), built for clean, low-latency 24 kHz Hindi narration and long-form content.
- **8.17M trainable acoustic parameters (21.70M with Vocos)**: RoPE Text Transformer, MAS Duration Predictor, and ConvNeXt-V2 1D OT-CFM vector field paired with a pretrained 24 kHz Vocos iSTFT vocoder
- **Single-speaker studio Hindi**: Trained for 500 epochs on 49.28 hours (`24,019` clips) of `syspin_male_01` ([ViuAI/ViuAI_Hindi_TTS_50h](https://huggingface.co/datasets/ViuAI/ViuAI_Hindi_TTS_50h))
- **Fast ODE flow sampling**: 48-step Euler ODE solver with Sway Sampling (`-1.0`) and Classifier-Free Guidance (`1.5`)
- **Long-form text**: Clause-level automatic chunking, contextual Anusvara normalization, `min_frames=2` duration guard, and zero-phase high-frequency de-buzzing
## Quickstart
Install the inference runtime from the [Murli / TTS_10M code repository](https://huggingface.co/ViuAI/TTS_10M) and download the model weights from `{repo_id}`:
```bash
git lfs install
git clone https://huggingface.co/ViuAI/TTS_10M && cd TTS_10M
pip install -r requirements.txt
```
Generate speech from the command line or launch the Gradio interface:
```bash
python -c "from huggingface_hub import hf_hub_download; print(hf_hub_download('{repo_id}', 'model.safetensors'))"
python infer.py --checkpoint model.safetensors --text "नमस्ते! यह मुरली हिंदी टेक्स्ट टू स्पीच मॉडल बोल रहा है।"
```
```bash
python app.py
```
## Example Usage
All samples below were synthesized unmodified from `{repo_id}` using the default sampling configuration (`steps=48`, `cfg_scale=1.5`, `temperature=0.667`, `speed=0.92`, `sway=-1.0`).
### Greeting
Text: `नमस्ते! यह मुरली हिंदी टेक्स्ट टू स्पीच मॉडल बोल रहा है।`
### Storytelling Narration
Text: `बहुत समय पहले एक शांत गांव में एक नेक किसान रहता था, जो सुबह सूरज उगने से पहले खेतों में काम करने निकल जाता था।`
### Conversational Hindi
Text: `आज मौसम बहुत सुहावना है, और शाम को सभी दोस्त मिलकर नदी के किनारे टहलने जाने वाले हैं।`
### Python API
Load `model.safetensors` directly from Hugging Face Hub and run long-form synthesis with the `TTS_10M` runtime:
```python
import torch
from huggingface_hub import hf_hub_download
from config import TTS10MConfig
from models.tts_engine import TTS10MEngine
from data.text_cleaner import TextTokenizer
from utils.checkpoint import load_checkpoint
from utils.long_form import synthesize_long_text
from utils.audio_sanity import save_audio
cfg = TTS10MConfig()
device = "cuda" if torch.cuda.is_available() else "cpu"
weights_path = hf_hub_download("{repo_id}", "model.safetensors")
model = load_checkpoint(
TTS10MEngine(cfg.model, cfg.training).to(device),
weights_path,
device=device,
)
model.eval()
text = "नमस्ते! यह मुरली हिंदी टेक्स्ट टू स्पीच मॉडल बोल रहा है।"
wav = synthesize_long_text(
model,
TextTokenizer(),
text,
torch.device(device),
sample_rate=cfg.audio.sample_rate,
num_steps=48,
speed=0.92,
cfg_scale=1.5,
temperature=0.667,
)
save_audio("murli_output.wav", torch.from_numpy(wav), cfg.audio.sample_rate)
```
## Architecture & Evaluation
Murli V1.0 decouples acoustic synthesis into an alignment/duration front-end and an 8-block ConvNeXt-V2 OT-CFM vector field operating in 100-bin HTK mel-spectrogram space (`24,000 Hz`, hop size `256`).
| Component | Architecture | Parameters |
| :--- | :--- | ---: |
| Text Encoder | RoPE Transformer (4 layers, 4 heads, 256 dim) | 2,765,312 |
| Duration Predictor | 1D ConvNeXt + FP32 Monotonic Alignment Search | 395,009 |
| Mel Prior Projection | Linear Mel Prior Head | 25,700 |
| CFM Vector Field | Mask-aware ConvNeXt-V2 1D (8 blocks, 7x7 DW) | 4,984,164 |
| Vocoder | Pretrained Vocos 24 kHz iSTFT (`charactr/vocos-mel-24khz`) | 13,531,650 |
| **Total System** | **End-to-End** | **21,701,835** |
*Table 1. Parameter breakdown of Murli V1.0 (`8.17M` trainable acoustic model + `13.53M` Vocos vocoder).*
| Property / Evaluation Metric | Murli V1.0 Value |
| :--- | ---: |
| Training Dataset (`syspin_male_01`) | 49.28 hours (24,019 clips) |
| Total Training Epochs | 500 epochs (71,368 warm-started steps) |
| Audio Output Format | 24,000 Hz Mono PCM (`100` HTK mel bins) |
| Default Sampling Config | 48 ODE steps, CFG `1.5`, Temp `0.667`, Speed `0.92` |
| Long-Form Story Evaluation (~900 words, 6m 30s) | ~1.0% WER (~99% word intelligibility) |
*Table 2. Training specification and long-form Hindi story evaluation summary.*
## Limitations
- **Devanagari character vocabulary**: Murli V1.0 operates on raw Devanagari characters (`vocab_size=512`) without an external G2P phonemizer, so occasional pronunciation slips (~1% WER) can occur on rare proper nouns or retroflex aspirates.
- **Single read-speech speaker**: Trained exclusively on `syspin_male_01` studio read speech; calm narrative tone is best suited for audiobooks, narration, and assistant voices rather than multi-speaker dialogue.
- **English loanwords**: Pure Devanagari input yields the highest accuracy; mixed Latin script words should be transliterated to Devanagari before synthesis.
## Links
- [Murli V1.0 Model Weights](https://huggingface.co/{repo_id})
- [TTS_10M Source Code & Training Repo](https://huggingface.co/ViuAI/TTS_10M)
- [ViuAI Hindi TTS 50h Dataset](https://huggingface.co/datasets/ViuAI/ViuAI_Hindi_TTS_50h)
## License
This model is licensed under the [Apache License 2.0](https://huggingface.co/{repo_id}/blob/main/LICENSE). Please refer to the `LICENSE` file for full terms.
"""
def export_and_push(
checkpoint_path: str,
repo_id: str,
token: str = None,
private: bool = False,
):
if not os.path.exists(checkpoint_path):
raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}. Cannot export empty weights.")
if os.path.getsize(checkpoint_path) == 0:
raise ValueError(f"Checkpoint file is 0 bytes: {checkpoint_path}.")
if token:
login(token=token)
with tempfile.TemporaryDirectory() as staging_dir:
# 1. Copy model weights
target_weights = os.path.join(staging_dir, "model.safetensors")
from models.tts_engine import TTS10MEngine
from utils.checkpoint import load_checkpoint
from safetensors.torch import save_file
model = load_checkpoint(TTS10MEngine(), checkpoint_path)
save_file(model.state_dict(), target_weights)
print(f"Copied {checkpoint_path} -> {target_weights}")
# 2. Write Config
cfg = TTS10MConfig()
config_dict = {
"audio": cfg.audio.__dict__,
"model": cfg.model.__dict__,
}
with open(os.path.join(staging_dir, "config.json"), "w", encoding="utf-8") as f:
json.dump(config_dict, f, indent=2)
# 3. Write Model Card
card_content = generate_model_card(repo_id)
with open(os.path.join(staging_dir, "README.md"), "w", encoding="utf-8") as f:
f.write(card_content)
# 4. Write Apache-2.0 LICENSE (weights-only release repo; source code stays in ViuAI/TTS_10M)
with open(os.path.join(staging_dir, "LICENSE"), "w", encoding="utf-8") as f:
f.write(APACHE_2_0_LICENSE)
# 5. Push weights + config + card + license to Hugging Face Model Hub
api = HfApi()
print(f"Creating / verifying repo: {repo_id}...")
create_repo(repo_id, repo_type="model", private=private, exist_ok=True)
print(f"Uploading weights & model card to Hugging Face Model Hub: {repo_id}...")
api.upload_folder(
folder_path=staging_dir,
repo_id=repo_id,
repo_type="model",
delete_patterns=[
"*.py",
"models/*",
"models/**",
"data/*",
"data/**",
"utils/*",
"utils/**",
"LESSONS_LEARNED_V1.md",
"requirements.txt",
],
commit_message="Publish Murli V1.0 weights, config, license, and model card",
)
print(f"\n🎉 Successfully published model to: https://huggingface.co/{repo_id}\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Export and push 10M TTS model to Hugging Face Hub")
parser.add_argument("--checkpoint", type=str, default="checkpoints/model.safetensors", help="Path to .safetensors")
parser.add_argument("--repo_id", type=str, default="ViuAI/Murli-V1.0", help="HF model repo")
parser.add_argument("--token", type=str, default=None, help="HF write token (optional if logged in)")
parser.add_argument("--private", action="store_true", help="Make model private")
args = parser.parse_args()
token = args.token or os.environ.get("HF_TOKEN")
if not token:
try:
from kaggle_secrets import UserSecretsClient
token = UserSecretsClient().get_secret("HF_TOKEN")
print("[+] Loaded HF_TOKEN from Kaggle Secrets.")
except Exception:
pass
export_and_push(
checkpoint_path=args.checkpoint,
repo_id=args.repo_id,
token=token,
private=args.private,
)