| import tempfile |
| import asyncio |
| from pydub import AudioSegment |
| import edge_tts |
| import gradio as gr |
|
|
| |
| language_dict = { |
| "Persian": { |
| "Dilara (Female)": "fa-IR-DilaraNeural", |
| "Farid (Male)": "fa-IR-FaridNeural" |
| } |
| } |
|
|
| |
| async def tts_dialogue_persian(dialogue_text): |
| lines = dialogue_text.strip().split("\n") |
| audio_segments = [] |
|
|
| for line in lines: |
| if ':' not in line: |
| continue |
| speaker, text = line.split(":", 1) |
| text = text.strip() |
|
|
| |
| if "زن" in speaker: |
| voice = language_dict["Persian"]["Dilara (Female)"] |
| else: |
| voice = language_dict["Persian"]["Farid (Male)"] |
|
|
| communicate = edge_tts.Communicate(text, voice) |
|
|
| |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: |
| tmp_path = tmp_file.name |
| await communicate.save(tmp_path) |
| segment = AudioSegment.from_file(tmp_path) |
| audio_segments.append(segment) |
|
|
| |
| if audio_segments: |
| final_audio = sum(audio_segments) |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file: |
| final_path = tmp_file.name |
| final_audio.export(final_path, format="mp3") |
| return final_path |
| else: |
| return None |
|
|
| |
| def tts_dialogue_wrapper(dialogue_text): |
| return asyncio.run(tts_dialogue_persian(dialogue_text)) |
|
|
| |
| with gr.Blocks(title="Persian TTS Dialogue") as demo: |
| gr.HTML("<center><h1>Persian TTS Dialogue (Edge TTS)</h1></center>") |
| gr.Markdown("Use 'زن:' and 'مرد:' as prefixes for lines to select voice.") |
|
|
| with gr.Row(): |
| with gr.Column(): |
| input_text = gr.Textbox( |
| lines=10, |
| label="Input Dialogue", |
| placeholder="مرد: سلام\nزن: سلام، خوبی؟" |
| ) |
| run_btn = gr.Button(value="Generate Audio", variant="primary") |
|
|
| with gr.Column(): |
| output_audio = gr.Audio(type="filepath", label="Generated Dialogue") |
|
|
| run_btn.click(tts_dialogue_wrapper, inputs=[input_text], outputs=[output_audio]) |
|
|
| if __name__ == "__main__": |
| demo.queue().launch(share=True) |