一直有文本转语音的需要,本地化复制音频实现语言复制的功能也很有兴趣,于是知道了CosyVoice,于是整理了 CosyVoice 的安装部署流程、常见报错排查指南、模型差异说明以及高级功能(声音复刻 + 指令控制)的使用指导,方便后续使用。
一、 安装过程
1. 源码克隆与子模块更新
# 克隆仓库及子模块
git clone --recursive https://github.com/FunAudioLLM/CosyVoice.git
# 进入项目目录
cd CosyVoice
# 若因网络问题导致子模块更新失败,请反复执行以下命令直到成功
git submodule update --init --recursive
2. Conda 环境配置
安装 Conda:请跳转至 Miniconda 官方安装页面 下载并安装。
创建与激活 Conda 环境:
conda create -n cosyvoice -y python=3.10 conda activate cosyvoice安装 Python 依赖包:
pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com系统级 Sox 依赖(如遇到 sox 兼容性问题):
- Ubuntu:
sudo apt-get install sox libsox-dev - CentOS:
sudo yum install sox sox-devel
- Ubuntu:
3. 模型下载
使用 Python SDK (ModelScope) 批量下载所需预训练模型:
# modelscope SDK model download
from modelscope import snapshot_download
snapshot_download('FunAudioLLM/Fun-CosyVoice3-0.5B-2512', local_dir='pretrained_models/Fun-CosyVoice3-0.5B')
snapshot_download('iic/CosyVoice2-0.5B', local_dir='pretrained_models/CosyVoice2-0.5B')
snapshot_download('iic/CosyVoice-300M', local_dir='pretrained_models/CosyVoice-300M')
snapshot_download('iic/CosyVoice-300M-SFT', local_dir='pretrained_models/CosyVoice-300M-SFT')
snapshot_download('iic/CosyVoice-300M-Instruct', local_dir='pretrained_models/CosyVoice-300M-Instruct')
snapshot_download('iic/CosyVoice-ttsfrd', local_dir='pretrained_models/CosyVoice-ttsfrd')
二、 安装常见问题与排错
1. ERROR: Failed to build ‘openai-whisper’ when getting requirements to build wheel
- 问题讨论: CosyVoice Issue #1844
报错日志
Collecting openai-whisper==20231117 (from -r requirements.txt (line 25))
Downloading https://mirrors.aliyun.com/pypi/packages/d2/6e/50ace2bf704e5ffc786d20d96403ab0d57c5d6ab8729de7fed8c436687df/openai-whisper-20231117.tar.gz (798 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
Traceback (most recent call last):
...
File "", line 5, in <module>
ModuleNotFoundError: No module named 'pkg_resources'
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed to build 'openai-whisper' when getting requirements to build wheel
原因分析
最新版本的 setuptools >= 82 不再包含 pkg_resources(详见 setuptools Issue #5174),导致构建 openai-whisper 时找不到依赖模块。
解决方案
指定降低 setuptools 版本并使用 --no-build-isolation 标志单独安装:
pip install "setuptools==81.0.0" -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com
pip install openai-whisper==20231117 --no-build-isolation -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com
2. FileNotFoundError: [WinError 2] 系统找不到指定的文件。
- 问题讨论: CosyVoice Issue #872
报错日志
C:\Users\enigm\miniconda3\envs\cosyvoice\lib\site-packages\pydub\utils.py:198: RuntimeWarning: Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work
Traceback (most recent call last):
File "C:\Users\enigm\miniconda3\envs\cosyvoice\lib\subprocess.py", line 1456, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
现象描述:环境部署成功后,在 WebUI 生成音频阶段报“找不到指定文件”。
解决方案
该报错原因为系统缺失 ffmpeg 音视频工具包。请在 Conda 环境终端中执行:
conda install ffmpeg
三、 模型说明与使用指南
1. 为什么预训练音色选择“中文男”却生成了女声?
在使用 CosyVoice-300M-Instruct 模型时,选择预训练音色“中文男”却输出了女声,这是由于模型定位与推理模式不匹配导致的。
模型特性与机制对比
| 模型类别 | 代表模型 | 支持“预训练音色”模式 | 实现机制与差异分析 |
|---|---|---|---|
| SFT 模型 | CosyVoice-300M-SFT |
支持 | LLM 在训练时输入了说话人嵌入向量(llm_embedding),可精准识别并输出对应的预训练音色(如中文男、中文女)。 |
| Instruct 模型 | CosyVoice-300M-Instruct |
不支持 (输出异常) | 专门用于自然语言指令控制。为避免信息泄漏,其 LLM 训练时完全去除了 llm_embedding,音色与情感完全由指令文本(instruct_text)驱动。 |
[!WARNING] 问题根源:在 WebUI 中使用
Instruct模型强制选择“预训练音色”时,系统会将llm_embedding传入 LLM。因Instruct模型无法识别此输入,导致语言模型生成崩溃并退化为默认的无特征声音(听感通常偏向女声)。
💡 解决办法
方案 A:纯预训练音色使用
将 WebUI 运行模型切换为 SFT 模型:python webui.py --port 50000 --model_dir pretrained_models/CosyVoice-300M-SFT方案 B:Instruct 模型指令控制使用
在使用Instruct模型时,需将 WebUI 推理模式切换为 “自然语言控制”,并在指令框写入具体的音色特征描述(以<|endofprompt|>结尾):极具魅力的成熟男声,声音低沉而有磁性。<|endofprompt|>
2. 模型是否支持“复制声音 + 指令控制”组合生成?
支持!但需要使用二代或三代模型(如 CosyVoice2-0.5B 或 Fun-CosyVoice3-0.5B)。
在初代 CosyVoice-300M 系列中,复刻(Zero-shot)与指令控制(Instruct)分布在不同模型中;而在二代与三代模型中,这两个功能已实现全面融合。
(1) 支持该功能的模型
pretrained_models/CosyVoice2-0.5Bpretrained_models/Fun-CosyVoice3-0.5B
(2) 实现原理与 Python 代码示例
在新版模型中可调用 inference_instruct2 接口,同时传入参考音频(复制声音)与指令文本(控制方言/情感/语速):
# 示例代码(参考 example.py)
import torchaudio
from cosyvoice.cli.cosyvoice import AutoModel
# 1. 加载支持混合模式的模型
cosyvoice = AutoModel(model_dir='pretrained_models/CosyVoice2-0.5B')
# 2. 同时传入:目标文本、控制指令、参考音频(用于复制声音)
for i, j in enumerate(cosyvoice.inference_instruct2(
tts_text='收到好友从远方寄来的生日礼物,那份意外的惊喜与深深的祝福让我心中充满了甜蜜的快乐,笑容如花儿般绽放。',
instruct_text='用四川话说这句话<|endofprompt|>', # 控制指令
prompt_wav='./asset/zero_shot_prompt.wav' # 用于复制声音的参考音频
)):
torchaudio.save('instruct_{}.wav'.format(i), j['tts_speech'], cosyvoice.sample_rate)
(3) 支持的控制指令类型
- 控制口音 / 方言:
"用四川话说这句话<|endofprompt|>""请用广东话表达。<|endofprompt|>"
- 控制语速 / 情感:
"请用尽可能快地语速说一句话。<|endofprompt|>""用开心的语气说。<|endofprompt|>"
- 细粒度情感音效标记:可在合成文本中直接嵌入控制标签,如
[laughter](笑声)、[breath](呼吸声)、[cough](咳嗽声)等。
四、 自定义 webui3.py 实现 Fun-CosyVoice3-0.5B 的运行
参考官方提供的 webui.py,可通过定制化编写 webui3.py 实现 Fun-CosyVoice3-0.5B 模型的高效运行与界面交互。
webui3.py:
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Liu Yue)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import argparse
import gradio as gr
import numpy as np
import torch
import torchaudio
import random
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append("{}/third_party/Matcha-TTS".format(ROOT_DIR))
from cosyvoice.cli.cosyvoice import AutoModel
from cosyvoice.utils.file_utils import logging
from cosyvoice.utils.common import set_all_random_seed
stream_mode_list = [("否", False), ("是", True)]
def generate_seed():
seed = random.randint(1, 100000000)
return {"__type__": "update", "value": seed}
def toggle_details(is_visible):
new_visible = not is_visible
btn_text = "隐藏详情 ⬆️" if new_visible else "显示详情 ⬇️"
return gr.update(visible=new_visible), gr.update(value=btn_text), new_visible
def generate_audio(
tts_text,
active_mode,
prompt_text,
prompt_wav_upload,
prompt_wav_record,
instruct_text,
seed,
stream,
speed,
):
if prompt_wav_upload is not None:
prompt_wav = prompt_wav_upload
elif prompt_wav_record is not None:
prompt_wav = prompt_wav_record
else:
prompt_wav = None
# Validations based on chosen mode
if active_mode == "音色克隆与指令控制":
if prompt_wav is None:
gr.Warning(
"您正在使用音色克隆与指令控制模式,请上传或录制参考音频(prompt音频)!"
)
yield (cosyvoice.sample_rate, default_data)
return
if instruct_text == "":
gr.Warning("您正在使用音色克隆与指令控制模式,请输入instruct指令控制文本!")
yield (cosyvoice.sample_rate, default_data)
return
if not instruct_text.endswith("<|endofprompt|>"):
instruct_text += "<|endofprompt|>"
gr.Info("已检测到您未在指令结尾输入 `<|endofprompt|>`,已自动为您追加。")
if prompt_text != "":
gr.Info("您正在使用音色克隆与指令控制模式,prompt文本会被忽略。")
elif active_mode == "3s极速复刻":
if prompt_wav is None:
gr.Warning("您正在使用3s极速复刻模式,请提供prompt音频!")
yield (cosyvoice.sample_rate, default_data)
return
if prompt_text == "":
gr.Warning("您正在使用3s极速复刻模式,请输入prompt文本!")
yield (cosyvoice.sample_rate, default_data)
return
if instruct_text != "":
gr.Info("您正在使用3s极速复刻模式,instruct指令文本会被忽略。")
elif active_mode == "跨语种复刻":
if prompt_wav is None:
gr.Warning("您正在使用跨语种复刻模式,请提供prompt音频!")
yield (cosyvoice.sample_rate, default_data)
return
if instruct_text != "" or prompt_text != "":
gr.Info("您正在使用跨语种复刻模式,prompt文本和instruct指令文本会被忽略。")
# Common check for prompt wav sample rate
if prompt_wav is not None and active_mode in [
"音色克隆与指令控制",
"3s极速复刻",
"跨语种复刻",
]:
try:
if torchaudio.info(prompt_wav).sample_rate < prompt_sr:
gr.Warning(
"prompt音频采样率{}低于{}".format(
torchaudio.info(prompt_wav).sample_rate, prompt_sr
)
)
except Exception as e:
logging.warning("无法检查参考音频的采样率: {}".format(e))
# Inference execution
if active_mode == "音色克隆与指令控制":
logging.info("get instruct2 (voice clone + language control) inference request")
set_all_random_seed(seed)
for i in cosyvoice.inference_instruct2(
tts_text, instruct_text, prompt_wav, stream=stream, speed=speed
):
yield (cosyvoice.sample_rate, i["tts_speech"].numpy().flatten())
elif active_mode == "3s极速复刻":
logging.info("get zero_shot inference request")
set_all_random_seed(seed)
for i in cosyvoice.inference_zero_shot(
tts_text, prompt_text, prompt_wav, stream=stream, speed=speed
):
yield (cosyvoice.sample_rate, i["tts_speech"].numpy().flatten())
elif active_mode == "跨语种复刻":
logging.info("get cross_lingual inference request")
set_all_random_seed(seed)
for i in cosyvoice.inference_cross_lingual(
tts_text, prompt_wav, stream=stream, speed=speed
):
yield (cosyvoice.sample_rate, i["tts_speech"].numpy().flatten())
def main():
css = """
.gradio-container {
font-family: 'Outfit', 'Segoe UI', -apple-system, sans-serif !important;
max-width: 1050px !important;
margin: 20px auto !important;
background: #ffffff !important;
border: 1px solid #f1f5f9 !important;
border-radius: 16px !important;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.01) !important;
padding: 24px !important;
}
@media (prefers-color-scheme: dark) {
.gradio-container {
background: #0f172a !important;
border-color: #1e293b !important;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1) !important;
}
}
.header-title h3 {
font-weight: 700 !important;
font-size: 28px !important;
color: #1e293b !important;
letter-spacing: -0.5px !important;
}
@media (prefers-color-scheme: dark) {
.header-title h3 {
color: #f8fafc !important;
}
}
/* Gradio Tabs Beautification */
.tab-nav {
border-bottom: 2px solid #f1f5f9 !important;
background: transparent !important;
gap: 4px !important;
margin-bottom: 16px !important;
}
.tab-nav button {
border: none !important;
background: transparent !important;
color: #64748b !important;
font-weight: 500 !important;
padding: 10px 18px !important;
border-bottom: 2px solid transparent !important;
margin-bottom: -2px !important;
transition: all 0.2s ease !important;
border-radius: 0 !important;
font-size: 14.5px !important;
}
.tab-nav button.selected {
color: #2563eb !important;
border-bottom: 2px solid #2563eb !important;
font-weight: 600 !important;
background: transparent !important;
}
.tab-nav button:hover {
color: #2563eb !important;
}
@media (prefers-color-scheme: dark) {
.tab-nav {
border-color: #1e293b !important;
}
.tab-nav button.selected {
color: #3b82f6 !important;
border-bottom-color: #3b82f6 !important;
}
.tab-nav button:hover {
color: #3b82f6 !important;
}
}
/* Custom Tips Card */
.custom-tips {
background-color: transparent !important;
background: transparent !important;
padding: 16px !important;
border-radius: 12px !important;
border-left: 4px solid #2563eb !important;
margin-top: 12px !important;
font-size: 13.5px !important;
line-height: 1.6 !important;
color: #475569 !important;
border-top: none !important;
border-right: none !important;
border-bottom: none !important;
box-shadow: none !important;
}
.custom-tips, .custom-tips * {
background-color: rgb(241, 245, 249) !important;
background: rgb(241, 245, 249) !important;
border-top: none !important;
border-right: none !important;
border-bottom: none !important;
box-shadow: none !important;
}
@media (prefers-color-scheme: dark) {
.custom-tips {
background-color: transparent !important;
background: transparent !important;
color: #cbd5e1 !important;
border-left-color: #3b82f6 !important;
}
}
/* Quick-click tag buttons */
.tag-btn {
background: #f1f5f9 !important;
border: 1px solid #e2e8f0 !important;
border-radius: 20px !important;
font-size: 12px !important;
font-weight: 500 !important;
color: #475569 !important;
padding: 4px 12px !important;
min-width: 60px !important;
box-shadow: none !important;
transition: all 0.2s ease !important;
}
.tag-btn:hover {
background: #2563eb !important;
color: #ffffff !important;
border-color: #2563eb !important;
transform: translateY(-1px) !important;
}
@media (prefers-color-scheme: dark) {
.tag-btn {
background: #334155 !important;
border-color: #475569 !important;
color: #cbd5e1 !important;
}
.tag-btn:hover {
background: #3b82f6 !important;
color: #ffffff !important;
border-color: #3b82f6 !important;
}
}
/* Primary buttons */
.gr-button-primary {
background: #2563eb !important;
border: none !important;
color: white !important;
border-radius: 10px !important;
font-weight: 600 !important;
font-size: 15px !important;
letter-spacing: 0.5px !important;
box-shadow: 0 4px 10px rgba(37, 99, 235, 0.15) !important;
transition: all 0.2s ease !important;
}
.gr-button-primary:hover {
background: #1d4ed8 !important;
box-shadow: 0 6px 14px rgba(37, 99, 235, 0.25) !important;
transform: translateY(-1px) !important;
}
@media (prefers-color-scheme: dark) {
.gr-button-primary {
background: #3b82f6 !important;
box-shadow: 0 4px 10px rgba(59, 130, 246, 0.15) !important;
}
.gr-button-primary:hover {
background: #2563eb !important;
box-shadow: 0 6px 14px rgba(59, 130, 246, 0.25) !important;
}
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown(
"### [CosyVoice2/3](https://github.com/FunAudioLLM/CosyVoice) 智能语音克隆与指令控制系统",
elem_classes=["header-title"],
)
gr.Markdown(
"#### 基于 Gradio 页面美化构建,通过 Tab 控制推理模式,智能隐藏无关属性输入框。"
)
# State components for routing and dynamic tabs
active_mode = gr.Textbox(visible=False, value="音色克隆与指令控制")
# State components for details visibility
instruct_details_visible = gr.State(False)
zero_shot_details_visible = gr.State(False)
cross_lingual_details_visible = gr.State(False)
# Pills/Tabs for selecting mode
with gr.Tabs() as tabs:
with gr.Tab("🎤 音色克隆与指令控制", id=0) as tab_instruct:
with gr.Row():
with gr.Column(scale=8):
gr.Markdown("""**📋 操作步骤**:
1. 选择或录制参考音频(用于克隆音色)。
2. 输入 instruct 描述控制文本(例如控制方言口音、情感、语速等)。
3. 输入合成文本,点击生成语音。""")
with gr.Column(scale=1):
instruct_details_btn = gr.Button("显示详情 ⬇️", size="sm")
instruct_details_box = gr.Markdown(
"""**🔧 API 方法原型与参数**:
* `inference_instruct2(self, tts_text, instruct_text, prompt_wav, stream=False, speed=1.0)`
* `tts_text`:要合成的目标文本。
* `instruct_text`:控制语气、情感、方言等口音 of 描述性文本。
* `prompt_wav`:用于复制音色的参考音频文件。
* `stream` & `speed`:是否开启流式推理与语速调节系数。
**💻 代码调用示例(参考 `example.py`)**:
```python
# 克隆音色的同时,进行语气与语言样式(如广东话)的指令控制
for i, j in enumerate(cosyvoice.inference_instruct2(
tts_text='好少咯,一般系放嗰啲国庆啊,中秋嗰啲可能会咯。',
instruct_text='You are a helpful assistant. 请用广东话表达。<|endofprompt|>',
prompt_wav='./asset/zero_shot_prompt.wav',
stream=False
)):
torchaudio.save('instruct_{}.wav'.format(i), j['tts_speech'], cosyvoice.sample_rate)
```""",
visible=False,
)
with gr.Tab("⚡ 3s极速复刻", id=1) as tab_zero_shot:
with gr.Row():
with gr.Column(scale=8):
gr.Markdown("""**📋 操作步骤**:
1. 选择或录制不超过 30s 的参考音频(建议 3 ~ 10 秒最佳)。
2. 输入参考音频中原本在说哪些字(prompt文本)。
3. 输入合成文本,点击生成语音。""")
with gr.Column(scale=1):
zero_shot_details_btn = gr.Button("显示详情 ⬇️", size="sm")
zero_shot_details_box = gr.Markdown(
"""**🔧 API 方法原型与参数**:
* `inference_zero_shot(self, tts_text, prompt_text, prompt_wav, stream=False, speed=1.0)`
* `tts_text`:要合成的目标文本。
* `prompt_text`:参考音频对应的原文本内容。
* `prompt_wav`:用于复制音色的参考音频文件。
* `stream` & `speed`:是否开启流式推理与语速调节系数。
**💻 代码调用示例(参考 `example.py`)**:
```python
# 利用参考音频及其文本进行快速声音克隆与目标文本合成
for i, j in enumerate(cosyvoice.inference_zero_shot(
tts_text='八百标兵奔北坡,北坡炮兵并排跑,炮兵怕把标兵碰,标兵怕碰炮兵炮。',
prompt_text='You are a helpful assistant.<|endofprompt|>希望你以后能够做的比我还好呦。',
prompt_wav='./asset/zero_shot_prompt.wav',
stream=False
)):
torchaudio.save('zero_shot_{}.wav'.format(i), j['tts_speech'], cosyvoice.sample_rate)
```""",
visible=False,
)
with gr.Tab("🌐 跨语种复刻", id=2) as tab_cross_lingual:
with gr.Row():
with gr.Column(scale=8):
gr.Markdown("""**📋 操作步骤**:
1. 选择或录制不超过 30s 的参考音频。
2. 输入要合成的**不同语种**的目标文本(如参考音频为中文,合成文本为日语)。
3. 点击生成语音。""")
with gr.Column(scale=1):
cross_lingual_details_btn = gr.Button("显示详情 ⬇️", size="sm")
cross_lingual_details_box = gr.Markdown(
"""**🔧 API 方法原型与参数**:
* `inference_cross_lingual(self, tts_text, prompt_wav, stream=False, speed=1.0)`
* `tts_text`:与参考音频不同语种的目标合成文本(可用于实现跨语言克隆)。
* `prompt_wav`:用于复制音色的参考音频文件。
* `stream` & `speed`:是否开启流式推理与语速调节系数。
**💻 代码调用示例(参考 `example.py`)**:
```python
# 使用中文参考音频克隆音色并合成日语文本
for i, j in enumerate(cosyvoice.inference_cross_lingual(
tts_text='You are a helpful assistant.<|endofprompt|>レキシ テキ セカイ ニ オイ テ ワ、カコ ワ タンニ スギサッ タ モノ デ ワ ナイ、プラトン ノ イウ ゴトク ヒ ユー ガ ユー デ ...',
prompt_wav='./asset/zero_shot_prompt.wav',
stream=False
)):
torchaudio.save('japanese_{}.wav'.format(i), j['tts_speech'], cosyvoice.sample_rate)
```""",
visible=False,
)
# Main Layout: 2 columns
with gr.Row():
# Left column: Audio uploading and recording
with gr.Column(scale=1):
with gr.Group():
audio_source = gr.Radio(
choices=["上传参考音频", "录制参考音频"],
value="上传参考音频",
show_label=False,
container=False,
)
prompt_wav_upload = gr.Audio(
sources="upload",
type="filepath",
label="选择 prompt 音频文件(建议采样率不低于 16khz)",
visible=True,
)
prompt_wav_record = gr.Audio(
sources="microphone",
type="filepath",
label="录制 prompt 音频文件",
visible=False,
)
with gr.Group(elem_classes="custom-tips"):
gr.Markdown("""📋 **参考音频指南**:
* 请使用**无背景噪音**的清晰音频。
* **最佳时长**:约 **3 ~ 10 秒** 效果最佳(最长 30s)。
* 请使用与音频实际内容一致的正常语速自然朗读。
* 支持主流格式如 `MP3`, `WAV`, `M4A`, `OGG`。""")
# Right column: Synthesis and extra controls
with gr.Column(scale=1.2):
with gr.Group():
tts_text = gr.Textbox(
label="输入合成文本",
lines=3,
placeholder="请输入要合成的文本内容...",
value="我是通义实验室语音团队全新推出的生成式语音大模型,提供舒适自然的语音合成能力。",
)
prompt_text = gr.Textbox(
label="输入 prompt 文本(仅用于 3s极速复刻)",
lines=1,
placeholder="请输入参考音频对应的文字内容,需与音频一致...",
value="",
visible=False,
)
instruct_text = gr.Textbox(
label="输入 instruct 控制指令",
lines=1,
placeholder="例如: '用四川话说这句话<|endofprompt|>' 或 '温柔女声。<|endofprompt|>'",
value="",
visible=True,
)
with gr.Row(visible=True) as instruct_examples_row:
example_btn1 = gr.Button(
"四川话 🌶️", elem_classes=["tag-btn"], size="sm"
)
example_btn2 = gr.Button(
"广东话 🥟", elem_classes=["tag-btn"], size="sm"
)
example_btn3 = gr.Button(
"东北话 ❄️", elem_classes=["tag-btn"], size="sm"
)
example_btn4 = gr.Button(
"开心 😄", elem_classes=["tag-btn"], size="sm"
)
example_btn5 = gr.Button(
"快速 ⚡", elem_classes=["tag-btn"], size="sm"
)
example_btn6 = gr.Button(
"佩奇 🐷", elem_classes=["tag-btn"], size="sm"
)
with gr.Accordion("💡 语气与情感控制指令指南", open=False):
gr.Markdown("""系统支持在合成文本中插入语气标记,或在指令框输入风格控制词:
* **常用语气/伴随音标记**:可直接插入合成文本或控制指令中:
* `[laughter]` / `<laughter>` / `</laughter>`(笑声)
* `[breath]` / `[quick_breath]`(吸气 / 急促呼吸)
* `[cough]`(咳嗽声) | `[clucking]`(咯咯声) | `[hissing]`(发嘘声)
* `[sigh]`(叹气声) | `[vocalized-noise]`(发声杂音) | `[lipsmack]`(吧唧嘴)
* `[mn]`(嗯/哼等辅助语气) | `[noise]`(环境噪声) | `[accent]`(重音)
* **强调控制**:可用 `<strong>强调内容</strong>` 标记强调整句话中特定的重点词语。
* **指令风格词示例**(直接复制到 instruct 文本框):
* *方言*:`用四川话说这句话<|endofprompt|>` | `请用广东话表达。<|endofprompt|>` | `请用东北话表达。<|endofprompt|>`
* *情感*:`请非常开心地说一句话。<|endofprompt|>` | `请非常伤心地说一句话。<|endofprompt|>` | `请非常生气地说一句话。<|endofprompt|>`
* *音速*:`请用尽可能快地语速说一句话。<|endofprompt|>` | `请用尽可能慢地语速说一句话。<|endofprompt|>`""")
generate_button = gr.Button(
"▶ 生成语音", variant="primary", elem_classes=["gr-button-primary"]
)
audio_output = gr.Audio(
label="合成音频结果", autoplay=True, streaming=True
)
# Advanced Settings Accordion
with gr.Accordion("⚙ 高级参数设置", open=False):
with gr.Row():
stream = gr.Radio(
choices=stream_mode_list,
label="是否流式推理",
value=stream_mode_list[0][1],
)
speed = gr.Number(
value=1.0,
label="速度调节(仅支持非流式推理)",
minimum=0.5,
maximum=2.0,
step=0.1,
)
with gr.Row():
seed = gr.Number(value=0, label="随机推理种子", precision=0)
seed_button = gr.Button(value="🎲 随机种子", scale=0.5)
# Event Handlers
# 1. Switch audio source between uploading and recording
def toggle_audio_source(source):
if source == "上传参考音频":
return gr.update(visible=True), gr.update(visible=False)
else:
return gr.update(visible=False), gr.update(visible=True)
audio_source.change(
fn=toggle_audio_source,
inputs=[audio_source],
outputs=[prompt_wav_upload, prompt_wav_record],
)
# 2. Dynamic visibility changes on Tab selection
def select_instruct():
return (
"音色克隆与指令控制",
gr.update(visible=False),
gr.update(visible=True),
gr.update(visible=True),
)
def select_zero_shot():
return (
"3s极速复刻",
gr.update(visible=True),
gr.update(visible=False),
gr.update(visible=False),
)
def select_cross_lingual():
return (
"跨语种复刻",
gr.update(visible=False),
gr.update(visible=False),
gr.update(visible=False),
)
tab_instruct.select(
fn=select_instruct,
inputs=[],
outputs=[active_mode, prompt_text, instruct_text, instruct_examples_row],
)
tab_zero_shot.select(
fn=select_zero_shot,
inputs=[],
outputs=[active_mode, prompt_text, instruct_text, instruct_examples_row],
)
tab_cross_lingual.select(
fn=select_cross_lingual,
inputs=[],
outputs=[active_mode, prompt_text, instruct_text, instruct_examples_row],
)
# 3. Toggle Details visibility
instruct_details_btn.click(
fn=toggle_details,
inputs=[instruct_details_visible],
outputs=[
instruct_details_box,
instruct_details_btn,
instruct_details_visible,
],
)
zero_shot_details_btn.click(
fn=toggle_details,
inputs=[zero_shot_details_visible],
outputs=[
zero_shot_details_box,
zero_shot_details_btn,
zero_shot_details_visible,
],
)
cross_lingual_details_btn.click(
fn=toggle_details,
inputs=[cross_lingual_details_visible],
outputs=[
cross_lingual_details_box,
cross_lingual_details_btn,
cross_lingual_details_visible,
],
)
# 4. Quick-click examples for instruct_text
example_btn1.click(
fn=lambda: "You are a helpful assistant. 请用四川话表达。<|endofprompt|>",
outputs=instruct_text,
)
example_btn2.click(
fn=lambda: "You are a helpful assistant. 请用广东话表达。<|endofprompt|>",
outputs=instruct_text,
)
example_btn3.click(
fn=lambda: "You are a helpful assistant. 请用东北话表达。<|endofprompt|>",
outputs=instruct_text,
)
example_btn4.click(
fn=lambda: (
"You are a helpful assistant. 请非常开心地说一句话。<|endofprompt|>"
),
outputs=instruct_text,
)
example_btn5.click(
fn=lambda: (
"You are a helpful assistant. 请用尽可能快地语速说一句话。<|endofprompt|>"
),
outputs=instruct_text,
)
example_btn6.click(
fn=lambda: (
"You are a helpful assistant. 我想体验一下小猪佩奇风格,可以吗?<|endofprompt|>"
),
outputs=instruct_text,
)
# 5. Generate seed and generate audio
seed_button.click(generate_seed, inputs=[], outputs=seed)
generate_button.click(
fn=generate_audio,
inputs=[
tts_text,
active_mode,
prompt_text,
prompt_wav_upload,
prompt_wav_record,
instruct_text,
seed,
stream,
speed,
],
outputs=[audio_output],
)
demo.queue(max_size=4, default_concurrency_limit=2)
demo.launch(server_name="0.0.0.0", server_port=args.port)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=50000)
parser.add_argument(
"--model_dir",
type=str,
default="pretrained_models/Fun-CosyVoice3-0.5B",
help="local path or modelscope repo id",
)
args = parser.parse_args()
# Automatically load CosyVoice/CosyVoice2/CosyVoice3
cosyvoice = AutoModel(model_dir=args.model_dir)
prompt_sr = 16000
default_data = np.zeros(cosyvoice.sample_rate)
main()
并争对于windows系统增加bat批处理脚本用于方便双击运行, 注意要使用GBK编码保存:
@echo off
chcp 936 >nul
cd /d "%~dp0"
title CosyVoice WebUI 3
:: 设置端口号变量
set PORT=7777
set /p PORT="请输入 WebUI 运行端口号 (回车默认: 7777): "
echo ===================================================
echo CosyVoice WebUI 3 启动助手 (当前运行端口: %PORT%)
echo ===================================================
echo [1] 使用 Conda 命令行切换环境(支持输入自定义环境名)
echo [2] 直接定位系统内置 Miniconda3 默认路径环境运行
echo ===================================================
set /p opt="请选择启动方式 (输入 1 或 2,默认为 1): "
if "%opt%"=="" set opt=1
if "%opt%"=="2" goto OPTION_DIRECT
:OPTION_CONDA
echo.
set env_name=cosyvoice
set /p env_name="请输入您的 Conda 环境名称 (回车默认: cosyvoice): "
echo.
echo 正在尝试使用 Conda 激活环境 [%env_name%]...
:: 1. 尝试直接使用环境变量中的 conda 命令
where conda >nul 2>nul
if %errorlevel% equ 0 (
call conda activate %env_name% 2>nul
if %errorlevel% equ 0 (
python webui3.py --port %PORT%
goto END
)
)
:: 2. 如果直接调用失败,尝试标准安装位置的激活脚本
if exist "%UserProfile%\miniconda3\Scriptsctivate.bat" (
call "%UserProfile%\miniconda3\Scriptsctivate.bat" %env_name%
python webui3.py --port %PORT%
goto END
) else if exist "%UserProfile%naconda3\Scriptsctivate.bat" (
call "%UserProfile%naconda3\Scriptsctivate.bat" %env_name%
python webui3.py --port %PORT%
goto END
)
echo 警告: 无法自动找到 Conda 安装路径,尝试使用默认 python 执行...
python webui3.py --port %PORT%
goto END
:OPTION_DIRECT
echo.
echo 正在直接定位 %UserProfile%\miniconda3\envs\cosyvoice 环境运行...
if exist "%UserProfile%\miniconda3\envs\cosyvoice\python.exe" (
if exist "%UserProfile%\miniconda3\Scriptsctivate.bat" (
call "%UserProfile%\miniconda3\Scriptsctivate.bat" cosyvoice
)
"%UserProfile%\miniconda3\envs\cosyvoice\python.exe" webui3.py --port %PORT%
) else (
echo 错误: 未能在指定路径找到 Python 运行环境!
echo 请检查路径是否存在: %UserProfile%\miniconda3\envs\cosyvoice\python.exe
)
goto END
:END
echo ===================================================
echo WebUI 服务已结束。
echo ===================================================
pause
网友评论 (0)
暂无评论,快来抢沙发吧~