# StyleTTS2

StyleTTS2 在 LJSpeech 和 LibriTTS 基准测试中获得了高于真实录音的人类评分自然度（MOS 4.55 对比真实 4.23）。它使用 **风格扩散** 和 **对抗训练** 将说话风格建模为潜在变量分布，从而实现富表达的合成并能通过短参考音频片段进行零样本说话人适配。

与传统 TTS 系统不同，StyleTTS2 能够通过短参考音频片段泛化到未见说话人，生成可与专业配音演员相媲美的语音。它已在多个数据集上经过基准测试并超越了人工评分的自然度——这是开源 TTS 的首次突破。

主要功能：

* **接近人类的自然度** — 在 LJSpeech 上超过人类 MOS 分数
* **零样本说话人适配** — 从短音频样本克隆任意声音
* **风格扩散** — 富于表现力、变化的韵律与说话风格
* **多说话人支持** — 在 LibriTTS（2300+ 说话人）上训练
* **轻量推理** — 在消费级 GPU 上高效运行

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

***

## 服务器要求

| 参数       | 最低要求                  | 推荐配置                   |
| -------- | --------------------- | ---------------------- |
| GPU      | NVIDIA RTX 3070（8 GB） | NVIDIA RTX 4090（24 GB） |
| 显存（VRAM） | 6 GB                  | 12–24 GB               |
| 内存（RAM）  | 16 GB                 | 32 GB                  |
| CPU      | 4 个内核                 | 8 个以上内核                |
| 磁盘       | 15 GB                 | 30 GB                  |
| 操作系统     | Ubuntu 20.04+         | Ubuntu 22.04           |
| CUDA     | 11.7+                 | 12.1+                  |
| Python   | 3.8+                  | 3.10                   |
| 端口       | 22, 7860              | 22, 7860               |

{% hint style="info" %}
StyleTTS2 相对轻量——RTX 3070 或 3080 可轻松应对实时推理。对于批处理或并发用户服务，建议使用 4090 或 A100。
{% endhint %}

***

## 在 CLORE.AI 上快速部署

StyleTTS2 需要自定义 Docker 构建，因为没有官方预构建镜像。设置大约需要 \~10 分钟。

### 1. 找到合适的服务器

前往 [CLORE.AI 市场](https://clore.ai/marketplace) 并按以下条件筛选：

* **显存（VRAM）**：≥ 6 GB
* **GPU**：RTX 3070、3080、3090、4080、4090、A100
* **磁盘**：≥ 20 GB

### 2. 配置部署

**Docker 镜像（基础）：**

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

**端口映射：**

```
22   → SSH 访问
7860 → Gradio Web 界面
```

**启动命令：**

```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. 访问界面

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

***

## 逐步设置

### 步骤 1：SSH 登录到你的服务器

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

### 步骤 2：安装系统依赖项

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

### 步骤 3：克隆 StyleTTS2 仓库

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

### 步骤 4：创建 Python 虚拟环境

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

### 步骤 5：安装依赖项

```bash
pip install -r requirements.txt

# 如有需要，安装额外依赖
pip install phonemizer gruut
```

### 步骤 6：下载预训练模型

```bash
# 下载 LJSpeech 模型（单说话人，高质量）
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 模型（多说话人，零样本）
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"
```

### 步骤 7：构建并运行 Dockerfile

```bash
# 创建 Dockerfile
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
```

### 步骤 8：直接启动 Gradio 演示

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

访问地址 `http://<server-ip>:7860`

***

## 使用示例

### 示例 1：通过 Python API 的基本 TTS

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

# 加载配置
config = yaml.safe_load(open("Models/LJSpeech/config.yml"))

# 初始化模型
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)

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

print(f"Model loaded on: {device}")
print(f"VRAM used: {torch.cuda.memory_allocated()/1e9:.2f} GB")
```

***

### 示例 2：零样本语音克隆

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

# 初始化推理引擎
tts = StyleTTS2Inference(
    model_path="Models/LibriTTS/epochs_2nd_00020.pth",
    config_path="Models/LibriTTS/config.yml",
    device="cuda"
)

# 加载参考音频（10–30 秒效果最佳）
reference_audio, sr = torchaudio.load("reference_voice.wav")

# 以参考声音生成语音
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,    # 更高 = 更好质量，但更慢
    embedding_scale=1.5,   # 控制风格强度
    alpha=0.3,             # 声学风格权重
    beta=0.7,              # 韵律风格权重
)

sf.write("cloned_voice_output.wav", audio, 24000)
print("已保存克隆语音输出！")
```

***

### 示例 3：富表达的风格控制

```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."

# 试验不同的风格参数
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"Generated: {filename}")
```

***

### 示例 4：Gradio Web 界面

