youngtsai's picture
6
261c7e8
raw
history blame
1.78 kB
import gradio as gr
from gtts import gTTS
import json
def generate_dialogue(rounds, method, role1, role2):
# 這裡只是一個示例,你可能需要更高級的生成方式
if method == "auto":
dialogue = []
for i in range(rounds):
dialogue.append((role1 if i % 2 == 0 else role2, f"自動文本 {i+1}"))
else:
dialogue = [(role1, "手動輸入文本 1"), (role2, "手動輸入文本 2")]
return dialogue
def main_function(rounds: int, method: str, role1: str, role2: str):
dialogue = generate_dialogue(rounds, method, role1, role2)
audio_path = dialogue_to_audio(dialogue)
json_output = json.dumps({"dialogue": dialogue}, ensure_ascii=False, indent=4)
# 儲存對話為 JSON 文件
with open("dialogue_output.json", "w", encoding="utf-8") as f:
f.write(json_output)
return dialogue, audio_path, "dialogue_output.json"
def dialogue_to_audio(dialogue):
text = " ".join([item[1] for item in dialogue])
tts = gTTS(text=text, lang='en')
file_path = "temp_audio.mp3"
tts.save(file_path)
return file_path
if __name__ == "__main__":
gr.Interface(
main_function,
[
gr.components.Slider(minimum=2, maximum=6, step=2, label="對話輪數"),
gr.components.Dropdown(choices=["auto", "manual"], default="auto", label="生成方式"),
gr.components.Textbox(label="角色 1 名稱", default="A"),
gr.components.Textbox(label="角色 2 名稱", default="B"),
],
[
gr.components.Chatbot(label="生成的對話"),
gr.components.Audio(type="filepath", label="對話朗讀"),
gr.components.File(label="下載對話 JSON 文件")
]
).launch()