Nymbo's picture
Update app.py
877300f verified
Raw
History Blame Contribute Delete
2.12 kB
import gradio as gr
import os
import tempfile
import time
from openai import OpenAI
def tts(text, model, voice, api_key):
if api_key == '':
raise gr.Error('Please enter your OpenAI API Key')
else:
try:
client = OpenAI(api_key=api_key)
response = client.audio.speech.create(
model=model, # "tts-1","tts-1-hd"
voice=voice, # 'alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'
input=text,
)
except Exception as error:
# Handle any exception that occurs
raise gr.Error("An error occurred while generating speech. Please check your API key and try again.")
print(str(error))
# Create a temp file to save the audio
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:
temp_file.write(response.content)
# Get the file path of the temp file
temp_file_path = temp_file.name
return temp_file_path
with gr.Blocks(theme='Nymbo/Alyx_Theme') as demo:
#gr.Markdown("# <center> Alyxsissy TTS Preview </center>")
#gr.HTML("You can also access the Streaming demo for OpenAI TTS by clicking this <a href='https://huggingface.co/spaces/ysharma/OpenAI_TTS_Streaming'>Gradio demo link</a>")
with gr.Row(variant='panel'):
api_key = gr.Textbox(type='password', label='OpenAI API Key', placeholder='Enter your API key')
model = gr.Dropdown(choices=['tts-1','tts-1-hd'], label='Model', value='tts-1-hd')
voice = gr.Dropdown(choices=['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'], label='Voice', value='nova')
text = gr.Textbox(label="Input Text", placeholder="Enter your text and then click on the button below.")
btn = gr.Button("Run", variant="primary")
output_audio = gr.Audio(label="Speech Output")
text.submit(fn=tts, inputs=[text, model, voice, api_key], outputs=output_audio, api_name="tts_enter_key", concurrency_limit=None)
btn.click(fn=tts, inputs=[text, model, voice, api_key], outputs=output_audio, api_name="tts_button", concurrency_limit=None)
demo.launch()