Spaces:
Sleeping
Sleeping
from tts_voice import tts_order_voice | |
import edge_tts | |
import gradio as gr | |
import tempfile | |
import anyio | |
import ffmpeg | |
import os | |
import time | |
import threading | |
language_dict = tts_order_voice | |
temp_file_prefix = "edge_tts_" | |
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", prefix=temp_file_prefix) as tmp_file: | |
tmp_path = tmp_file.name | |
await communicate.save(tmp_path) | |
return tmp_path | |
def cleanup_temp_files(temp_dir, max_age_seconds=3600): | |
"""定期清理超過 max_age_seconds 的臨時文件""" | |
while True: | |
now = time.time() | |
for filename in os.listdir(temp_dir): | |
if filename.startswith(temp_file_prefix): # 只清理特定前綴的文件 | |
file_path = os.path.join(temp_dir, filename) | |
if os.path.isfile(file_path): | |
file_age = now - os.path.getmtime(file_path) | |
if file_age > max_age_seconds: | |
os.remove(file_path) | |
print(f"已刪除過期的臨時文件: {file_path}") | |
time.sleep(600) # 每隔10分鐘時執行一次清理 | |
# 啟動清理臨時文件的線程 | |
tempfile_tempdir = tempfile.gettempdir() | |
cleanup_thread = threading.Thread(target=cleanup_temp_files, args=(tempfile_tempdir,3600), daemon=True) | |
cleanup_thread.start() | |
input_text = gr.Textbox(lines=5, label="輸入文本") | |
output_audio = gr.Audio(type="filepath", label="導出文件") | |
default_language = list(language_dict.keys())[287] | |
language = gr.Dropdown(choices=list(language_dict.keys()), value=default_language, label="語言") | |
interface = gr.Interface(fn=text_to_speech_edge, inputs=[input_text, language], outputs=[output_audio], title="Edge TTS 文字轉語音") | |
if __name__ == "__main__": | |
anyio.run(interface.launch, backend="asyncio") |