Urain/OpenAI_TTS_New
2
1import gradio as gr2import os3import tempfile4from openai import OpenAI5import requests6import json7 8def create_header(api_key):9 return {10 'Authorization': f'Bearer {api_key}',11 'Content-Type': 'application/json'12 }13 14def tts(text, model, voice, api_key,url,speed):15 if api_key == '':16 raise gr.Error('Please enter your OpenAI API Key')17 else:18 try:19 headers = create_header(api_key)20 url = url21 input_text = text22 query = {23 "model":model,24 "input":input_text,25 "voice":voice,26 "response_format":"mp3",27 "speed":speed,28 }29 response = requests.post(url=url, data=json.dumps(query), headers=headers)30 except Exception as error:31 # Handle any exception that occurs32 raise gr.Error("An error occurred while generating speech. Please check your API key and try again.")33 print(str(error))34 35 # Create a temp file to save the audio36 with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:37 temp_file.write(response.content)38 39 # Get the file path of the temp file40 temp_file_path = temp_file.name41 42 return temp_file_path43 44 45with gr.Blocks() as demo:46 gr.Markdown("# <center> OpenAI Text-To-Speech API with Gradio </center>")47 gr.Markdown("This demo uses the OpenAI Text-To-Speech API to generate speech from text. You get free API key from https://faucet.openkey.cloud/")48 #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>")49 with gr.Row(variant='panel'):50 api_key = gr.Textbox(type='password', label='OpenAI API Key', placeholder='Enter your API key to access the TTS demo')51 model = gr.Dropdown(choices=['tts-1','tts-1-hd'], label='Model', value='tts-1-hd')52 voice = gr.Dropdown(choices=['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'], label='Voice Options', value='nova')53 url = gr.Textbox(label="URL", placeholder="Enter your URL and then click on the 'Text-To-Speech' button, or simply press the Enter key.", value='https://openkey.cloud/v1/audio/speech')54 #新增一个speed,数字滑块从0.25值4,默认是155 speed = gr.Slider(label="Speed", minimum=0.25, maximum=4, step=0.25, value=1) 56 57 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.")58 btn = gr.Button("Text-To-Speech")59 output_audio = gr.Audio(label="Speech Output")60 61 text.submit(fn=tts, inputs=[text, model, voice, api_key,url,speed], outputs=output_audio, api_name="tts_enter_key", concurrency_limit=None)62 btn.click(fn=tts, inputs=[text, model, voice, api_key,url,speed], outputs=output_audio, api_name="tts_button", concurrency_limit=None)63 64demo.launch()