File size: 1,956 Bytes
7322f38
 
 
 
 
 
 
 
e53525d
7322f38
 
5276198
7322f38
 
 
 
5276198
7322f38
 
 
 
a1eb356
7322f38
e53525d
 
7322f38
 
e53525d
5276198
 
 
 
 
 
 
34a24ae
e53525d
 
 
34a24ae
e53525d
7322f38
3c9029f
 
7322f38
0ab94df
7322f38
 
 
 
5276198
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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")