Spaces:
Runtime error
Runtime error
import gradio as gr | |
from gtts import gTTS | |
import json | |
def generate_dialogue(rounds: int, method: str, role1: str, role2: str) -> list: | |
roles = [role1, role2] | |
dialogue = [] | |
for i in range(rounds): | |
if method == "auto": | |
dialogue.append((roles[i % 2], f"自動文本 {i + 1}")) | |
else: | |
dialogue.append((roles[i % 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) | |
# 將對話格式化為 Chatbot 能接受的格式 | |
formatted_dialogue = [{"role": item[0], "content": item[1]} for item in dialogue] | |
return formatted_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, default=2, label="對話輪數"), | |
gr.components.Dropdown(choices=["auto", "manual"], label="生成方式"), | |
gr.components.Textbox(default="A", label="角色 1 名稱"), | |
gr.components.Textbox(default="B", label="角色 2 名稱"), | |
], | |
[ | |
gr.components.Chatbot(label="生成的對話"), | |
gr.components.Audio(type="filepath", label="對話朗讀"), | |
gr.components.File(label="下載對話 JSON 文件") | |
] | |
).launch() | |