Spaces:
Running
Running
import gradio as gr | |
from gtts import gTTS | |
from nltk import tokenize | |
import os | |
# Import necessary nltk libraries | |
import nltk | |
nltk.download('punkt') | |
# Global variable to store sentences and the entire text | |
sentences = [] | |
full_text = "" | |
# Function to process text and generate sentence options | |
def process_text(mytext): | |
global sentences, full_text | |
full_text = mytext | |
sentences = tokenize.sent_tokenize(mytext) | |
choices = ["Play the whole text"] + [f"{i + 1}. {s}" for i, s in enumerate(sentences)] | |
return choices | |
# Function to generate audio for the selected item | |
def generate_audio(selected_item): | |
global full_text | |
if not selected_item: | |
return None | |
if selected_item == "Play the whole text": | |
tts = gTTS(text=full_text, lang='en') | |
audio_path = 'full_text.mp3' | |
tts.save(audio_path) | |
return audio_path | |
index = int(selected_item.split('.')[0]) - 1 # Adjust for 0-based index | |
if 0 <= index < len(sentences): | |
sentence = sentences[index] | |
tts = gTTS(text=sentence, lang='en') | |
audio_path = f'sentence_{index + 1}.mp3' | |
tts.save(audio_path) | |
return audio_path | |
else: | |
return None | |
# Function to update dropdown choices based on text input | |
def update_dropdown(mytext): | |
choices = process_text(mytext) | |
return gr.update(choices=choices) | |
# Create a Gradio Blocks app | |
with gr.Blocks() as app: | |
with gr.Row(): | |
textbox = gr.Textbox(label="Enter your text here") | |
with gr.Row(): | |
submit_button = gr.Button("Submit") | |
with gr.Row(): | |
dropdown = gr.Dropdown(choices=[], label="Select Sentence") | |
with gr.Row(): | |
audio_output = gr.Audio(label="Audio of Selected Sentence") | |
submit_button.click(fn=update_dropdown, inputs=textbox, outputs=dropdown) | |
dropdown.change(fn=generate_audio, inputs=dropdown, outputs=audio_output) | |
app.launch(share=True) | |