zhutyler21/OpenAI_TTS_New
0
1import gradio as gr2import os3import tempfile4from openai import OpenAI5 6 7def tts(text, model, voice, api_key):8 if api_key == '':9 raise gr.Error('Please enter your OpenAI API Key')10 else:11 try:12 client = OpenAI(api_key=api_key)13 14 response = client.audio.speech.create(15 model=model, # "tts-1","tts-1-hd"16 voice=voice, # 'alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'17 input=text,18 )19 20 except Exception as error:21 # Handle any exception that occurs22 raise gr.Error("An error occurred while generating speech. Please check your API key and try again.")23 print(str(error))24 25 # Create a temp file to save the audio26 with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:27 temp_file.write(response.content)28 29 # Get the file path of the temp file30 temp_file_path = temp_file.name31 32 return temp_file_path33 34 35with gr.Blocks() as demo:36 gr.Markdown("# <center> OpenAI Text-To-Speech API with Gradio </center>")37 #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>")38 with gr.Row(variant='panel'):39 api_key = gr.Textbox(type='password', label='OpenAI API Key', placeholder='Enter your API key to access the TTS demo')40 model = gr.Dropdown(choices=['tts-1','tts-1-hd'], label='Model', value='tts-1')41 voice = gr.Dropdown(choices=['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'], label='Voice Options', value='alloy')42 43 text = gr.Textbox(label="Input text", placeholder="Enter your text and then click on the 'Text-To-Speech' button, or simply press the Enter key.")44 btn = gr.Button("Text-To-Speech")45 output_audio = gr.Audio(label="Speech Output")46 47 text.submit(fn=tts, inputs=[text, model, voice, api_key], outputs=output_audio, api_name="tts_enter_key", concurrency_limit=None)48 btn.click(fn=tts, inputs=[text, model, voice, api_key], outputs=output_audio, api_name="tts_button", concurrency_limit=None)49 50demo.launch()