```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
        # 转换为期望的格式
        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,
    )

    # 保存到临时文件
    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="输入文本", lines=4),
        gr.Audio(label="参考声音（可选）", type="numpy"),
        gr.Slider(1, 30, value=10, label="扩散步数"),
        gr.Slider(0.0, 1.0, value=0.3, label="Alpha（声学风格）"),
        gr.Slider(0.0, 1.0, value=0.7, label="Beta（韵律风格）"),
    ],
    outputs=gr.Audio(label="生成的语音"),
    title="Clore.ai GPU 上的 StyleTTS2",
    description="具有人类级别的风格扩散 TTS"
)

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

***

### 示例 5：批量有声书生成

```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"
)

# 将文本分成段落
book_text = """
第一章：GPU 革命

人工智能的历史无法与图形处理单元的发展分离开来。 
最初作为像素渲染的专用硬件， 
它成为了现代 AI 革命的引擎。

第二章：分布式计算

随着模型变得更大，单 GPU 训练让位于分布式系统。 
像 Clore.ai 这样的平台出现，旨在将这种计算能力民主化， 
使企业级 GPU 基础设施对个人和初创公司也可访问。
""".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"Processing paragraph {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"  ✓ Saved {segment_path}")

# 将所有片段用短静音拼接
silence = np.zeros(int(24000 * 0.5))  # 0.5 秒静音
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"\nComplete audiobook: {len(combined)/24000:.1f} seconds")
```

***

## invokeai.yaml 配置文件

### config.yml 关键参数

```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
```

### 推理参数

| 参数                | 范围      | 默认  | 效果              |
| ----------------- | ------- | --- | --------------- |
| `diffusion_steps` | 1–30    | 10  | 质量与速度的权衡        |
| `alpha`           | 0.0–1.0 | 0.3 | 来自参考的声学风格权重     |
| `beta`            | 0.0–1.0 | 0.7 | 来自参考的韵律风格权重     |
| `embedding_scale` | 1.0–3.0 | 1.5 | 总体风格强度          |
| `t`               | 0.6–1.0 | 0.7 | 噪声水平（更高 = 更多变化） |

***

## 1. 使用 SDXL-Turbo 或 SDXL-Lightning 以实现快速生成

### 1. 优化扩散步数

默认的 10 步在质量和速度之间取得平衡。对于实时应用，使用 5 步；对于最高质量，使用 20–30 步。

```python
# 实时（快速）
audio = tts.synthesize(text, diffusion_steps=5)

# 高质量（慢）
audio = tts.synthesize(text, diffusion_steps=20)
```

### 2. 使用 torch.compile（PyTorch 2.0+）

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

### 3. 混合精度推理

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

### 4. 批量处理多句子

在可能的情况下将多句子一起处理，以最大化 GPU 利用率并减少开销。

### 5. 缓存参考说话人嵌入

```python
# 计算一次，重复使用多次
speaker_embedding = tts.compute_speaker_embedding(reference_audio, sr)

# 在多次发声中重复使用
for text in texts:
    audio = tts.synthesize_with_embedding(text, speaker_embedding)
```

***

## 故障排除

### 问题：未找到 espeak-ng

```bash
apt-get install -y espeak-ng espeak-ng-data
# 验证安装
espeak-ng --version
```

### 问题：Phonemizer 失败

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

### 问题：CUDA 内存不足

```bash
# 减小批量大小或使用 CPU 卸载
export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:256
# 或切换到 FP16
```

### 问题：音频质量差

* 增加 `diffusion_steps` 到 15–20
* 确保参考音频干净，最低 16kHz
* 尝试调整 `alpha` 和 `beta` 参数
* 使用更长的参考音频片段（15–30 秒）

### 问题：从 Hugging Face 下载模型失败

```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 建议

StyleTTS2 是一个轻量模型——LibriTTS 检查点约 \~300MB，即使在较弱的 GPU 上推理也很快。

| GPU       | 显存（VRAM） | Clore.ai 价格 | 推理速度      | 适合用于        |
| --------- | -------- | ----------- | --------- | ----------- |
| 仅 CPU     | —        | ≈$0.02/小时   | \~0.5× 实时 | 开发、测试       |
| RTX 3090  | 24 GB    | \~$0.12/小时  | \~15× 实时  | 生产 API、语音克隆 |
| RTX 4090  | 24 GB    | \~$0.70/小时  | \~25× 实时  | 高并发 API     |
| A100 40GB | 40 GB    | \~$1.20/小时  | \~40× 实时  | 大批量有声书生成    |

{% hint style="info" %}
**RTX 3090 约 $0.12/小时** 对于 StyleTTS2 来说，这是最优选择。模型足够小，你几乎不需要为 GPU 时间付出成本——合成一小时完整音频的 GPU 租用费用低于 $0.01。对于有声书制作或语音克隆服务，这极为高效。
{% endhint %}

**零样本语音克隆质量提示：** 提供 15–30 秒的干净参考音频，采样率为 22kHz 或 24kHz。风格扩散模块需要足够的音频以准确捕捉说话风格、语速和韵律。嘈杂或过短的参考会显著降低输出质量。

***

## 文档

* **GitHub**: <https://github.com/yl4579/StyleTTS2>
* **论文（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>
* **演示空间**: <https://huggingface.co/spaces/styletts2/styletts2>
* **CLORE.AI 市场**: <https://clore.ai/marketplace>
