# MeloTTS

MeloTTS ist eine hochwertige, mehrsprachige Text‑zu‑Sprache‑Bibliothek, entwickelt von **MyShell AI**. Sie liefert schnelle, natürlich klingende Sprachsynthese in mehreren Sprachen und englischen Akzenten, ausgelegt für Forschung und Produktionseinsatz. MeloTTS ist auf Geschwindigkeit optimiert — es kann Sprache deutlich schneller als in Echtzeit sogar auf der CPU erzeugen — und behält dabei eine hohe Audioqualität, die für kommerzielle Nutzung geeignet ist.

MeloTTS unterstützt derzeit:

* **Englisch** (Amerikanisch, Britisch, Indisch, Australisch, Standard)
* **Chinesisch (vereinfachtes Chinesisch & gemischtes Chinesisch‑Englisch)**
* **Japanisch**
* **Koreanisch**
* **Spanisch**
* **Französisch**

Wichtigste Höhepunkte:

* ⚡ **Schnelle Inferenz** — schneller als in Echtzeit auf der CPU, blitzschnell auf der GPU
* 🌍 **Mehrsprachig** — 6 Sprachen mit Akzentvarianten für Englisch
* 🐳 **Docker‑bereit** — offizielles Docker‑Image verfügbar
* 🔌 **REST-API** — HTTP‑API zur Integration in jede Anwendung
* 📱 **Produktionsreif** — verwendet in MyShells Verbraucherprodukten

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die über [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

***

## Serveranforderungen

| Parameter      | Minimum                | Empfohlen               |
| -------------- | ---------------------- | ----------------------- |
| GPU            | NVIDIA GTX 1080 (8 GB) | NVIDIA RTX 3090 (24 GB) |
| VRAM           | 4 GB                   | 8–16 GB                 |
| RAM            | 8 GB                   | 16 GB                   |
| CPU            | 4 Kerne                | 8 Kerne                 |
| Festplatte     | 10 GB                  | 20 GB                   |
| Betriebssystem | Ubuntu 20.04+          | Ubuntu 22.04            |
| CUDA           | 11.7+ (optional)       | 12.1+                   |
| Python         | 3.8+                   | 3.10                    |
| Ports          | 22, 8888               | 22, 8888                |

{% hint style="info" %}
MeloTTS ist außergewöhnlich effizient — es läuft gut auf der CPU für einzelne Anfragen und profitiert stark von der GPU bei der Stapelverarbeitung. Selbst eine günstige GPU verdoppelt den Durchsatz dramatisch.
{% endhint %}

***

## Schnelle Bereitstellung auf CLORE.AI

{% hint style="warning" %}
**Hinweis:** MeloTTS hat kein offizielles vorgefertigtes Docker‑Image auf Docker Hub (`myshell-ai/melotts` existiert nicht). Der empfohlene Ansatz ist, ein NVIDIA CUDA Basis‑Image zu verwenden und MeloTTS per pip aus dem offiziellen GitHub‑Repository zu installieren.
{% endhint %}

### 1. Finden Sie einen geeigneten Server

Gehe zu [CLORE.AI Marketplace](https://clore.ai/marketplace) und filtern Sie nach:

* **VRAM**: ≥ 4 GB (oder CPU‑only für geringen Durchsatz)
* **GPU**: Jede NVIDIA GPU (GTX 1080+, RTX‑Serie, A100)
* **Festplatte**: ≥ 10 GB

### 2. Konfigurieren Sie Ihre Bereitstellung

**Docker-Image:**

```
nvidia/cuda:12.1.0-devel-ubuntu22.04
```

**Portzuordnungen:**

```
22   → SSH-Zugriff
8888 → MeloTTS API‑Server
```

**Umgebungsvariablen:**

```
NVIDIA_VISIBLE_DEVICES=all
```

**Startbefehl** (ausführen nach SSH in den Server):

```bash
apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git && \
git clone https://github.com/myshell-ai/MeloTTS.git && \
cd MeloTTS && pip install -e . && \
python -m unidic download && \
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')" && \
python -m melo.api_server --host 0.0.0.0 --port 8888
```

### 3. Greifen Sie auf die API zu

```
http://<your-clore-server-ip>:8888
```

Testen mit:

```bash
curl -X POST http://<server-ip>:8888/synthesize \
  -H "Content-Type: application/json" \
  -d '{"text": "Hello from Clore.ai!", "language": "EN", "speaker_id": "EN-Default"}'
```

***

## Schritt-für-Schritt-Einrichtung

### Schritt 1: SSH auf Ihren Server

```bash
ssh root@<your-clore-server-ip> -p <ssh-port>
```

### Schritt 2: Container bauen und ausführen

Da MeloTTS kein vorgefertigtes Docker Hub Image hat, verwenden Sie ein NVIDIA CUDA Basisimage und installieren MeloTTS aus dem Quellcode:

```bash
# Führen Sie einen CUDA‑Container aus und installieren Sie MeloTTS darin
docker run -d \
  --name melotts \
  --gpus all \
  -p 8888:8888 \
  -v /workspace/melotts/outputs:/app/outputs \
  -e NVIDIA_VISIBLE_DEVICES=all \
  nvidia/cuda:12.1.0-devel-ubuntu22.04 \
  bash -c "apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git && \
    git clone https://github.com/myshell-ai/MeloTTS.git /app/MeloTTS && \
    cd /app/MeloTTS && pip install -e . && \
    python -m unidic download && \
    python3 -c \"import nltk; nltk.download('averaged_perceptron_tagger_eng')\" && \
    python -m melo.api_server --host 0.0.0.0 --port 8888"
```

Alternativ: Ein benutzerdefiniertes Docker‑Image aus dem Quellcode bauen:

```bash
git clone https://github.com/myshell-ai/MeloTTS.git
cd MeloTTS
docker build -t melotts:local .
docker run -d \
  --name melotts \
  --gpus all \
  -p 8888:8888 \
  melotts:local
```

### Schritt 3: Überprüfen, ob der Dienst läuft

```bash
# Überprüfen Sie die Container-Logs
docker logs -f melotts

# Auf Start warten, dann testen
curl http://localhost:8888/health
```

### Schritt 4: Alternative — Jupyter Notebook Oberfläche

```bash
docker run -d \
  --name melotts-jupyter \
  --gpus all \
  -p 8888:8888 \
  nvidia/cuda:12.1.0-devel-ubuntu22.04 \
  bash -c "pip install jupyter melo-tts && \
    jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root"
```

Zugriff unter: `http://<server-ip>:8888`

### Schritt 5: Installation per pip (ohne Docker)

```bash
# Systemabhängigkeiten installieren
apt-get install -y python3-pip ffmpeg espeak-ng

# MeloTTS installieren
pip install melo-tts

# Erforderliche NLTK‑Daten herunterladen
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')"
```

***

## Beispielanwendungen

### Beispiel 1: Grundlegendes English TTS (Python)

```python
from melo.api import TTS

# English TTS initialisieren
speed = 1.0  # Sprechgeschwindigkeit anpassen (0.5 = langsam, 2.0 = schnell)
device = 'cuda'  # Verwenden Sie 'cpu', wenn keine GPU verfügbar ist

tts = TTS(language='EN', device=device)

# Verfügbare Sprecher‑IDs abrufen
speakers = tts.hps.data.spk2id
print("Available speakers:", list(speakers.keys()))
# Ausgabe: ['EN-Default', 'EN-US', 'EN-GB', 'EN-India', 'EN-Australia', 'EN-Brazil']

# Sprache erzeugen
speaker_ids = tts.hps.data.spk2id
output_path = "output_english.wav"

tts.tts_to_file(
    text="Welcome to Clore.ai, your GPU cloud marketplace for AI workloads. Rent powerful GPUs in minutes.",
    speaker_id=speaker_ids['EN-Default'],
    output_path=output_path,
    speed=speed
)

print(f"Saved to: {output_path}")
```

***

### Beispiel 2: Mehrsprachiges TTS

```python
from melo.api import TTS

device = 'cuda'

# Definieren Sie Sprache‑Text Paare
language_texts = [
    ('EN', 'EN-US', "GPU computing has transformed artificial intelligence research and development."),
    ('EN', 'EN-GB', "The United Kingdom leads Europe in AI investment and innovation."),
    ('ZH', 'ZH', "Clore.ai是一个去中心化的GPU云计算市场，为AI开发者提供算力服务。"),
    ('JP', 'JP', "人工知能の発展には大規模な計算資源が必要です。"),
    ('KR', 'KR', "Clore.ai는 AI 연구자를 위한 GPU 클라우드 마켓플레이스입니다."),
    ('SP', 'SP', "La inteligencia artificial está transformando todas las industrias del mundo."),
    ('FR', 'FR', "L'intelligence artificielle révolutionne la façon dont nous travaillons et vivons."),
]

for lang, speaker, text in language_texts:
    try:
        tts = TTS(language=lang, device=device)
        speaker_id = tts.hps.data.spk2id[speaker]

        output_file = f"output_{lang}_{speaker}.wav"
        tts.tts_to_file(text=text, speaker_id=speaker_id, output_path=output_file)
        print(f"✓ Generated [{lang}]: {output_file}")
    except Exception as e:
        print(f"✗ Error [{lang}]: {e}")
```

***

### Beispiel 3: Verwendung der REST API

```python
import requests
import json

API_BASE = "http://<your-clore-server-ip>:8888"

# Verfügbare Stimmen prüfen
response = requests.get(f"{API_BASE}/voices")
print("Available voices:", json.dumps(response.json(), indent=2))

# Sprache synthetisieren
def synthesize(text, language="EN", speaker="EN-Default", speed=1.0):
    payload = {
        "text": text,
        "language": language,
        "speaker_id": speaker,
        "speed": speed,
        "format": "wav"
    }

    response = requests.post(
        f"{API_BASE}/synthesize",
        json=payload,
        timeout=30
    )

    if response.status_code == 200:
        return response.content
    else:
        raise Exception(f"API error: {response.status_code} - {response.text}")

# Beispiele erzeugen
samples = [
    ("Hello, this is MeloTTS running on Clore.ai GPU servers.", "EN", "EN-US"),
    ("This is the British English accent variant.", "EN", "EN-GB"),
    ("Let me demonstrate the Indian English accent.", "EN", "EN-India"),
]

for text, lang, speaker in samples:
    audio_bytes = synthesize(text, lang, speaker)
    filename = f"api_output_{speaker.replace('-', '_')}.wav"
    with open(filename, "wb") as f:
        f.write(audio_bytes)
    print(f"Saved: {filename}")
```

***

### Beispiel 4: Hochgeschwindigkeits‑Batchverarbeitung

```python
from melo.api import TTS
from concurrent.futures import ThreadPoolExecutor
import soundfile as sf
import time
import numpy as np
from pathlib import Path

device = 'cuda'
tts = TTS(language='EN', device=device)
speaker_id = tts.hps.data.spk2id['EN-US']

# Große Charge von Texten
texts = [
    f"This is sentence number {i}. It demonstrates fast batch processing with MeloTTS on Clore.ai GPU infrastructure."
    for i in range(1, 51)  # 50 sentences
]

output_dir = Path("batch_output")
output_dir.mkdir(exist_ok=True)

start_time = time.time()

# Charge verarbeiten
for i, text in enumerate(texts):
    output_path = str(output_dir / f"batch_{i+1:03d}.wav")
    tts.tts_to_file(
        text=text,
        speaker_id=speaker_id,
        output_path=output_path,
        speed=1.0,
        quiet=True
    )
    if (i + 1) % 10 == 0:
        elapsed = time.time() - start_time
        print(f"Progress: {i+1}/50 | Time: {elapsed:.1f}s | Rate: {(i+1)/elapsed:.1f} sentences/sec")

total_time = time.time() - start_time
print(f"\nBatch complete: {len(texts)} sentences in {total_time:.1f}s")
print(f"Average: {total_time/len(texts)*1000:.0f}ms per sentence")
```

***

### Beispiel 5: Gemischtes Chinesisch‑Englisch TTS

```python
from melo.api import TTS

device = 'cuda'
tts = TTS(language='ZH', device=device)
speaker_id = tts.hps.data.spk2id['ZH']

# Gemischter Sprachtext (Chinesisch + Englisch)
mixed_texts = [
    "我们使用Clore.ai的GPU服务器来运行machine learning workloads。",
    "今天的AI conference讨论了large language models和speech synthesis技术。",
    "我的startup需要GPU资源来训练我们的deep learning模型。",
    "Clore.ai提供了非常competitive的价格，比AWS和GCP便宜很多。",
]

for i, text in enumerate(mixed_texts):
    output_file = f"mixed_zh_en_{i+1}.wav"
    tts.tts_to_file(
        text=text,
        speaker_id=speaker_id,
        output_path=output_file,
        speed=0.9  # Etwas langsamer für bessere Verständlichkeit
    )
    print(f"Generated: {output_file}")
    print(f"  Text: {text[:60]}...")
```

***

## Konfiguration

### Docker-Compose-Setup

Da MeloTTS kein offizielles Docker Hub Image hat, verwenden Sie das NVIDIA CUDA Basisimage und installieren MeloTTS beim Start aus dem Quellcode:

```yaml
version: '3.8'

services:
  melotts:
    image: nvidia/cuda:12.1.0-devel-ubuntu22.04
    container_name: melotts
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
      - PYTHONDONTWRITEBYTECODE=1
    ports:
      - "8888:8888"
    volumes:
      - ./outputs:/app/outputs
      - ./cache:/root/.cache
    command: >
      bash -c "apt-get update && apt-get install -y python3-pip ffmpeg espeak-ng git &&
      git clone https://github.com/myshell-ai/MeloTTS.git /app/MeloTTS &&
      cd /app/MeloTTS && pip install -e . &&
      python -m unidic download &&
      python3 -c 'import nltk; nltk.download(\"averaged_perceptron_tagger_eng\")' &&
      python -m melo.api_server --host 0.0.0.0 --port 8888"
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8888/health"]
      interval: 30s
      timeout: 10s
      retries: 3
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
```

### API Konfigurationsoptionen

| Parameter   | Standard    | Beschreibung                                          |
| ----------- | ----------- | ----------------------------------------------------- |
| `--host`    | `127.0.0.1` | Bind‑Adresse (verwenden Sie `0.0.0.0` für öffentlich) |
| `--port`    | `8888`      | API‑Server Port                                       |
| `--workers` | `1`         | Anzahl der Worker‑Prozesse                            |
| `--device`  | `auto`      | `cuda`, `cpu`, oder `auto`                            |

### Unterstützte Sprachen und Sprecher

| Sprache     | Code | Sprecher‑IDs                                                            |
| ----------- | ---- | ----------------------------------------------------------------------- |
| Englisch    | `EN` | `EN-Default`, `EN-US`, `EN-GB`, `EN-India`, `EN-Australia`, `EN-Brazil` |
| Chinesisch  | `ZH` | `ZH`                                                                    |
| Japanisch   | `JP` | `JP`                                                                    |
| Koreanisch  | `KR` | `KR`                                                                    |
| Spanisch    | `SP` | `SP`                                                                    |
| Französisch | `FR` | `FR`                                                                    |

***

## Leistungs-Tipps

### 1. GPU vs CPU Benchmark

MeloTTS Leistung (RTF = Real‑Time‑Factor, niedriger ist besser):

| Gerät         | RTF     | Hinweise                       |
| ------------- | ------- | ------------------------------ |
| CPU (8 Kerne) | \~0.3x  | Schnell, gut bei geringer Last |
| RTX 3080      | \~0.05x | 20× schneller als in Echtzeit  |
| RTX 4090      | \~0.02x | 50× schneller als in Echtzeit  |
| A100          | \~0.01x | 100× schneller als in Echtzeit |

### 2. Für Durchsatz optimieren

```python
# Gradientenberechnung für die Inferenz deaktivieren
import torch

with torch.no_grad():
    tts.tts_to_file(text, speaker_id, output_path)
```

### 3. Modell aufwärmen

```python
# Führen Sie eine Warmup‑Inference aus, um CUDA‑Kernels zu laden
tts.tts_to_file(
    text="warmup",
    speaker_id=speaker_id,
    output_path="/dev/null"
)
print("Modell aufgewärmt, bereit für schnelle Inferenz")
```

### 4. Audioqualität vs. Geschwindigkeit anpassen

```python
# Schneller (leicht geringere Qualität)
tts.tts_to_file(text, speaker_id, output_path, speed=1.2)

# Langsameres Sprechen (bessere Artikulation)
tts.tts_to_file(text, speaker_id, output_path, speed=0.8)
```

### 5. Speichereffizienz

```python
# GPU‑Speicher zwischen großen Batches freigeben
import gc
import torch

gc.collect()
torch.cuda.empty_cache()
```

***

## Fehlerbehebung

### Problem: `espeak-ng` nicht gefunden

```bash
apt-get install -y espeak-ng
python3 -c "import phonemizer; print('phonemizer OK')"
```

### Problem: NLTK‑Daten fehlen

```bash
python3 -c "
import nltk
nltk.download('averaged_perceptron_tagger_eng')
nltk.download('punkt')
"
```

### Problem: Port 8888 kollidiert mit Jupyter

MeloTTS verwendet standardmäßig Port 8888, der mit Jupyter Notebook kollidiert. Lösungen:

```bash
# Option 1: MeloTTS auf einem anderen Port ausführen
python -m melo.api_server --host 0.0.0.0 --port 8889

# Option 2: Jupyter auf einem anderen Port ausführen
jupyter notebook --port 8890
```

### Problem: Chinesischer Text wird nicht korrekt dargestellt

```bash
# Chinesische Sprachunterstützung installieren
pip install jieba
apt-get install -y python3-opencc

# Test
python3 -c "from melo.api import TTS; t = TTS('ZH'); print('ZH OK')"
```

### Problem: Docker‑Image Pull schlägt fehl

```bash
# Stattdessen aus dem Quellcode bauen
git clone https://github.com/myshell-ai/MeloTTS.git
cd MeloTTS
pip install -e .
python3 -c "import nltk; nltk.download('averaged_perceptron_tagger_eng')"
```

### Problem: Langsame Inferenz auf der GPU

```bash
# Überprüfen, ob die GPU genutzt wird
python3 -c "
import torch
from melo.api import TTS
tts = TTS('EN', device='cuda')
print(f'Device: {next(tts.model.parameters()).device}')
print(f'CUDA available: {torch.cuda.is_available()}')
"
```

***

## Clore.ai GPU-Empfehlungen

MeloTTS ist leichtgewichtig — es läuft gut auf der CPU bei geringem Volumen und skaliert linear mit GPU‑Rechenleistung. Sie benötigen keine teure Hardware.

| GPU       | VRAM  | Clore.ai-Preis | RTF (Real‑Time‑Factor)   | Kapazität          |
| --------- | ----- | -------------- | ------------------------ | ------------------ |
| Nur CPU   | —     | \~$0.02/Stunde | \~0.3×                   | \~3 Anfragen/Min   |
| RTX 3090  | 24 GB | \~$0.12/Stunde | \~0.02× (50× Echtzeit)   | \~100 Anfragen/Min |
| RTX 4090  | 24 GB | \~$0.70/Stunde | \~0.01× (100× Echtzeit)  | \~200 Anfragen/Min |
| A100 40GB | 40 GB | \~$1.20/Stunde | \~0.005× (200× Echtzeit) | \~400 Anfragen/Min |

{% hint style="info" %}
**Bestes Preis‑Leistungs‑Verhältnis für TTS‑Workloads:** RTX 3090 bei ~~$0.12/Stunde liefert 50× Echtzeit‑TTS‑Geschwindigkeit. Für eine Produktions‑API, die Hunderte von Nutzern bedient, ist das mehr als ausreichend. CPU‑Only Instanzen (~~$0.02/Stunde) eignen sich gut für Entwicklung und deployments mit geringem Traffic.
{% endhint %}

**Produktionsempfehlung:** Für eine mehrsprachige TTS‑API, die 10–50 gleichzeitige Nutzer bedient, ist die RTX 3090 der Sweetspot. Horizontal skalieren (mehrere Instanzen) statt auf teure A100 aufzurüsten — MeloTTS profitiert nicht proportional von höherwertigen GPUs.

***

## Links

* **GitHub**: <https://github.com/myshell-ai/MeloTTS>
* **Docker**: Kein offizielles Docker Hub Image — von installieren [GitHub Quellcode](https://github.com/myshell-ai/MeloTTS) unter Verwendung von `nvidia/cuda:12.1.0-devel-ubuntu22.04` Basis-Image
* **Paper**: <https://arxiv.org/abs/2406.06753>
* **Hugging Face**: <https://huggingface.co/myshell-ai/MeloTTS-English>
* **MyShell AI**: <https://myshell.ai>
* **CLORE.AI Marketplace**: <https://clore.ai/marketplace>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-de/audio-and-sprache/melotts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
