Spaces:
Running
Running
import gradio as gr | |
import tempfile | |
import openai | |
import requests | |
def tts(input_text: str, model: str, voice: str, api_key: str) -> str: | |
""" | |
Convert input text to speech using OpenAI's Text-to-Speech API. | |
Parameters: | |
input_text (str): The text to be converted to speech. | |
model (str): The model to use for synthesis (e.g., 'tts-1', 'tts-1-hd'). | |
voice (str): The voice profile to use (e.g., 'alloy', 'echo', 'fable', etc.). | |
api_key (str): OpenAI API key. | |
Returns: | |
str: File path to the generated audio file. | |
Raises: | |
gr.Error: If input parameters are invalid or API call fails. | |
""" | |
if not api_key.strip(): | |
raise gr.Error( | |
"API key is required. Get an API key at: https://platform.openai.com/account/api-keys" | |
) | |
if not input_text.strip(): | |
raise gr.Error("Input text cannot be empty.") | |
openai.api_key = api_key | |
try: | |
response = openai.Audio.create(text=input_text, voice=voice, model=model) | |
except openai.OpenAIError as e: | |
# Catch-all for OpenAI exceptions | |
raise gr.Error(f"An OpenAI error occurred: {e}") | |
except Exception as e: | |
# Catch any other exceptions | |
raise gr.Error(f"An unexpected error occurred: {e}") | |
if not hasattr(response, "audio"): | |
raise gr.Error( | |
"Invalid response from OpenAI API. The response does not contain audio content." | |
) | |
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file: | |
temp_file.write(response.audio) | |
temp_file_path = temp_file.name | |
return temp_file_path | |
def main(): | |
""" | |
Main function to create and launch the Gradio interface. | |
""" | |
MODEL_OPTIONS = ["tts-1", "tts-1-hd"] | |
VOICE_OPTIONS = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"] | |
# Predefine voice previews URLs | |
VOICE_PREVIEWS = { | |
voice: f"https://cdn.openai.com/API/docs/audio/{voice}.wav" | |
for voice in VOICE_OPTIONS | |
} | |
with gr.Blocks() as demo: | |
with gr.Row(): | |
with gr.Column(scale=1): | |
api_key_input = gr.Textbox( | |
label="OpenAI API Key", | |
info="https://platform.openai.com/account/api-keys", | |
type="password", | |
placeholder="Enter your OpenAI API Key", | |
) | |
model_dropdown = gr.Dropdown( | |
choices=MODEL_OPTIONS, label="Model", value="tts-1" | |
) | |
voice_dropdown = gr.Dropdown( | |
choices=VOICE_OPTIONS, label="Voice Options", value="echo" | |
) | |
# Add voice previews using HTML for minimal audio interface | |
gr.Markdown("### Voice Previews") | |
for voice in VOICE_OPTIONS: | |
audio_url = VOICE_PREVIEWS[voice] | |
# Create an HTML audio player with minimal controls | |
html_snippet = f''' | |
<div style="margin-bottom: 10px;"> | |
<p><strong>{voice.capitalize()}</strong></p> | |
<audio controls style="width: 100%;"> | |
<source src="{audio_url}" type="audio/wav"> | |
Your browser does not support the audio element. | |
</audio> | |
</div> | |
''' | |
gr.HTML(html_snippet) | |
with gr.Column(scale=2): | |
input_textbox = gr.Textbox( | |
label="Input Text", lines=10, placeholder="Type your text here..." | |
) | |
submit_button = gr.Button( | |
"Convert Text to Speech", variant="primary" | |
) | |
with gr.Column(scale=1): | |
output_audio = gr.Audio(label="Output Audio") | |
# Define the event handler for the submit button with error handling | |
def on_submit(input_text, model, voice, api_key): | |
audio_file = tts(input_text, model, voice, api_key) | |
return audio_file | |
# Trigger the conversion when the submit button is clicked | |
submit_button.click( | |
fn=on_submit, | |
inputs=[input_textbox, model_dropdown, voice_dropdown, api_key_input], | |
outputs=output_audio, | |
) | |
# Launch the Gradio app with error display enabled | |
demo.launch(show_error=True) | |
if __name__ == "__main__": | |
main() | |