> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-de/audio-and-sprache/styletss2.md).

# StyleTTS2

StyleTTS2 erreicht von Menschen bewertete Natürlichkeitswerte, die über denen der Originalaufnahmen auf den Benchmarks LJSpeech und LibriTTS liegen (MOS 4,55 vs. 4,23 Ground Truth). Es verwendet **Stil-Diffusion** und **adversariales Training** um Sprechstile als Verteilung latenter Variablen zu modellieren, wodurch expressive Synthese und Zero-Shot-Sprecheranpassung aus einem kurzen Referenzclip ermöglicht werden.

Im Gegensatz zu traditionellen TTS-Systemen kann StyleTTS2 mit einem kurzen Referenzaudio auf nicht gesehene Sprecher verallgemeinern und Sprache erzeugen, die mit professionellen Synchronsprechern konkurriert. Es wurde benchmarked und übertrifft die von Menschen bewerteten Natürlichkeitswerte in mehreren Datensätzen — ein Novum für Open-Source-TTS.

Wichtige Funktionen:

* **Natürlichkeit auf Menscheniveau** — übertrifft menschliche MOS-Werte auf LJSpeech
* **Zero-Shot-Sprecheranpassung** — klont jede Stimme aus einer kurzen Audioaufnahme
* **Stil-Diffusion** — expressive, abwechslungsreiche Prosodie und Sprechstil
* **Mehrere Sprecher unterstützt** — trainiert auf LibriTTS (2.300+ Sprecher)
* **Leichte Inferenz** — läuft effizient auf Consumer-GPUs

