the-walking-fish commited on
Commit
7322f38
·
verified ·
1 Parent(s): 666d65f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tts_voice import tts_order_voice
2
+ import edge_tts
3
+ import gradio as gr
4
+ import tempfile
5
+ import anyio
6
+ import ffmpeg
7
+ import os
8
+ import glob
9
+ import time
10
+
11
+ language_dict = tts_order_voice
12
+
13
+ async def text_to_speech_edge(text, language_code):
14
+ voice = language_dict[language_code]
15
+ communicate = edge_tts.Communicate(text, voice)
16
+
17
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
18
+ tmp_path = tmp_file.name
19
+
20
+ await communicate.save(tmp_path)
21
+
22
+ new_temp_path = tmp_path.replace(".mp3", ".wav")
23
+ (
24
+ ffmpeg.input(tmp_path)
25
+ .output(new_temp_path)
26
+ .run()
27
+ )
28
+
29
+ # 清理原始的 MP3 臨時文件
30
+ os.remove(tmp_path)
31
+
32
+ return new_temp_path
33
+
34
+ async def cleanup_temp_files(interval=3600):
35
+ while True:
36
+ await anyio.sleep(interval)
37
+ temp_dir = tempfile.gettempdir()
38
+ now = time.time()
39
+
40
+ # 刪除過期的臨時文件
41
+ for temp_file in glob.glob(os.path.join(temp_dir, "*.wav")):
42
+ if os.path.isfile(temp_file) and now - os.path.getmtime(temp_file) > interval:
43
+ os.remove(temp_file)
44
+
45
+ input_text = gr.inputs.Textbox(lines=5, label="輸入文本")
46
+ output_audio = gr.outputs.Audio(type="filepath", label="導出文件")
47
+ default_language = list(language_dict.keys())[287]
48
+ language = gr.inputs.Dropdown(choices=list(language_dict.keys()), default=default_language, label="語言")
49
+
50
+ interface = gr.Interface(fn=text_to_speech_edge, inputs=[input_text, language], outputs=[output_audio], title="Edge TTS 文字轉語音")
51
+
52
+ async def main():
53
+ async with anyio.create_task_group() as task_group:
54
+ await task_group.spawn(interface.launch, backend="asyncio")
55
+ await task_group.spawn(cleanup_temp_files, interval=3600) # 每隔1小時清理一次臨時文件
56
+
57
+ if __name__ == "__main__":
58
+ anyio.run(main)