cro-ime / app.py
thak123's picture
Update app.py
c0da4ca verified
from gtts import gTTS
import gradio as gr
import os
import pygame
import random
# Function to convert text to speech and save as an audio file
def text_to_speech(text, language="hr"):
# Create a gTTS object
tts = gTTS(text=text, lang=language, slow=False)
# Save the audio file
audio_file = "output.mp3"
tts.save(audio_file)
return audio_file
# Gradio interface
def tts_demo(text, language="hr"):
# Convert text to speech
audio_file = text_to_speech(text, language)
# Return the audio file to be played in the Gradio interface
return audio_file
# # Define Gradio inputs and outputs
# inputs = [
# gr.Textbox(label="Enter Text", placeholder="Type something here..."),
# gr.Dropdown(label="Language", choices=["en", "es", "fr", "de", "hr"], value="hr")
# ]
# outputs = gr.Audio(label="Generated Audio", type="filepath")
# # Create the Gradio interface
# iface = gr.Interface(
# fn=tts_demo,
# inputs=inputs,
# outputs=outputs,
# title="Text-to-Speech Demo",
# description="Enter text and select a language to generate and play audio."
# )
# # Launch the app
# iface.launch()
def select_and_speak(state):
if not state:
return "", "No names provided.", []
names_list = state
names_list = names_list.split("\n")
if not names_list:
return "", "List is empty. Please reset.", []
selected_name = random.choice(names_list)
names_list.remove(selected_name)
tts_demo(selected_name)
# engine.say(selected_name)
# engine.runAndWait()
play_sound()
return names_list, selected_name
def play_sound():
pygame.mixer.init()
pygame.mixer.music.load("output.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
# Remove the temporary audio file
os.remove("output.mp3")
# return "<audio autoplay><source src='output.mp3' type='audio/mp3'></audio>"
def reset_names(names):
return names.split('\n')
demo = gr.Interface(
fn=select_and_speak,
inputs=["text"],
outputs=[gr.Textbox(label="Remaining Names"), gr.Textbox(label="Selected Name")],
title="Random Name Selector and Speaker",
description="Enter a list of names separated by newlines in the 'Reset' tab to start.",
)
# reset_demo = gr.Interface(
# fn=reset_names,
# inputs=[gr.Textbox(label="List of Names (separated by newline)")],
# title="Reset Names",
# description="Enter new list of names here to reset the app.",
# )
if __name__ == "__main__":
demo.launch()
# reset_demo.launch()