phehvn commited on
Commit
d78e18f
·
verified ·
1 Parent(s): b4f2a47

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -0
app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import tempfile
4
+ import re
5
+ from pydub import AudioSegment # Library to combine audio files
6
+ from openai import OpenAI
7
+
8
+ # Max character limit per API request
9
+ MAX_CHAR_LIMIT = 140964096
10
+
11
+ def clean_text(text):
12
+ # Replace newlines with spaces and multiple spaces with a single space
13
+ cleaned_text = re.sub(r'\s+', ' ', text.strip()) # Replace multiple spaces and newlines with a single space
14
+ return cleaned_text
15
+
16
+ def split_text(text, limit=MAX_CHAR_LIMIT):
17
+ # Split text into chunks of <= MAX_CHAR_LIMIT characters
18
+ words = text.split(' ')
19
+ chunks = []
20
+ current_chunk = ""
21
+
22
+ for word in words:
23
+ # Add words to the current chunk without exceeding the character limit
24
+ if len(current_chunk) + len(word) + 1 <= limit: # +1 for space
25
+ current_chunk += word + " "
26
+ else:
27
+ chunks.append(current_chunk.strip()) # Append the current chunk
28
+ current_chunk = word + " " # Start a new chunk
29
+
30
+ if current_chunk:
31
+ chunks.append(current_chunk.strip()) # Add the last chunk
32
+
33
+ return chunks
34
+
35
+ def tts(text, model, voice, speed, api_key, base_url):
36
+ if api_key == '':
37
+ raise gr.Error('Please enter your Key')
38
+
39
+ cleaned_text = clean_text(text)
40
+ chunks = split_text(cleaned_text)
41
+
42
+ audio_segments = []
43
+
44
+ try:
45
+ client = OpenAI(api_key=api_key, base_url=base_url+'/v1') # Use selected base_url
46
+
47
+ # Process each chunk of text
48
+ for chunk in chunks:
49
+ response = client.audio.speech.create(
50
+ model=model, # "tts-1", "tts-1-hd"
51
+ voice=voice, # 'alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'
52
+ input=chunk,
53
+ speed=speed
54
+ )
55
+
56
+ # Create a temp file to save the audio for each chunk
57
+ with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:
58
+ temp_file.write(response.content)
59
+ temp_file_path = temp_file.name
60
+ audio_segments.append(AudioSegment.from_mp3(temp_file_path))
61
+
62
+ except Exception as error:
63
+ raise gr.Error("An error occurred while generating speech. Please check your API key and try again.")
64
+
65
+ # Concatenate all audio chunks into one final audio file
66
+ final_audio = sum(audio_segments)
67
+
68
+ # Save the concatenated audio to a final file
69
+ with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as final_temp_file:
70
+ final_audio.export(final_temp_file.name, format="mp3")
71
+ final_audio_path = final_temp_file.name
72
+
73
+ return final_audio_path
74
+
75
+
76
+ with gr.Blocks() as demo:
77
+ gr.Markdown("# <center> OpenAI TTS </center>")
78
+ with gr.Row(variant='panel'):
79
+ api_key = gr.Textbox(type='password', label='OpenAI API Key', placeholder='sk-sAqNNgs8VZyi8DHY4a37D44eBc3d408e96D40116Da679376')
80
+ model = gr.Dropdown(choices=['tts-1', 'tts-1-hd'], label='Model', value='tts-1')
81
+ voice = gr.Dropdown(choices=['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer'], label='Voice Options', value='alloy')
82
+ speed = gr.Slider(minimum=0.5, maximum=2.0, step=0.1, label="Speed", value=1.0)
83
+ # Add dropdown for URL selection
84
+ base_url = gr.Dropdown(choices=['https://api.hakai.shop', 'https://api.keyai.shop','https://open.keyai.shop','https://api.openai.com' ], label="API Endpoint", value='https://api.keyai.shop')
85
+
86
+ 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.")
87
+ char_counter = gr.Markdown("Character count: 0")
88
+ btn = gr.Button("Text-To-Speech")
89
+ output_audio = gr.Audio(label="Speech Output")
90
+
91
+ def update_char_counter(text):
92
+ cleaned_text = clean_text(text) # Clean the text by removing extra spaces and newlines
93
+ return f"Character count: {len(cleaned_text)}"
94
+
95
+ text.change(fn=update_char_counter, inputs=text, outputs=char_counter)
96
+
97
+ text.submit(fn=tts, inputs=[text, model, voice, speed, api_key, base_url], outputs=output_audio, api_name="tts_enter_key", concurrency_limit=None)
98
+ btn.click(fn=tts, inputs=[text, model, voice, speed, api_key, base_url], outputs=output_audio, api_name="tts_button", concurrency_limit=None)
99
+
100
+ demo.launch()