hamza2923 commited on
Commit
f5436ef
·
verified ·
1 Parent(s): fc674ec

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pyttsx3
3
+ import os
4
+
5
+ # Initialize the TTS engine
6
+ engine = pyttsx3.init()
7
+
8
+ # Get available voices
9
+ voices = engine.getProperty('voices')
10
+
11
+ # Create a dictionary to map voice names to IDs
12
+ voice_map = {f"{voice.name} ({voice.languages[0] if voice.languages else 'Unknown'})": voice.id for voice in voices}
13
+
14
+ def text_to_speech(text, voice_name, rate=200):
15
+ """
16
+ Convert text to speech with selected voice and rate.
17
+ Saves output as an audio file and returns the file path.
18
+ """
19
+ # Initialize engine for each call to avoid threading issues with Gradio
20
+ engine = pyttsx3.init()
21
+
22
+ # Set voice
23
+ voice_id = voice_map.get(voice_name)
24
+ if not voice_id:
25
+ return "Error: Selected voice not found."
26
+ engine.setProperty('voice', voice_id)
27
+
28
+ # Set speech rate
29
+ engine.setProperty('rate', rate)
30
+
31
+ # Save audio to a file
32
+ output_file = "output.wav"
33
+ engine.save_to_file(text, output_file)
34
+ engine.runAndWait()
35
+
36
+ return output_file
37
+
38
+ # Gradio interface
39
+ with gr.Blocks(title="Text-to-Speech with Different Voices") as demo:
40
+ gr.Markdown("# Text-to-Speech Converter")
41
+ gr.Markdown("Enter text and select a voice to convert it to speech with different voices and accents.")
42
+
43
+ text_input = gr.Textbox(label="Enter Text", placeholder="Type your text here...")
44
+ voice_dropdown = gr.Dropdown(choices=list(voice_map.keys()), label="Select Voice/Accent")
45
+ rate_slider = gr.Slider(minimum=100, maximum=300, value=200, step=10, label="Speech Rate")
46
+
47
+ convert_button = gr.Button("Convert to Speech")
48
+ audio_output = gr.Audio(label="Generated Speech")
49
+
50
+ convert_button.click(
51
+ fn=text_to_speech,
52
+ inputs=[text_input, voice_dropdown, rate_slider],
53
+ outputs=audio_output
54
+ )
55
+
56
+ # Launch the app (commented out for Hugging Face Spaces deployment)
57
+ # demo.launch()
58
+
59
+ if __name__ == "__main__":
60
+ demo.launch()