{% 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 RTX 3070 (8 GB) | NVIDIA RTX 4090 (24 GB) |
| VRAM           | 6 GB                   | 12–24 GB                |
| RAM            | 16 GB                  | 32 GB                   |
| CPU            | 4 Kerne                | 8+ Kerne                |
| Festplatte     | 15 GB                  | 30 GB                   |
| Betriebssystem | Ubuntu 20.04+          | Ubuntu 22.04            |
| CUDA           | 11.7+                  | 12.1+                   |
| Python         | 3.8+                   | 3.10                    |
| Ports          | 22, 7860               | 22, 7860                |

{% hint style="info" %}
StyleTTS2 ist relativ ressourcenschonend — eine RTX 3070 oder 3080 bewältigt Realtime-Inferenz problemlos. Für Batch-Verarbeitung oder das Bedienen gleichzeitiger Nutzer sollte man eine 4090 oder A100 verwenden.
{% endhint %}

***

## Schnelle Bereitstellung auf CLORE.AI

StyleTTS2 erfordert einen benutzerdefinierten Docker-Build, da kein offizielles vorgefertigtes Image vorhanden ist. Die Einrichtung dauert etwa 10 Minuten.

### 1. Finden Sie einen geeigneten Server

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

* **VRAM**: ≥ 6 GB
* **GPU**: RTX 3070, 3080, 3090, 4080, 4090, A100
* **Festplatte**: ≥ 20 GB

### 2. Konfigurieren Sie Ihre Bereitstellung

**Docker-Image (Basis):**

```
nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04
```

**Port-Zuordnungen:**

```
22   → SSH-Zugriff
7860 → Gradio Web UI
```

**Startbefehl:**

```bash
bash -c "apt-get update && apt-get install -y git python3 python3-pip ffmpeg espeak-ng && \
  git clone https://github.com/yl4579/StyleTTS2 /workspace/StyleTTS2 && \
  cd /workspace/StyleTTS2 && pip install -r requirements.txt && \
  python app.py"
```

### 3. Greifen Sie auf die Oberfläche zu

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

***

## Schritt-für-Schritt-Einrichtung

### Schritt 1: Per SSH auf Ihren Server verbinden

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

### Schritt 2: Systemabhängigkeiten installieren

```bash
apt-get update && apt-get install -y \
  git \
  python3 \
  python3-pip \
  python3-venv \
  ffmpeg \
  espeak-ng \
  libsndfile1 \
  build-essential \
  wget \
  curl
```

### Schritt 3: StyleTTS2-Repository klonen

```bash
cd /workspace
git clone https://github.com/yl4579/StyleTTS2.git
cd StyleTTS2
```

### Schritt 4: Python-Virtualenv erstellen

```bash
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
```

### Schritt 5: Abhängigkeiten installieren

```bash
pip install -r requirements.txt

# Zusätzliche Abhängigkeiten bei Bedarf installieren
pip install phonemizer gruut
```

### Schritt 6: Vorgefertigte Modelle herunterladen

```bash
# LJSpeech-Modell herunterladen (Einzelspeaker, hohe Qualität)
mkdir -p Models/LJSpeech
wget -O Models/LJSpeech/epoch_2nd_00100.pth \
  "https://huggingface.co/yl4579/StyleTTS2-LJSpeech/resolve/main/Models/LJSpeech/epoch_2nd_00100.pth"

wget -O Models/LJSpeech/config.yml \
  "https://huggingface.co/yl4579/StyleTTS2-LJSpeech/resolve/main/Models/LJSpeech/config.yml"

# LibriTTS-Modell herunterladen (Mehrfachsprecher, Zero-Shot)
mkdir -p Models/LibriTTS
wget -O Models/LibriTTS/epochs_2nd_00020.pth \
  "https://huggingface.co/yl4579/StyleTTS2-LibriTTS/resolve/main/Models/LibriTTS/epochs_2nd_00020.pth"

wget -O Models/LibriTTS/config.yml \
  "https://huggingface.co/yl4579/StyleTTS2-LibriTTS/resolve/main/Models/LibriTTS/config.yml"
```

### Schritt 7: Dockerfile bauen und ausführen

```bash
# Dockerfile erstellen
cat > Dockerfile << 'EOF'
FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04

ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
    git python3 python3-pip python3-venv \
    ffmpeg espeak-ng libsndfile1 build-essential wget curl \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /workspace
RUN git clone https://github.com/yl4579/StyleTTS2.git
WORKDIR /workspace/StyleTTS2
RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 7860
CMD ["python3", "app.py", "--share"]
EOF

docker build -t styletts2:local .
docker run -d --name styletts2 --gpus all \
  -p 7860:7860 \
  -v /workspace/models:/workspace/StyleTTS2/Models \
  styletts2:local
```

### Schritt 8: Gradio-Demo direkt starten

```bash
source venv/bin/activate
python app.py
```

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

***

## Beispielanwendungen

### Beispiel 1: Basis-TTS via Python-API

```python
import torch
import soundfile as sf
import numpy as np
from models import *
from utils import *
import yaml

# Konfig laden
config = yaml.safe_load(open("Models/LJSpeech/config.yml"))

# Modell initialisieren
model = build_model(recursive_munch(config['model_params']), "cpu")
params = torch.load("Models/LJSpeech/epoch_2nd_00100.pth", map_location='cpu')
model = load_F0_models(model)

# Auf GPU verschieben
device = "cuda" if torch.cuda.is_available() else "cpu"
for key in model:
    model[key] = model[key].to(device)

print(f"Modell geladen auf: {device}")
print(f"Genutzter VRAM: {torch.cuda.memory_allocated()/1e9:.2f} GB")
```

***

### Beispiel 2: Zero-Shot-Voice-Cloning

```python
import torch
import torchaudio
import soundfile as sf
from inference import StyleTTS2Inference

# Inferenz-Engine initialisieren
tts = StyleTTS2Inference(
    model_path="Models/LibriTTS/epochs_2nd_00020.pth",
    config_path="Models/LibriTTS/config.yml",
    device="cuda"
)

# Referenzaudio laden (10–30 Sekunden funktionieren am besten)
reference_audio, sr = torchaudio.load("reference_voice.wav")

# Sprache in der Referenzstimme erzeugen
text = "Clore.ai provides powerful GPU infrastructure for AI applications including text-to-speech synthesis."

audio = tts.synthesize(
    text=text,
    reference_audio=reference_audio,
    reference_sr=sr,
    diffusion_steps=10,    # Höher = bessere Qualität, langsamer
    embedding_scale=1.5,   # Steuert die Stilstärke
    alpha=0.3,             # Akustisches Stilgewicht
    beta=0.7,              # Prosodisches Stilgewicht
)

sf.write("cloned_voice_output.wav", audio, 24000)
print("Klon-Ausgabe gespeichert!")
```

***

### Beispiel 3: Expressive Stilkontrolle

```python
from inference import StyleTTS2Inference
import soundfile as sf

tts = StyleTTS2Inference(
    model_path="Models/LibriTTS/epochs_2nd_00020.pth",
    config_path="Models/LibriTTS/config.yml",
    device="cuda"
)

text = "Welcome to our presentation on GPU computing with Clore.ai."

# Experimentieren Sie mit unterschiedlichen Stilparametern
style_configs = [
    {"name": "neutral",    "alpha": 0.3, "beta": 0.7, "diffusion_steps": 5},
    {"name": "expressive", "alpha": 0.5, "beta": 0.9, "diffusion_steps": 15},
    {"name": "fast",       "alpha": 0.1, "beta": 0.3, "diffusion_steps": 3},
    {"name": "slow_deep",  "alpha": 0.7, "beta": 0.5, "diffusion_steps": 20},
]

for cfg in style_configs:
    audio = tts.synthesize(
        text=text,
        diffusion_steps=cfg["diffusion_steps"],
        alpha=cfg["alpha"],
        beta=cfg["beta"],
    )
    filename = f"style_{cfg['name']}.wav"
    sf.write(filename, audio, 24000)
    print(f"Generiert: {filename}")
```

***

### Beispiel 4: Gradio Web-Interface

```python
import gradio as gr
import soundfile as sf
import numpy as np
from inference import StyleTTS2Inference
import tempfile

tts = StyleTTS2Inference(
    model_path="Models/LibriTTS/epochs_2nd_00020.pth",
    config_path="Models/LibriTTS/config.yml",
    device="cuda"
)

def synthesize(text, reference_audio, diffusion_steps, alpha, beta):
    if reference_audio is not None:
        sr, audio_data = reference_audio
        # In das erwartete Format konvertieren
        ref_audio = audio_data.astype(np.float32) / 32768.0
    else:
        ref_audio = None
        sr = None

    output = tts.synthesize(
        text=text,
        reference_audio=ref_audio,
        reference_sr=sr,
        diffusion_steps=int(diffusion_steps),
        alpha=alpha,
        beta=beta,
    )

    # In temporäre Datei speichern
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
        sf.write(f.name, output, 24000)
        return f.name

demo = gr.Interface(
    fn=synthesize,
    inputs=[
        gr.Textbox(label="Eingabetext", lines=4),
        gr.Audio(label="Referenzstimme (optional)", type="numpy"),
        gr.Slider(1, 30, value=10, label="Diffusionsschritte"),
        gr.Slider(0.0, 1.0, value=0.3, label="Alpha (akustischer Stil)"),
        gr.Slider(0.0, 1.0, value=0.7, label="Beta (prosodischer Stil)"),
    ],
    outputs=gr.Audio(label="Generierte Sprache"),
    title="StyleTTS2 auf Clore.ai GPU",
    description="TTS auf Menscheniveau mit Stil-Diffusion"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

***

### Beispiel 5: Batch-Erstellung von Hörbüchern

```python
import soundfile as sf
import numpy as np
from pathlib import Path
from inference import StyleTTS2Inference

tts = StyleTTS2Inference(
    model_path="Models/LibriTTS/epochs_2nd_00020.pth",
    config_path="Models/LibriTTS/config.yml",
    device="cuda"
)

# Text in Absätze aufteilen
book_text = """
Kapitel Eins: Die GPU-Revolution

Die Geschichte der künstlichen Intelligenz lässt sich nicht von der Entwicklung der 
Grafikprozessoren trennen. Was als spezialisierte Hardware zum Rendern von Pixeln begann, 
wurde zum Motor der modernen KI-Revolution.

Kapitel Zwei: Verteiltes Rechnen

Als Modelle größer wurden, wich das Training auf einer einzelnen GPU verteilten Systemen. 
Plattformen wie Clore.ai entstanden, um den Zugang zu dieser Rechenkraft zu demokratisieren, 
und Unternehmensniveau-GPU-Infrastruktur für Einzelpersonen und Startups zugänglich zu machen.
""".strip()

paragraphs = [p.strip() for p in book_text.split('\n\n') if p.strip()]
output_dir = Path("audiobook_output")
output_dir.mkdir(exist_ok=True)

audio_segments = []
for i, paragraph in enumerate(paragraphs):
    print(f"Verarbeite Absatz {i+1}/{len(paragraphs)}...")
    audio = tts.synthesize(
        text=paragraph,
        diffusion_steps=10,
        alpha=0.3,
        beta=0.7,
    )
    segment_path = output_dir / f"segment_{i+1:03d}.wav"
    sf.write(str(segment_path), audio, 24000)
    audio_segments.append(audio)
    print(f"  ✓ Gespeichert {segment_path}")

# Alle Segmente mit kurzer Stille zusammenfügen
silence = np.zeros(int(24000 * 0.5))  # 0,5 Sekunden Stille
full_audio = []
for seg in audio_segments:
    full_audio.append(seg)
    full_audio.append(silence)

combined = np.concatenate(full_audio)
sf.write("audiobook_complete.wav", combined, 24000)
print(f"\nKomplettes Hörbuch: {len(combined)/24000:.1f} Sekunden")
```

***

## Konfiguration

### config.yml Hauptparameter

```yaml
model_params:
  dim_in: 64
  hidden_dim: 512
  max_conv_dim: 512
  n_layer: 3
  n_mels: 80

diffusion:
  timesteps: 1000
  beta_schedule: "squaredcos_cap_v2"

training:
  batch_size: 16
  epochs: 100
  save_freq: 10
```

### Inferenzparameter

| Parameter         | Bereich | Standard | Wirkung                                   |
| ----------------- | ------- | -------- | ----------------------------------------- |
| `diffusion_steps` | 1–30    | 10       | Qualitäts- vs. Geschwindigkeitskompromiss |
| `alpha`           | 0.0–1.0 | 0.3      | Akustisches Stilgewicht aus der Referenz  |
| `beta`            | 0.0–1.0 | 0.7      | Prosodisches Stilgewicht aus der Referenz |
| `embedding_scale` | 1.0–3.0 | 1.5      | Gesamte Stilintensität                    |
| `t`               | 0.6–1.0 | 0.7      | Rauschpegel (höher = mehr Variation)      |

***

## Leistungs-Tipps

### 1. Diffusionsschritte optimieren

Der Standardwert von 10 Schritten balanciert Qualität und Geschwindigkeit. Für Echtzeitanwendungen verwenden Sie 5 Schritte; für maximale Qualität 20–30.

```python
# Echtzeit (schnell)
audio = tts.synthesize(text, diffusion_steps=5)

# Hohe Qualität (langsam)
audio = tts.synthesize(text, diffusion_steps=20)
```

### 2. Verwenden Sie torch.compile (PyTorch 2.0+)

```python
import torch
model = torch.compile(model, mode="reduce-overhead")
```

### 3. Mixed-Precision-Inferenz

```python
with torch.autocast(device_type="cuda", dtype=torch.float16):
    audio = tts.synthesize(text, diffusion_steps=10)
```

### 4. Mehrere Sätze im Batch verarbeiten

Verarbeiten Sie mehrere Sätze zusammen, wenn möglich, um die GPU-Auslastung zu maximieren und Overhead zu reduzieren.

### 5. Referenzsprecher-Embeddings cachen

```python
# Einmal berechnen, vielfach wiederverwenden
speaker_embedding = tts.compute_speaker_embedding(reference_audio, sr)

# Für mehrere Äußerungen wiederverwenden
for text in texts:
    audio = tts.synthesize_with_embedding(text, speaker_embedding)
```

***

## Fehlerbehebung

### Problem: espeak-ng nicht gefunden

```bash
apt-get install -y espeak-ng espeak-ng-data
# Installation überprüfen
espeak-ng --version
```

### Problem: Phonemizer schlägt fehl

```bash
pip install phonemizer
# Test
python3 -c "from phonemizer import phonemize; print(phonemize('hello world'))"
```

### Problem: CUDA Out of Memory

```bash
# Batch-Größe reduzieren oder CPU-Offloading verwenden
export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:256
# Oder zu FP16 wechseln
```

### Problem: Schlechte Audioqualität

* Erhöhen `diffusion_steps` auf 15–20
* Stellen Sie sicher, dass das Referenzaudio sauber ist, mindestens 16 kHz
* Versuchen Sie, anzupassen `alpha` und `beta` Parameter
* Verwenden Sie einen längeren Referenzclip (15–30 Sekunden)

### Problem: Modell-Download von Hugging Face schlägt fehl

```bash
pip install huggingface_hub
python3 -c "
from huggingface_hub import snapshot_download
snapshot_download('yl4579/StyleTTS2-LibriTTS', local_dir='Models/LibriTTS')
"
```

***

## Clore.ai GPU-Empfehlungen

StyleTTS2 ist ein leichtgewichtiges Modell — der LibriTTS-Checkpoint ist \~300MB, die Inferenz ist selbst auf bescheidenen GPUs schnell.

| GPU       | VRAM  | Clore.ai-Preis | Inferenzgeschwindigkeit | Am besten für                      |
| --------- | ----- | -------------- | ----------------------- | ---------------------------------- |
| Nur CPU   | —     | \~$0.02/Stunde | \~0,5× Echtzeit         | Entwicklung, Test                  |
| RTX 3090  | 24 GB | \~$0.12/Stunde | \~15× Echtzeit          | Produktions-API, Voice Cloning     |
| RTX 4090  | 24 GB | \~$0.70/Stunde | \~25× Echtzeit          | API mit hoher Parallelität         |
| A100 40GB | 40 GB | \~$1.20/Stunde | \~40× Echtzeit          | Großes Batch für Hörbucherstellung |

{% hint style="info" %}
**RTX 3090 bei \~$0.12/std** ist die optimale Wahl für StyleTTS2. Das Modell ist so klein, dass Sie fast nichts für GPU-Zeit ausgeben — eine volle Stunde synthetisierten Audios kostet unter 0,01 $ GPU-Miete. Für Hörbuchproduktion oder Voice-Cloning-Dienste ist das extrem kosteneffizient.
{% endhint %}

**Tipp zur Qualität beim Zero-Shot-Voice-Cloning:** Stellen Sie 15–30 Sekunden sauberes Referenzaudio mit 22 kHz oder 24 kHz bereit. Das Stil-Diffusionsmodul benötigt genug Audio, um Sprechstil, Tempo und Prosodie genau zu erfassen. Rauschende oder zu kurze Referenzen verschlechtern die Ausgabequalität deutlich.

***

## Links

* **GitHub**: <https://github.com/yl4579/StyleTTS2>
* **Paper (arXiv)**: <https://arxiv.org/abs/2306.07691>
* **Hugging Face (LJSpeech)**: <https://huggingface.co/yl4579/StyleTTS2-LJSpeech>
* **Hugging Face (LibriTTS)**: <https://huggingface.co/yl4579/StyleTTS2-LibriTTS>
* **Demo Space**: <https://huggingface.co/spaces/styletts2/styletts2>
* **CLORE.AI Marketplace**: <https://clore.ai/marketplace>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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/styletss2.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.
