CosyVoice icon indicating copy to clipboard operation
CosyVoice copied to clipboard

调用 gradio api 报错:httpx.HTTPStatusError: Client error '403 Forbidden'

Open smallpize opened this issue 1 year ago • 1 comments

Describe the bug 更新版本后,调用 gradio api 报错:httpx.HTTPStatusError: Client error '403 Forbidden' 在 webUI 上,合成声音后,点击下载无反应

编写一个简短的脚本:

from gradio_client import Client, file

client = Client("http://localhost:7860/")
result = client.predict(
                tts_text="我是通义实验室语音团队全新推出的生成式语音大模型,提供舒适自然的语音合成能力。",
                prompt_wav_upload=None,  # 或使用本地文件路径
                prompt_wav_record=None,  # 或使用本地文件路径
                mode_checkbox_group="预训练音色",
                sft_dropdown="中文女",
                api_name="/generate_audio"
)
print(result)

执行报错:

Loaded as API: http://localhost:7860/ ✔
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    result = client.predict(
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/gradio_client/client.py", line 469, in predict
    return self.submit(
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/gradio_client/client.py", line 1513, in result
    return super().result(timeout=timeout)
  File "/anaconda/envs/cosyvoice/lib/python3.8/concurrent/futures/_base.py", line 444, in result
    return self.__get_result()
  File "/anaconda/envs/cosyvoice/lib/python3.8/concurrent/futures/_base.py", line 389, in __get_result
    raise self._exception
  File "/anaconda/envs/cosyvoice/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/gradio_client/client.py", line 1124, in _inner
    predictions = self.process_predictions(*predictions)
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/gradio_client/client.py", line 1298, in process_predictions
    predictions = self.download_files(*predictions)
  File "/anaconda/envs/cosyvoice/lib/python3.8
/site-packages/gradio_client/client.py", line 1311, in download_files
    data_ = utils.traverse(data_, self._download_file, utils.is_file_obj)
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/gradio_client/utils.py", line 984, in traverse
    new_obj.append(traverse(item, func, is_root))
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/gradio_client/utils.py", line 975, in traverse
    return func(json_obj)
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/gradio_client/client.py", line 1397, in _download_file
    response.raise_for_status()
  File "/anaconda/envs/cosyvoice/lib/python3.8/site-packages/httpx/_models.py", line 763, in raise_for_status
    raise HTTPStatusError(message, request=request, response=self)
httpx.HTTPStatusError: Client error '403 Forbidden' for url 'http://localhost:7860/file=072a68ec-e557-4a3f-8892-21744a40dfd6/139670860235056/21'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403

smallpize avatar Oct 11 '24 17:10 smallpize

找到问题了,修改webUI:

原代码:audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=True)

修改为:audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False)

smallpize avatar Oct 14 '24 08:10 smallpize

gr.Audio 组件的 streaming=True 时,通常会导致无法下载音频文件。这是由于以下原因:

  1. 流式音频的工作原理: 当 streaming=True 时,音频数据是以小块(chunks)的形式逐步传输的,而不是作为一个完整的文件。这种方式允许音频在生成的同时就开始播放,提供了更快的响应体验。

  2. 缺少完整文件: 由于音频是流式传输的,在播放过程中并没有生成一个完整的音频文件。这就意味着没有一个单一的、完整的文件可供下载。

  3. Gradio 的限制: Gradio 的 Audio 组件在流式模式下主要是为了实时播放而设计的,而不是为了提供下载功能。

  4. 浏览器限制: 浏览器通常需要完整的音频文件才能提供下载功能。

解决方案:

  1. 禁用流式传输: 如果下载功能对您的应用很重要,可以将 streaming 设置为 False

    audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False)
    

    这样会生成一个完整的音频文件,可以下载,但可能会增加首次播放的延迟。

  2. 双重输出: 您可以考虑使用两个音频输出组件,一个用于流式播放,另一个用于下载:

    audio_stream = gr.Audio(label="合成音频(流式播放)", autoplay=True, streaming=True)
    audio_download = gr.Audio(label="下载音频", streaming=False)
    
  3. 自定义下载按钮: 您可以实现一个自定义的下载功能,在流式传输完成后生成一个可下载的文件。

  4. 使用其他组件: 考虑使用 gr.File 组件来提供下载功能,同时保留 gr.Audio 用于流式播放。

  5. 后端处理: 在后端完成音频生成后,将完整的音频文件保存下来,然后提供一个下载链接。

