import gradio as gr import os import tempfile from openai import OpenAI # Set an environment variable for key os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY') client = OpenAI() # add api_key # Updated tts function now takes model and voice as parameters def tts(text, model, voice): # <-- Change here: added model and voice as parameters response = client.audio.speech.create( model=model, # <-- Change here: using the model parameter voice=voice, # <-- Change here: using the voice parameter input=text, ) # 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() as demo: gr.Markdown("#
OpenAI Text-To-Speech API with Gradio
") with gr.Row(): dd1 = gr.Dropdown(choices=['tts-1', 'tts-1-hd'], label='Model') dd2 = gr.Dropdown(choices=['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'], label='Voice Options') text = gr.Textbox(label="Input text") btn = gr.Button("Text-To-Speech") output_audio = gr.Audio(label="Speech Output") # Updated btn.click to pass model and voice parameters to the tts function btn.click(fn=tts, inputs=[text, dd1, dd2], outputs=output_audio, api_name="tts") # <-- Change here: added dd1 and dd2 to inputs demo.launch()