> 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-zh/yin-pin-yu-yu-yin/styletss2.md).

# StyleTTS2

在 Clore.ai GPU 上通过风格扩散运行接近人类水平的 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） |
| 显存     | 6 GB                  | 12–24 GB               |
| 内存     | 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) 并按以下条件筛选：

* **显存**：≥ 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 UI
```

**启动命令：**

```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"模型已加载到：{device}")
print(f"已使用 VRAM：{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 为 AI 应用提供强大的 GPU 基础设施，包括文本转语音合成。"

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 = "欢迎来到我们关于使用 Clore.ai 进行 GPU 计算的演示。"

# 试验不同的风格参数
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"已生成：{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"正在处理段落 {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"  ✓ 已保存 {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"\n完整有声书：{len(combined)/24000:.1f} 秒")
```

***

## 配置

### 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. 优化扩散步数

默认的 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       | 显存    | Clore.ai 价格                       | 推理速度      | 最适合         |
| --------- | ----- | --------------------------------- | --------- | ----------- |
| 仅 CPU     | —     | 约 $0.02/小时                        | 约 0.5× 实时 | 开发、测试       |
| RTX 3090  | 24 GB | $0.07–0.21/小时                     | 约 15× 实时  | 生产 API、声音克隆 |
| RTX 4090  | 24 GB | $0.14–0.42/小时                     | 约 25× 实时  | 高并发 API     |
| A100 40GB | 40 GB | [裸机](https://clore.ai/bare-metal) | 约 40× 实时  | 大批量有声书生成    |

{% hint style="info" %}
**每小时 0.07–0.21 美元的 RTX 3090** 是 StyleTTS2 的最佳选择。该模型足够小，GPU 时间成本几乎可以忽略不计——合成 1 小时音频的 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>


---

# 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, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yin-pin-yu-yu-yin/styletss2.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