选择哪种方法取决于您的具体需求和应用场景。如果即时播放和下载都很重要,可能需要结合使用上述的一些方法。

设置了 audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False) 。但是通过gradio API 调用的时候语音分成了多个文件地址

这个问题实际上不是由 generate_audio 函数的实现有关:

  1. 生成器函数的影响: 您的 generate_audio 函数是一个生成器函数(使用 yield 语句)。这意味着它不是一次性返回完整的音频,而是分段返回音频数据。

  2. Gradio的处理方式: 当 Gradio 处理一个生成器函数的输出时,它会为每个 yield 的值创建一个单独的输出。在 API 调用中,这表现为多个文件地址。

  3. streaming=False 的影响: 即使设置了 streaming=False,Gradio 仍然会处理生成器函数的每个输出。这就是为什么会返回多个文件地址。

  4. API 调用的行为: 在 API 调用中,Gradio 会返回函数每次 yield 的结果,而不是等待所有数据生成后合并为一个文件。

解决方案:

  1. 修改生成函数: 如果您希望在 API 调用中只返回一个完整的音频文件,您需要修改 generate_audio 函数,使其一次性返回完整的音频数据,而不是使用 yield。例如:

    def generate_audio(...):
        # ... 前面的代码保持不变 ...
    
        full_audio = []
        if mode_checkbox_group == '预训练音色':
            for i in cosyvoice.inference_sft(...):
                full_audio.append(i['tts_speech'].numpy().flatten())
        # ... 其他模式同理 ...
    
        return (target_sr, np.concatenate(full_audio))
    
  2. 使用两个不同的函数: 一个用于 Web 界面的流式输出,另一个用于 API 调用的完整输出。

  3. 在 API 端合并音频: 如果您需要保持当前的生成器函数不变,可以考虑在 API 调用端合并接收到的多个音频片段。

  4. 使用自定义组件: 创建一个自定义的 Gradio 组件,专门处理您的音频生成方式。

  5. 后处理: 在生成完所有音频片段后,将它们合并成一个文件,然后返回这个合并后的文件。

选择哪种方法取决于您的具体需求和应用场景。如果您主要关注 API 调用的行为,修改 generate_audio 函数以一次性返回完整音频可能是最直接的解决方案。如果您需要同时支持流式 Web 界面和单一文件 API 输出,可能需要实现两个不同的处理路径。

smallpize avatar Oct 16 '24 06:10 smallpize

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] avatar Nov 16 '24 02:11 github-actions[bot]

gr.Audio 组件的 streaming=True 时,通常会导致无法下载音频文件。这是由于以下原因:

  1. 流式音频的工作原理: 当 streaming=True 时,音频数据是以小块(chunks)的形式逐步传输的,而不是作为一个完整的文件。这种方式允许音频在生成的同时就开始播放,提供了更快的响应体验。
  2. 缺少完整文件: 由于音频是流式传输的,在播放过程中并没有生成一个完整的音频文件。这就意味着没有一个单一的、完整的文件可供下载。
  3. Gradio 的限制: Gradio 的 Audio 组件在流式模式下主要是为了实时播放而设计的,而不是为了提供下载功能。
  4. 浏览器限制: 浏览器通常需要完整的音频文件才能提供下载功能。

解决方案:

  1. 禁用流式传输: 如果下载功能对您的应用很重要,可以将 streaming 设置为 False

    audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False)
    

    这样会生成一个完整的音频文件,可以下载,但可能会增加首次播放的延迟。

  2. 双重输出: 您可以考虑使用两个音频输出组件,一个用于流式播放,另一个用于下载:

    audio_stream = gr.Audio(label="合成音频(流式播放)", autoplay=True, streaming=True)
    audio_download = gr.Audio(label="下载音频", streaming=False)
    
  3. 自定义下载按钮: 您可以实现一个自定义的下载功能,在流式传输完成后生成一个可下载的文件。

  4. 使用其他组件: 考虑使用 gr.File 组件来提供下载功能,同时保留 gr.Audio 用于流式播放。

  5. 后端处理: 在后端完成音频生成后,将完整的音频文件保存下来,然后提供一个下载链接。

选择哪种方法取决于您的具体需求和应用场景。如果即时播放和下载都很重要,可能需要结合使用上述的一些方法。

设置了 audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False) 。但是通过gradio API 调用的时候语音分成了多个文件地址

这个问题实际上不是由 generate_audio 函数的实现有关:

  1. 生成器函数的影响: 您的 generate_audio 函数是一个生成器函数(使用 yield 语句)。这意味着它不是一次性返回完整的音频,而是分段返回音频数据。
  2. Gradio的处理方式: 当 Gradio 处理一个生成器函数的输出时,它会为每个 yield 的值创建一个单独的输出。在 API 调用中,这表现为多个文件地址。
  3. streaming=False 的影响: 即使设置了 streaming=False,Gradio 仍然会处理生成器函数的每个输出。这就是为什么会返回多个文件地址。
  4. API 调用的行为: 在 API 调用中,Gradio 会返回函数每次 yield 的结果,而不是等待所有数据生成后合并为一个文件。

解决方案:

  1. 修改生成函数: 如果您希望在 API 调用中只返回一个完整的音频文件,您需要修改 generate_audio 函数,使其一次性返回完整的音频数据,而不是使用 yield。例如:
    def generate_audio(...):
        # ... 前面的代码保持不变 ...
    
        full_audio = []
        if mode_checkbox_group == '预训练音色':
            for i in cosyvoice.inference_sft(...):
                full_audio.append(i['tts_speech'].numpy().flatten())
        # ... 其他模式同理 ...
    
        return (target_sr, np.concatenate(full_audio))
    
  2. 使用两个不同的函数: 一个用于 Web 界面的流式输出,另一个用于 API 调用的完整输出。
  3. 在 API 端合并音频: 如果您需要保持当前的生成器函数不变,可以考虑在 API 调用端合并接收到的多个音频片段。
  4. 使用自定义组件: 创建一个自定义的 Gradio 组件,专门处理您的音频生成方式。
  5. 后处理: 在生成完所有音频片段后,将它们合并成一个文件,然后返回这个合并后的文件。

选择哪种方法取决于您的具体需求和应用场景。如果您主要关注 API 调用的行为,修改 generate_audio 函数以一次性返回完整音频可能是最直接的解决方案。如果您需要同时支持流式 Web 界面和单一文件 API 输出,可能需要实现两个不同的处理路径。

谢谢

xy3xy3 avatar Nov 21 '24 13:11 xy3xy3

我的解决方案:按照上面的修改了组件+自动保存到outpu文件夹 webui.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
import librosa
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append('{}/third_party/Matcha-TTS'.format(ROOT_DIR))
from cosyvoice.cli.cosyvoice import CosyVoice
from cosyvoice.utils.file_utils import load_wav, logging
from cosyvoice.utils.common import set_all_random_seed
import datetime


inference_mode_list = ['预训练音色', '3s极速复刻', '跨语种复刻', '自然语言控制']
instruct_dict = {'预训练音色': '1. 选择预训练音色\n2. 点击生成音频按钮',
                 '3s极速复刻': '1. 选择prompt音频文件,或录入prompt音频,注意不超过30s,若同时提供,优先选择prompt音频文件\n2. 输入prompt文本\n3. 点击生成音频按钮',
                 '跨语种复刻': '1. 选择prompt音频文件,或录入prompt音频,注意不超过30s,若同时提供,优先选择prompt音频文件\n2. 点击生成音频按钮',
                 '自然语言控制': '1. 选择预训练音色\n2. 输入instruct文本\n3. 点击生成音频按钮'}
stream_mode_list = [('否', False), ('是', True)]
max_val = 0.8


def generate_seed():
    seed = random.randint(1, 100000000)
    return {
        "__type__": "update",
        "value": seed
    }


def postprocess(speech, top_db=60, hop_length=220, win_length=440):
    speech, _ = librosa.effects.trim(
        speech, top_db=top_db,
        frame_length=win_length,
        hop_length=hop_length
    )
    if speech.abs().max() > max_val:
        speech = speech / speech.abs().max() * max_val
    speech = torch.concat([speech, torch.zeros(1, int(target_sr * 0.2))], dim=1)
    return speech


def change_instruction(mode_checkbox_group):
    return instruct_dict[mode_checkbox_group]


def generate_audio(tts_text, mode_checkbox_group, sft_dropdown, 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
    # if instruct mode, please make sure that model is iic/CosyVoice-300M-Instruct and not cross_lingual mode
    if mode_checkbox_group in ['自然语言控制']:
        if cosyvoice.frontend.instruct is False:
            gr.Warning('您正在使用自然语言控制模式, {}模型不支持此模式, 请使用iic/CosyVoice-300M-Instruct模型'.format(args.model_dir))
            yield (target_sr, default_data)
        if instruct_text == '':
            gr.Warning('您正在使用自然语言控制模式, 请输入instruct文本')
            yield (target_sr, default_data)
        if prompt_wav is not None or prompt_text != '':
            gr.Info('您正在使用自然语言控制模式, prompt音频/prompt文本会被忽略')
    # if cross_lingual mode, please make sure that model is iic/CosyVoice-300M and tts_text prompt_text are different language
    if mode_checkbox_group in ['跨语种复刻']:
        if cosyvoice.frontend.instruct is True:
            gr.Warning('您正在使用跨语种复刻模式, {}模型不支持此模式, 请使用iic/CosyVoice-300M模型'.format(args.model_dir))
            yield (target_sr, default_data)
        if instruct_text != '':
            gr.Info('您正在使用跨语种复刻模式, instruct文本会被忽略')
        if prompt_wav is None:
            gr.Warning('您正在使用跨语种复刻模式, 请提供prompt音频')
            yield (target_sr, default_data)
        gr.Info('您正在使用跨语种复刻模式, 请确保合成文本和prompt文本为不同语言')
    # if in zero_shot cross_lingual, please make sure that prompt_text and prompt_wav meets requirements
    if mode_checkbox_group in ['3s极速复刻', '跨语种复刻']:
        if prompt_wav is None:
            gr.Warning('prompt音频为空,您是否忘记输入prompt音频?')
            yield (target_sr, default_data)
        if torchaudio.info(prompt_wav).sample_rate < prompt_sr:
            gr.Warning('prompt音频采样率{}低于{}'.format(torchaudio.info(prompt_wav).sample_rate, prompt_sr))
            yield (target_sr, default_data)
    # sft mode only use sft_dropdown
    if mode_checkbox_group in ['预训练音色']:
        if instruct_text != '' or prompt_wav is not None or prompt_text != '':
            gr.Info('您正在使用预训练音色模式,prompt文本/prompt音频/instruct文本会被忽略!')
    # zero_shot mode only use prompt_wav prompt text
    if mode_checkbox_group in ['3s极速复刻']:
        if prompt_text == '':
            gr.Warning('prompt文本为空,您是否忘记输入prompt文本?')
            yield (target_sr, default_data)
        if instruct_text != '':
            gr.Info('您正在使用3s极速复刻模式,预训练音色/instruct文本会被忽略!')

    if mode_checkbox_group == '预训练音色':
        logging.info('get sft inference request')
        set_all_random_seed(seed)
        full_audio = []
        for i in cosyvoice.inference_sft(tts_text, sft_dropdown, stream=stream, speed=speed):
            full_audio.append(i['tts_speech'].numpy().flatten())
        generated_audio = np.concatenate(full_audio)

        # 保存文件
        output_dir = './output'
        os.makedirs(output_dir, exist_ok=True)  # 创建目录,如果不存在
        timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')  # 获取当前时间戳
        output_file = os.path.join(output_dir, f'generated_audio_{timestamp}.wav')

        # 使用 librosa 保存音频
        torchaudio.save(output_file, torch.tensor(generated_audio).unsqueeze(0), target_sr)
        logging.info(f'Audio saved to {output_file}')

        return (target_sr, generated_audio)
    elif mode_checkbox_group == '3s极速复刻':
        logging.info('get zero_shot inference request')
        prompt_speech_16k = postprocess(load_wav(prompt_wav, prompt_sr))
        set_all_random_seed(seed)
        outaudio = None
        for i in cosyvoice.inference_zero_shot(tts_text, prompt_text, prompt_speech_16k, stream=stream, speed=speed):
            audio = i['tts_speech'].numpy().flatten()
            if outaudio is None:
                outaudio = audio
            else:
                outaudio = np.concatenate([outaudio, audio])
            yield (target_sr, i['tts_speech'].numpy().flatten())
    elif mode_checkbox_group == '跨语种复刻':
        logging.info('get cross_lingual inference request')
        prompt_speech_16k = postprocess(load_wav(prompt_wav, prompt_sr))
        set_all_random_seed(seed)
        for i in cosyvoice.inference_cross_lingual(tts_text, prompt_speech_16k, stream=stream, speed=speed):
            yield (target_sr, i['tts_speech'].numpy().flatten())
    else:
        logging.info('get instruct inference request')
        set_all_random_seed(seed)
        for i in cosyvoice.inference_instruct(tts_text, sft_dropdown, instruct_text, stream=stream, speed=speed):
            yield (target_sr, i['tts_speech'].numpy().flatten())


def main():
    with gr.Blocks() as demo:
        gr.Markdown("### 代码库 [CosyVoice](https://github.com/FunAudioLLM/CosyVoice) \
                    预训练模型 [CosyVoice-300M](https://www.modelscope.cn/models/iic/CosyVoice-300M) \
                    [CosyVoice-300M-Instruct](https://www.modelscope.cn/models/iic/CosyVoice-300M-Instruct) \
                    [CosyVoice-300M-SFT](https://www.modelscope.cn/models/iic/CosyVoice-300M-SFT)")
        gr.Markdown("#### 请输入需要合成的文本,选择推理模式,并按照提示步骤进行操作")

        tts_text = gr.Textbox(label="输入合成文本", lines=1, value="我是通义实验室语音团队全新推出的生成式语音大模型,提供舒适自然的语音合成能力。")
        with gr.Row():
            mode_checkbox_group = gr.Radio(choices=inference_mode_list, label='选择推理模式', value=inference_mode_list[0])
            instruction_text = gr.Text(label="操作步骤", value=instruct_dict[inference_mode_list[0]], scale=0.5)
            sft_dropdown = gr.Dropdown(choices=sft_spk, label='选择预训练音色', value=sft_spk[0], scale=0.25)
            stream = gr.Radio(choices=stream_mode_list, label='是否流式推理', value=stream_mode_list[0][1])
            speed = gr.Number(value=1, label="速度调节(仅支持非流式推理)", minimum=0.5, maximum=2.0, step=0.1)
            with gr.Column(scale=0.25):
                seed_button = gr.Button(value="\U0001F3B2")
                seed = gr.Number(value=0, label="随机推理种子")

        with gr.Row():
            prompt_wav_upload = gr.Audio(sources='upload', type='filepath', label='选择prompt音频文件,注意采样率不低于16khz')
            prompt_wav_record = gr.Audio(sources='microphone', type='filepath', label='录制prompt音频文件')
        prompt_text = gr.Textbox(label="输入prompt文本", lines=1, placeholder="请输入prompt文本,需与prompt音频内容一致,暂时不支持自动识别...", value='')
        instruct_text = gr.Textbox(label="输入instruct文本", lines=1, placeholder="请输入instruct文本.", value='')

        generate_button = gr.Button("生成音频")

        audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False)


        seed_button.click(generate_seed, inputs=[], outputs=seed)
        generate_button.click(generate_audio,
                              inputs=[tts_text, mode_checkbox_group, sft_dropdown, prompt_text, prompt_wav_upload, prompt_wav_record, instruct_text,
                                      seed, stream, speed],
                              outputs=[audio_output])
        mode_checkbox_group.change(fn=change_instruction, inputs=[mode_checkbox_group], outputs=[instruction_text])
    demo.queue(max_size=4, default_concurrency_limit=2)
    demo.launch(server_name='0.0.0.0', server_port=args.port, share=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port',
                        type=int,
                        default=8000)
    parser.add_argument('--model_dir',
                        type=str,
                        default='pretrained_models/CosyVoice-300M',
                        help='local path or modelscope repo id')
    args = parser.parse_args()
    cosyvoice = CosyVoice(args.model_dir)
    sft_spk = cosyvoice.list_avaliable_spks()
    prompt_sr, target_sr = 16000, 22050
    default_data = np.zeros(target_sr)
    main()

xy3xy3 avatar Nov 21 '24 13:11 xy3xy3

我的解决方案:按照上面的修改了组件+自动保存到outpu文件夹 webui.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
import librosa
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append('{}/third_party/Matcha-TTS'.format(ROOT_DIR))
from cosyvoice.cli.cosyvoice import CosyVoice
from cosyvoice.utils.file_utils import load_wav, logging
from cosyvoice.utils.common import set_all_random_seed
import datetime


inference_mode_list = ['预训练音色', '3s极速复刻', '跨语种复刻', '自然语言控制']
instruct_dict = {'预训练音色': '1. 选择预训练音色\n2. 点击生成音频按钮',
                 '3s极速复刻': '1. 选择prompt音频文件,或录入prompt音频,注意不超过30s,若同时提供,优先选择prompt音频文件\n2. 输入prompt文本\n3. 点击生成音频按钮',
                 '跨语种复刻': '1. 选择prompt音频文件,或录入prompt音频,注意不超过30s,若同时提供,优先选择prompt音频文件\n2. 点击生成音频按钮',
                 '自然语言控制': '1. 选择预训练音色\n2. 输入instruct文本\n3. 点击生成音频按钮'}
stream_mode_list = [('否', False), ('是', True)]
max_val = 0.8


def generate_seed():
    seed = random.randint(1, 100000000)
    return {
        "__type__": "update",
        "value": seed
    }


def postprocess(speech, top_db=60, hop_length=220, win_length=440):
    speech, _ = librosa.effects.trim(
        speech, top_db=top_db,
        frame_length=win_length,
        hop_length=hop_length
    )
    if speech.abs().max() > max_val:
        speech = speech / speech.abs().max() * max_val
    speech = torch.concat([speech, torch.zeros(1, int(target_sr * 0.2))], dim=1)
    return speech


def change_instruction(mode_checkbox_group):
    return instruct_dict[mode_checkbox_group]


def generate_audio(tts_text, mode_checkbox_group, sft_dropdown, 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
    # if instruct mode, please make sure that model is iic/CosyVoice-300M-Instruct and not cross_lingual mode
    if mode_checkbox_group in ['自然语言控制']:
        if cosyvoice.frontend.instruct is False:
            gr.Warning('您正在使用自然语言控制模式, {}模型不支持此模式, 请使用iic/CosyVoice-300M-Instruct模型'.format(args.model_dir))
            yield (target_sr, default_data)
        if instruct_text == '':
            gr.Warning('您正在使用自然语言控制模式, 请输入instruct文本')
            yield (target_sr, default_data)
        if prompt_wav is not None or prompt_text != '':
            gr.Info('您正在使用自然语言控制模式, prompt音频/prompt文本会被忽略')
    # if cross_lingual mode, please make sure that model is iic/CosyVoice-300M and tts_text prompt_text are different language
    if mode_checkbox_group in ['跨语种复刻']:
        if cosyvoice.frontend.instruct is True:
            gr.Warning('您正在使用跨语种复刻模式, {}模型不支持此模式, 请使用iic/CosyVoice-300M模型'.format(args.model_dir))
            yield (target_sr, default_data)
        if instruct_text != '':
            gr.Info('您正在使用跨语种复刻模式, instruct文本会被忽略')
        if prompt_wav is None:
            gr.Warning('您正在使用跨语种复刻模式, 请提供prompt音频')
            yield (target_sr, default_data)
        gr.Info('您正在使用跨语种复刻模式, 请确保合成文本和prompt文本为不同语言')
    # if in zero_shot cross_lingual, please make sure that prompt_text and prompt_wav meets requirements
    if mode_checkbox_group in ['3s极速复刻', '跨语种复刻']:
        if prompt_wav is None:
            gr.Warning('prompt音频为空,您是否忘记输入prompt音频?')
            yield (target_sr, default_data)
        if torchaudio.info(prompt_wav).sample_rate < prompt_sr:
            gr.Warning('prompt音频采样率{}低于{}'.format(torchaudio.info(prompt_wav).sample_rate, prompt_sr))
            yield (target_sr, default_data)
    # sft mode only use sft_dropdown
    if mode_checkbox_group in ['预训练音色']:
        if instruct_text != '' or prompt_wav is not None or prompt_text != '':
            gr.Info('您正在使用预训练音色模式,prompt文本/prompt音频/instruct文本会被忽略!')
    # zero_shot mode only use prompt_wav prompt text
    if mode_checkbox_group in ['3s极速复刻']:
        if prompt_text == '':
            gr.Warning('prompt文本为空,您是否忘记输入prompt文本?')
            yield (target_sr, default_data)
        if instruct_text != '':
            gr.Info('您正在使用3s极速复刻模式,预训练音色/instruct文本会被忽略!')

    if mode_checkbox_group == '预训练音色':
        logging.info('get sft inference request')
        set_all_random_seed(seed)
        full_audio = []
        for i in cosyvoice.inference_sft(tts_text, sft_dropdown, stream=stream, speed=speed):
            full_audio.append(i['tts_speech'].numpy().flatten())
        generated_audio = np.concatenate(full_audio)

        # 保存文件
        output_dir = './output'
        os.makedirs(output_dir, exist_ok=True)  # 创建目录,如果不存在
        timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')  # 获取当前时间戳
        output_file = os.path.join(output_dir, f'generated_audio_{timestamp}.wav')

        # 使用 librosa 保存音频
        torchaudio.save(output_file, torch.tensor(generated_audio).unsqueeze(0), target_sr)
        logging.info(f'Audio saved to {output_file}')

        return (target_sr, generated_audio)
    elif mode_checkbox_group == '3s极速复刻':
        logging.info('get zero_shot inference request')
        prompt_speech_16k = postprocess(load_wav(prompt_wav, prompt_sr))
        set_all_random_seed(seed)
        outaudio = None
        for i in cosyvoice.inference_zero_shot(tts_text, prompt_text, prompt_speech_16k, stream=stream, speed=speed):
            audio = i['tts_speech'].numpy().flatten()
            if outaudio is None:
                outaudio = audio
            else:
                outaudio = np.concatenate([outaudio, audio])
            yield (target_sr, i['tts_speech'].numpy().flatten())
    elif mode_checkbox_group == '跨语种复刻':
        logging.info('get cross_lingual inference request')
        prompt_speech_16k = postprocess(load_wav(prompt_wav, prompt_sr))
        set_all_random_seed(seed)
        for i in cosyvoice.inference_cross_lingual(tts_text, prompt_speech_16k, stream=stream, speed=speed):
            yield (target_sr, i['tts_speech'].numpy().flatten())
    else:
        logging.info('get instruct inference request')
        set_all_random_seed(seed)
        for i in cosyvoice.inference_instruct(tts_text, sft_dropdown, instruct_text, stream=stream, speed=speed):
            yield (target_sr, i['tts_speech'].numpy().flatten())


def main():
    with gr.Blocks() as demo:
        gr.Markdown("### 代码库 [CosyVoice](https://github.com/FunAudioLLM/CosyVoice) \
                    预训练模型 [CosyVoice-300M](https://www.modelscope.cn/models/iic/CosyVoice-300M) \
                    [CosyVoice-300M-Instruct](https://www.modelscope.cn/models/iic/CosyVoice-300M-Instruct) \
                    [CosyVoice-300M-SFT](https://www.modelscope.cn/models/iic/CosyVoice-300M-SFT)")
        gr.Markdown("#### 请输入需要合成的文本,选择推理模式,并按照提示步骤进行操作")

        tts_text = gr.Textbox(label="输入合成文本", lines=1, value="我是通义实验室语音团队全新推出的生成式语音大模型,提供舒适自然的语音合成能力。")
        with gr.Row():
            mode_checkbox_group = gr.Radio(choices=inference_mode_list, label='选择推理模式', value=inference_mode_list[0])
            instruction_text = gr.Text(label="操作步骤", value=instruct_dict[inference_mode_list[0]], scale=0.5)
            sft_dropdown = gr.Dropdown(choices=sft_spk, label='选择预训练音色', value=sft_spk[0], scale=0.25)
            stream = gr.Radio(choices=stream_mode_list, label='是否流式推理', value=stream_mode_list[0][1])
            speed = gr.Number(value=1, label="速度调节(仅支持非流式推理)", minimum=0.5, maximum=2.0, step=0.1)
            with gr.Column(scale=0.25):
                seed_button = gr.Button(value="\U0001F3B2")
                seed = gr.Number(value=0, label="随机推理种子")

        with gr.Row():
            prompt_wav_upload = gr.Audio(sources='upload', type='filepath', label='选择prompt音频文件,注意采样率不低于16khz')
            prompt_wav_record = gr.Audio(sources='microphone', type='filepath', label='录制prompt音频文件')
        prompt_text = gr.Textbox(label="输入prompt文本", lines=1, placeholder="请输入prompt文本,需与prompt音频内容一致,暂时不支持自动识别...", value='')
        instruct_text = gr.Textbox(label="输入instruct文本", lines=1, placeholder="请输入instruct文本.", value='')

        generate_button = gr.Button("生成音频")

        audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False)


        seed_button.click(generate_seed, inputs=[], outputs=seed)
        generate_button.click(generate_audio,
                              inputs=[tts_text, mode_checkbox_group, sft_dropdown, prompt_text, prompt_wav_upload, prompt_wav_record, instruct_text,
                                      seed, stream, speed],
                              outputs=[audio_output])
        mode_checkbox_group.change(fn=change_instruction, inputs=[mode_checkbox_group], outputs=[instruction_text])
    demo.queue(max_size=4, default_concurrency_limit=2)
    demo.launch(server_name='0.0.0.0', server_port=args.port, share=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port',
                        type=int,
                        default=8000)
    parser.add_argument('--model_dir',
                        type=str,
                        default='pretrained_models/CosyVoice-300M',
                        help='local path or modelscope repo id')
    args = parser.parse_args()
    cosyvoice = CosyVoice(args.model_dir)
    sft_spk = cosyvoice.list_avaliable_spks()
    prompt_sr, target_sr = 16000, 22050
    default_data = np.zeros(target_sr)
    main()

我使用时发现22050的 target_sr 合成音频频率整体降低,需要将 target_sr 设为 cosyvoice.sample_rate 才能无偏生成

JesseM1024 avatar Jan 10 '25 17:01 JesseM1024

Great. the code I changed here:

pan2za avatar Aug 04 '25 03:08 pan2za

    outaudio = None
    for i in cosyvoice.inference_zero_shot(tts_text, prompt_text, prompt_speech_16k, stream=stream, speed=speed):
        audio = i['tts_speech'].numpy().flatten()
        if outaudio is None:
            outaudio = audio
        else:
            outaudio = np.concatenate([outaudio, audio])
    yield (cosyvoice.sample_rate, outaudio)

pan2za avatar Aug 04 '25 03:08 pan2za

also, streaming is False. audio_output = gr.Audio(label="合成音频", autoplay=True, streaming=False)

pan2za avatar Aug 04 '25 03:08 pan2za