Spaces:
Runtime error
Runtime error
import gradio as gr | |
from gtts import gTTS | |
import json | |
def generate_dialogue(rounds, method, role1, role2): | |
if method == "auto": | |
dialogue = [{"role": role1 if i % 2 == 0 else role2, "content": f"自動文本 {i+1}"} for i in range(rounds)] | |
else: | |
dialogue = [{"role": role1, "content": "手動輸入文本 1"}, {"role": role2, "content": "手動輸入文本 2"}] | |
return dialogue | |
def main_function(rounds: int, method: str, role1: str, role2: str): | |
structured_dialogue = generate_dialogue(rounds, method, role1, role2) | |
chatbot_dialogue = structured_dialogue | |
audio_path = dialogue_to_audio(structured_dialogue) | |
json_output = json.dumps({"dialogue": structured_dialogue}, ensure_ascii=False, indent=4) | |
# 儲存對話為 JSON 文件 | |
file_name = "dialogue_output.txt" | |
with open(file_name, "w", encoding="utf-8") as f: | |
f.write(json_output) | |
return chatbot_dialogue, audio_path, file_name | |
def dialogue_to_audio(dialogue): | |
text = " ".join([f"{item['role']}: {item['content']}" for item in dialogue]) | |
tts = gTTS(text=text, lang='zh-tw') | |
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"], label="生成方式"), | |
gr.components.Textbox(label="角色 1 名稱"), | |
gr.components.Textbox(label="角色 2 名稱"), | |
], | |
[ | |
gr.components.Chatbot(label="生成的對話"), | |
gr.components.Audio(type="filepath", label="對話朗讀"), | |
gr.components.File(label="下載對話 JSON 文件") | |
] | |
).launch() | |