import os import tempfile from openai import OpenAI from tts_voice import tts_order_voice import edge_tts import numpy as np import anyio import torch import torchaudio import gradio as gr from scipy.io import wavfile from scipy.io.wavfile import write #新加内容 import asyncio import threading import requests from aiohttp import ClientSession # # 异步函数进行预加载 # async def fetch_link_content(url): # async with ClientSession() as session: # async with session.get(url) as response: # return await response.text() # # 后台任务确保不阻塞主线程 # def fetch_link_in_background(url): # loop = asyncio.new_event_loop() # asyncio.set_event_loop(loop) # content = loop.run_until_complete(fetch_link_content(url)) # # 将 content 缓存起来或者在全局状态中保存以供后续使用 # print("预加载的内容:", content) # link_url = "https://huggingface.co/api/spaces/by-subdomain/zxsipola123456-tts" # background_thread = threading.Thread(target=fetch_link_in_background, args=(link_url,)) # background_thread.start() # 创建 KNN-VC 模型 knn_vc = torch.hub.load('bshall/knn-vc', 'knn_vc', prematched=True, trust_repo=True, pretrained=True, device='cpu') # 初始化 language_dict language_dict = tts_order_voice # 异步文字转语音函数 async def text_to_speech_edge(text, language_code): voice = language_dict[language_code] communicate = edge_tts.Communicate(text, voice) with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: tmp_path = tmp_file.name await communicate.save(tmp_path) return "语音合成完成:{}".format(text), tmp_path def voice_change(audio_in, audio_ref): samplerate1, data1 = wavfile.read(audio_in) samplerate2, data2 = wavfile.read(audio_ref) with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_audio_in, \ tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_audio_ref: audio_in_path = tmp_audio_in.name audio_ref_path = tmp_audio_ref.name write(audio_in_path, samplerate1, data1) write(audio_ref_path, samplerate2, data2) query_seq = knn_vc.get_features(audio_in_path) matching_set = knn_vc.get_matching_set([audio_ref_path]) out_wav = knn_vc.match(query_seq, matching_set, topk=4) output_path = 'output.wav' torchaudio.save(output_path, out_wav[None], 16000) return output_path # #验证中转api key是否有效 # def validate_api_key(api_proxy_key): # try: # client = OpenAI(api_key=api_proxy_key, base_url='https://lmzh.top/v1') # # 测试调用一个简单的API来验证Key # response = client.models.list() # return True # except Exception: # return False # # 更新Edge TTS标签页状态的函数 # def update_edge_tts_tab(api_proxy_key): # is_valid = validate_api_key(api_proxy_key) # return gr.update(interactive=is_valid) # 文字转语音(OpenAI) def tts(text, model, voice, api_key): if len(text) > 300: raise gr.Error('您输入的文本字符多于300个,请缩短您的文本') if api_key == '': raise gr.Error('请填写您的 中转API Key') try: client = OpenAI(api_key=api_key, base_url='https://lmzh.top/v1') response = client.audio.speech.create( model=model, voice=voice, input=text, ) except Exception as error: raise gr.Error(f"生成语音时出错:{error}") with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file: temp_file.write(response.content) temp_file_path = temp_file.name return temp_file_path def tts1(text, model, voice, api_key): if len(text)>300: raise gr.Error('您输入的文本字符多于300个,请缩短您的文本') if api_key == '': raise gr.Error('Please enter your OpenAI API Key') else: try: client = OpenAI(api_key=api_key) response = client.audio.speech.create( model=model, # "tts-1","tts-1-hd" voice=voice, # 'alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer' input=text, ) except Exception as error: # Handle any exception that occurs raise gr.Error("An error occurred while generating speech. Please check your API key and try again.") print(str(error)) # Create a temp file to save the audio with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file: temp_file.write(response.content) # Get the file path of the temp file temp_file_path = temp_file.name return temp_file_path # Gradio 前端设计 app = gr.Blocks(title="TTS文本生成语音 + AI秒变声") with app: gr.Markdown("#