qwen3-tts
by arifsoul
README.md
# Qwen3-TTS Production Runtime (`tts-runtime`)
Production-ready **Qwen3-TTS** API server yang didesain khusus agar mudah dijalankan di **Google Colab** (untuk langsung menghasilkan **Public HTTPS `API_URL`** + **`API_KEY`**) maupun di server GPU / Docker production.
---
## Arsitektur Multi-Model
| Alias API | Hugging Face Repo | Fungsi Utama | Catatan Teknis |
|---|---|---|---|
| `qwen3-indonesian` | [`alkhrzmy/qwen3-tts-0.6b-indonesian`](https://huggingface.co/alkhrzmy/qwen3-tts-0.6b-indonesian) | TTS **Bahasa Indonesia** natural (`speaker="indonesian_speaker"`) | Fine-tune dari `0.6B-Base`, otomatis dipanggil saat `language="id"` / `"Indonesian"` |
| `qwen3-custom-voice` | [`Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice`](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice) | TTS Multilingual (10 bahasa, 9 speaker premium) + **Style/Emotion Instruct** | Mendukung `Vivian`, `Serena`, `Uncle_Fu`, `Dylan`, `Eric`, `Ryan`, `Aiden`, `Ono_Anna`, `Sohee` |
| `qwen3-voice-clone` | [`Qwen/Qwen3-TTS-12Hz-1.7B-Base`](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-Base) *(atau `0.6B-Base`)* | **Voice Cloning** (Zero-Shot 3 detik & Persistent Voice Profiles) | Kedua model `CustomVoice` tidak menyimpan `speaker_encoder`; `Qwen3-TTS-12Hz-*-Base` memiliki `speaker_encoder` resmi untuk `create_voice_clone_prompt` & `generate_voice_clone` |
### Fitur Production-Ready
- **Public HTTPS API URL & API Key Generator**: `scripts/colab_launch.py` otomatis membuat API Key (`qtts_live_...` & `qtts_admin_...`), menjalankan Uvicorn, membuka tunnel HTTPS (`cloudflared` gratis tanpa akun, `cloudflared-named` custom domain, atau `ngrok`), dan menyimpan info koneksi ke `data/secrets/runtime_connection.json`.
- **Keamanan API Key**: Hash SHA-256 + perbandingan constant-time (`Authorization: Bearer <KEY>` dan `X-API-Key: <KEY>`), pemisahan role `client` & `admin`, serta endpoint admin untuk membuat/mencabut API Key (`/v1/admin/keys`).
- **Voice Cloning Lengkap**:
- **One-Shot Cloning**: kirim file audio via multipart (`POST /v1/tts/voice-clone/upload`) atau JSON base64/URL (`POST /v1/tts/voice-clone`).
- **Persistent Voice Profiles**: simpan profil suara sekali (`POST /v1/voices`), prompt embedding otomatis di-cache di memori agar inferensi berikutnya jauh lebih cepat, lalu gunakan `voice_id` di `/v1/tts/voice-clone`, `/v1/tts/synthesize`, maupun `/v1/audio/speech`.
- Otomatis memilih **ICL Mode** (kualitas kloning terbaik) bila `ref_text` diisi, atau **x-vector only mode** bila tanpa transkrip.
- **OpenAI SDK Drop-in Compatible**: Endpoint `POST /v1/audio/speech` kompatibel langsung dengan library resmi `openai`.
- **VRAM-Aware LRU Model Manager**: Deteksi otomatis GPU (`A100`/`L4` -> `bfloat16` + FlashAttention 2/SDPA, `T4` -> `float16` + SDPA, `CPU` -> `float32`), antrean inferensi aman (`max_queue_size`, `inference_timeout_seconds`), dan LRU eviction otomatis agar tidak OOM di Colab T4 15GB.
- **Long-Text Auto Chunker & Multi-Format Audio**: Teks panjang otomatis dipecah per kalimat dan disambung dengan jeda natural; mendukung output `wav`, `mp3`, `ogg`/`opus`, `flac`, dan `pcm`.
---
## Cara Cepat Menjalankan di Google Colab (Dapat `API_URL` + `API_KEY`)
### Opsi A — Menggunakan Notebook `colab_launcher.ipynb`
1. Buka `colab_launcher.ipynb` di Google Colab.
2. Pilih **Runtime -> Change runtime type -> GPU (T4 / L4 / A100)**.
3. Jalankan semua cell (**Runtime -> Run all**).
4. Salin **`PUBLIC API URL`** dan **`API KEY`** yang tampil di output cell ke-4/5.
### Opsi B — Via Terminal Colab
```bash
cd /content/drive/MyDrive/tts-runtime
bash scripts/setup_colab.sh
python3 scripts/colab_launch.py --tunnel cloudflared
```
> **Tip VRAM T4 (15GB)**: Default `TTS_PRELOAD_MODELS=indonesian,custom_voice` (~6GB VRAM). Model `voice_clone` akan dimuat otomatis saat endpoint cloning dipanggil. Jika ingin lebih hemat VRAM, set `TTS_VOICE_CLONE_MODEL_ID=Qwen/Qwen3-TTS-12Hz-0.6B-Base` di `.env`.
---
## Contoh Pemakaian API
### 1. TTS Bahasa Indonesia (`alkhrzmy/qwen3-tts-0.6b-indonesian`)
```bash
curl -X POST "${API_URL}/v1/tts/custom-voice" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"text": "Halo, selamat pagi! Ini adalah layanan suara Bahasa Indonesia berbasis Qwen3 TTS.",
"language": "id",
"response_format": "wav"
}' \
--output indonesia.wav
```
### 2. TTS Multilingual CustomVoice + Style Instruct (`Qwen3-TTS-12Hz-1.7B-CustomVoice`)
```bash
curl -X POST "${API_URL}/v1/tts/custom-voice" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"text": "Welcome! Everything is running smoothly in production.",
"speaker": "Ryan",
"language": "English",
"instruct": "Speak warmly with upbeat energy.",
"response_format": "mp3"
}' \
--output custom_en.mp3
```
### 3. Voice Cloning — One-Shot (Upload Audio Referensi 3–15 detik)
```bash
curl -X POST "${API_URL}/v1/tts/voice-clone/upload" \
-H "Authorization: Bearer ${API_KEY}" \
-F "text=Halo semua, ini adalah contoh suara hasil kloning." \
-F "language=Auto" \
-F "ref_text=Transkrip persis dari audio referensi di sini." \
-F "ref_audio=@suara_referensi.wav" \
-F "response_format=wav" \
--output cloned_oneshot.wav
```
### 4. Voice Cloning — Simpan Profil Suara & Pakai Berulang (Cepat)
```bash
# Langkah 1: Daftarkan suara sekali
VOICE_ID=$(curl -s -X POST "${API_URL}/v1/voices" \
-H "Authorization: Bearer ${API_KEY}" \
-F "name=Suara Brand" \
-F "language=Auto" \
-F "ref_text=Transkrip audio referensi di sini." \
-F "ref_audio=@suara_referensi.wav" | python3 -c "import sys,json; print(json.load(sys.stdin)['voice_id'])")
# Langkah 2: Sintesis berkali-kali pakai voice_id (prompt sudah di-cache!)
curl -X POST "${API_URL}/v1/tts/voice-clone" \
-H "Authorization: Bearer ${API_KEY}" \
-H "Content-Type: application/json" \
-d "{
\"text\": \"Selamat datang di aplikasi kami, suara ini diambil dari profil kloning tersimpan.\",
\"voice_id\": \"${VOICE_ID}\",
\"language\": \"Auto\",
\"response_format\": \"mp3\"
}" \
--output cloned_profile.mp3
```
### 5. Kompatibel dengan OpenAI Python SDK
```python
from openai import OpenAI
client = OpenAI(base_url=f"{API_URL}/v1", api_key=API_KEY)
# Bahasa Indonesia
with client.audio.speech.with_streaming_response.create(
model="qwen3-indonesian",
voice="indonesian_speaker",
input="Halo dunia, ini menggunakan OpenAI Python SDK!",
response_format="mp3",
) as resp:
resp.stream_to_file("indo_openai.mp3")
# Atau langsung pakai voice_id hasil cloning!
with client.audio.speech.with_streaming_response.create(
model="tts-1",
voice=VOICE_ID,
input="Suara ini dihasilkan memakai voice clone profile.",
response_format="mp3",
) as resp:
resp.stream_to_file("clone_openai.mp3")
```
---
## Permanent `BASE_URL` (Agar URL Tidak Berubah Saat Colab Restart)
Default `--tunnel cloudflared` menghasilkan URL acak `*.trycloudflare.com` (gratis tanpa akun). Untuk **URL permanen** di produksi, pilih salah satu:
### Opsi 1 — Cloudflare Named Tunnel (Custom Domain Sendiri, Gratis)
1. Masuk ke [Cloudflare Zero Trust Dashboard](https://one.dash.cloudflare.com/) -> **Networks -> Tunnels -> Create a tunnel -> Cloudflared**.
2. Salin token tunnel (`CLOUDFLARED_TOKEN`).
3. Pada tab **Public Hostname**, tambahkan subdomain (mis. `tts.domainanda.com`) mengarah ke **Service**: `HTTP` -> `127.0.0.1:8000`.
4. Isi di `.env` (atau di cell #3 `colab_launcher.ipynb`):
```env
TTS_TUNNEL_PROVIDER=cloudflared-named
CLOUDFLARED_TOKEN=eyJhIjoi...
TTS_PUBLIC_URL=https://tts.domainanda.com
```
5. Jalankan: `python3 scripts/colab_launch.py --tunnel cloudflared-named`
### Opsi 2 — ngrok Static Domain (Gratis 1 Domain Tetap)
1. Ambil `NGROK_AUTHTOKEN` dan klaim 1 domain statis gratis di [ngrok Dashboard -> Domains](https://dashboard.ngrok.com/domains).
2. Isi di `.env` (atau cell #3 `colab_launcher.ipynb`):
```env
TTS_TUNNEL_PROVIDER=ngrok
NGROK_AUTHTOKEN=2abc...
NGROK_DOMAIN=your-static-name.ngrok-free.app
```
3. Jalankan: `python3 scripts/colab_launch.py --tunnel ngrok`
---
## Integrasi MCP Server (Untuk AI Agent: Antigravity / Claude Desktop / Cursor)
`mcp_server/server.py` adalah **MCP wrapper tipis** (hanya butuh `mcp` + `httpx`, tanpa PyTorch/GPU di laptop Anda) yang memanggil server Qwen3-TTS Anda lewat `TTS_BASE_URL` dan `TTS_API_KEY`.
1. Di mesin lokal (laptop/desktop):
```bash
pip install -r mcp_server/requirements.txt
```
2. Salin konfigurasi siap pakai dari `data/secrets/mcp_client_config.json` (otomatis dibuat oleh `colab_launch.py`) atau pakai template `mcp_server/mcp_config.example.json`:
```json
{
"mcpServers": {
"qwen3-tts": {
"command": "python",
"args": ["/path/to/tts-runtime/mcp_server/server.py"],
"env": {
"TTS_BASE_URL": "https://tts.domainanda.com",
"TTS_API_KEY": "qtts_live_..."
}
}
}
}
```
3. Tools MCP yang otomatis tersedia untuk AI Agent:
- `tts_health` — cek status GPU & model yang ter-load
- `tts_list_models_and_speakers` — daftar model, speaker bawaan, & profil voice clone
- `tts_indonesian` — sintesis Bahasa Indonesia (`alkhrzmy/qwen3-tts-0.6b-indonesian`)
- `tts_custom_voice` — sintesis multilingual + style `instruct` (`Qwen3-TTS-12Hz-1.7B-CustomVoice`)
- `tts_register_voice` — daftarkan audio referensi 3–15 detik menjadi `voice_id` reusable
- `tts_voice_clone` — kloning suara (via `voice_id` maupun one-shot file audio lokal)
- `tts_delete_voice` — hapus profil suara
---
## Manajemen API Key
```bash
# Lihat / pastikan bootstrap key aktif
python3 scripts/manage_keys.py bootstrap
# Buat API Key baru untuk aplikasi tertentu dengan rate limit khusus
python3 scripts/manage_keys.py create --name "backend-whatsapp-bot" --role client --rpm 120
# Daftar semua key (metadata saja)
python3 scripts/manage_keys.py list
# Cabut key yang sudah tidak dipakai
python3 scripts/manage_keys.py revoke key_xxxxxxxxxxxx
```
---
## Testing & Deployment Docker
```bash
# Jalankan unit & API integration test (pakai mock backend, cepat < 3 detik)
pytest -v tests/test_api.py
# Jalankan smoke test ke server yang sedang berjalan
python3 scripts/smoke_test.py
# Build & run di GPU server produksi (Docker)
docker build -t qwen3-tts-runtime .
docker run --gpus all -p 8000:8000 --env-file .env -v $(pwd)/data:/app/data qwen3-tts-runtime
```
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues