File size: 10,441 Bytes
0edab04
 
 
0a2958b
 
e419f45
0edab04
 
 
 
 
990159e
 
0edab04
dc3a0c9
990159e
0edab04
990159e
 
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
 
 
d9a62b3
 
0a2958b
 
 
 
 
 
 
 
 
0edab04
 
72e0f08
 
 
 
 
0edab04
 
 
 
 
0a2958b
 
 
 
 
 
 
 
d9a62b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2958b
d9a62b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2958b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a62b3
 
 
 
 
 
 
 
 
 
 
72e0f08
d9a62b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72e0f08
0edab04
d9a62b3
 
 
 
 
 
 
 
 
0a2958b
0edab04
 
 
0a2958b
e419f45
 
 
 
 
 
 
 
0a2958b
0edab04
 
0a2958b
 
0edab04
 
 
 
 
 
e419f45
0edab04
 
e419f45
 
0edab04
0a2958b
0edab04
 
 
 
0a2958b
990159e
 
0a2958b
990159e
0a2958b
45b2ac8
 
0a2958b
990159e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# AUTOGENERATED! DO NOT EDIT! File to edit: app.ipynb.

# %% auto 0
__all__ = ['secret_import_failed', 'tts_voices', 'clean_text_prompt', 'OPENAI_CLIENT_TTS_THREADS', 'launch_kwargs',
           'queue_kwargs', 'split_text', 'concatenate_mp3', 'create_speech_openai', 'create_speech2', 'create_speech',
           'get_input_text_len', 'get_generation_cost']

# %% app.ipynb 1
#tts_openai_secrets.py content:
#import os
#os.environ['OPENAI_API_KEY'] = 'sk-XXXXXXXXXXXXXXXXXXXXXX'
import os
secret_import_failed = False
try:
    _ = os.environ['OPENAI_API_KEY']
    print('OPENAI_API_KEY environment variable was found.')
except:
    print('OPENAI_API_KEY environment variable was not found.')
    secret_import_failed = True
try:
    GRADIO_PASSWORD = os.environ['GRADIO_PASSWORD']
    print('GRADIO_PASSWORD environment variable was found.')
except:
    print('GRADIO_PASSWORD environment variable was not found.')
    secret_import_failed = True

if secret_import_failed == True:
    import tts_openai_secrets
    GRADIO_PASSWORD = os.environ['GRADIO_PASSWORD']
    print('import tts_openai_secrets succeeded')

# %% app.ipynb 3
import gradio as gr
import openai
from pydub import AudioSegment
import io
from datetime import datetime
from math import ceil
from multiprocessing.pool import ThreadPool
from functools import partial
from tenacity import (
    retry,
    stop_after_attempt,
    wait_random_exponential,
)  # for exponential backoff

# %% app.ipynb 4
try:
    tts_models = [o.id for o in openai.models.list().data if 'tts' in o.id]
    print('successfully got tts model list:', tts_models)
except:
    tts_models = ['tts-1']

# %% app.ipynb 5
tts_voices = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']

# %% app.ipynb 6
clean_text_prompt = """Your job is to clean up text that is going to be fed into a text to speech (TTS) model. You must remove parts of the text that would not normally be spoken such as reference marks `[1]`, spurious citations such as `(Reddy et al., 2021; Wu et al., 2022; Chang et al., 2022; Kondratyuk et al., 2023)` and any other part of the text that is not normally spoken. Please also clean up sections and headers so they are on new lines with proper numbering. You must also clean up any math formulas that are salvageable from being copied from a scientific paper. If they are garbled and do not make sense then remove them. You must carefully perform the text cleanup so it is translated into speech that is easy to listen to however you must not modify the text otherwise. It is critical that you repeat all of the text without modifications except for the cleanup activities you've been instructed to do. Also you must clean all of the text you are given, you may not omit any of it or stop the cleanup task early."""


# %% app.ipynb 7
#Number of threads created PER USER REQUEST. This throttels the # of API requests PER USER request. This is in ADDITION to the Gradio threads.
OPENAI_CLIENT_TTS_THREADS = 10 

# %% app.ipynb 8
def split_text(input_text, max_length=4000, lookback=1000):
    # If the text is shorter than the max_length, return it as is
    if len(input_text) <= max_length:
        return [input_text]

    chunks = []
    while input_text:
        # Check if the remaining text is shorter than the max_length
        if len(input_text) <= max_length:
            chunks.append(input_text)
            break

        # Define the split point, initially set to max_length
        split_point = max_length

        # Look for a newline in the last 'lookback' characters
        newline_index = input_text.rfind('\n', max_length-lookback, max_length)
        if newline_index != -1:
            split_point = newline_index + 1  # Include the newline in the current chunk

        # If no newline, look for a period followed by space
        elif '. ' in input_text[max_length-lookback:max_length]:
            # Find the last '. ' in the lookback range
            period_index = input_text.rfind('. ', max_length-lookback, max_length)
            split_point = period_index + 2  # Split after the space

        # Split the text and update the input_text
        chunks.append(input_text[:split_point])
        input_text = input_text[split_point:]

    return chunks

# %% app.ipynb 9
def concatenate_mp3(mp3_files):
    if len(mp3_files) == 1:
        return mp3_files[0]
    else:
        # Initialize an empty AudioSegment object for concatenation
        combined = AudioSegment.empty()
        
        # Write out audio file responses as individual files for debugging
        # for idx, mp3_data in enumerate(mp3_files):
        #     with open(f'./{idx}.mp3', 'wb') as f:
        #         f.write(mp3_data)

        # Loop through the list of mp3 binary data
        for mp3_data in mp3_files:
            # Convert binary data to an audio segment
            audio_segment = AudioSegment.from_file(io.BytesIO(mp3_data), format="mp3")
            # Concatenate this segment to the combined segment
            combined += audio_segment

        # Export the combined segment to a new mp3 file
        # Use a BytesIO object to handle this in memory
        combined_mp3 = io.BytesIO()
        combined.export(combined_mp3, format="mp3")

        # Seek to the start so it's ready for reading
        combined_mp3.seek(0)

        return combined_mp3.getvalue()

# %% app.ipynb 10
def create_speech_openai(chunk_idx, input, model='tts-1', voice='alloy', speed=1.0, **kwargs):
    client = openai.OpenAI()
    
    @retry(wait=wait_random_exponential(min=1, max=180), stop=stop_after_attempt(6))
    def _create_speech_with_backoff(**kwargs):
        return client.audio.speech.create(**kwargs)
    
    response = _create_speech_with_backoff(input=input, model=model, voice=voice, speed=speed, **kwargs)
    client.close()
    return chunk_idx, response.content

# %% app.ipynb 11
def create_speech2(input_text, model='tts-1', voice='alloy', progress=gr.Progress(), **kwargs):
    start = datetime.now()
    # Split the input text into chunks
    chunks = split_text(input_text)

    # Initialize the progress bar
    progress(0, desc=f"Started processing {len(chunks)} text chunks using {OPENAI_CLIENT_TTS_THREADS} threads. ETA is ~{ceil(len(chunks)/OPENAI_CLIENT_TTS_THREADS)} min.")

    # Initialize a list to hold the audio data of each chunk
    audio_data = []

    # Process each chunk
    with ThreadPool(processes=OPENAI_CLIENT_TTS_THREADS) as pool:
        results = pool.starmap(
            partial(create_speech_openai, model=model, voice=voice, **kwargs), 
            zip(range(len(chunks)),chunks)
        )
    audio_data = [o[1] for o in sorted(results)]

    # Progress
    progress(.9, desc=f"Merging audio chunks... {(datetime.now()-start).seconds} seconds to process.")
    
    # Concatenate the audio data from all chunks
    combined_audio = concatenate_mp3(audio_data)

    # Final update to the progress bar
    progress(1, desc=f"Processing completed... {(datetime.now()-start).seconds} seconds to process.")
    
    print(f"Processing time: {(datetime.now()-start).seconds} seconds.")

    return combined_audio


# %% app.ipynb 12
def create_speech(input_text, model='tts-1', voice='alloy', progress=gr.Progress()):
    # Split the input text into chunks
    chunks = split_text(input_text)

    # Initialize the progress bar
    progress(0, desc="Starting TTS processing...")

    # Initialize a list to hold the audio data of each chunk
    audio_data = []

    # Create a client instance for OpenAI
    client = openai.OpenAI()

    # Calculate the progress increment for each chunk
    progress_increment = 1.0 / len(chunks)

    # Process each chunk
    for i, chunk in enumerate(chunks):
        response = client.audio.speech.create(
            model=model,
            voice=voice,
            input=chunk,
            speed=1.0
        )
        # Append the audio content of the response to the list
        audio_data.append(response.content)

        # Update the progress bar
        progress((i + 1) * progress_increment, desc=f"Processing chunk {i + 1} of {len(chunks)}")

    # Close the client connection
    client.close()

    # Concatenate the audio data from all chunks
    combined_audio = concatenate_mp3(audio_data)

    # Final update to the progress bar
    progress(1, desc="Processing completed")

    return combined_audio


# %% app.ipynb 13
def get_input_text_len(input_text):
    return len(input_text)

# %% app.ipynb 14
def get_generation_cost(input_text, tts_model_dropdown):
    text_len = len(input_text)
    if tts_model_dropdown.endswith('-hd'):
        cost = text_len/1000 * 0.03
    else:
        cost = text_len/1000 * 0.015
    return "${:,.3f}".format(cost)

# %% app.ipynb 15
with gr.Blocks(title='OpenAI TTS', head='OpenAI TTS') as app:
    gr.Markdown("# OpenAI TTS")
    gr.Markdown("""Start typing below and then click **Go** to create the speech from your text. The current limit is 4,000 characters. 
For requests longer than 4,000 chars they will be broken into chunks of 4,000 or less chars automatically.""")
    with gr.Row():
        input_text = gr.Textbox(max_lines=100, label="Enter text here")
    with gr.Row():
        tts_model_dropdown = gr.Dropdown(value='tts-1',choices=tts_models, label='Model')
        tts_voice_dropdown = gr.Dropdown(value='alloy',choices=tts_voices,label='Voice')
        input_text_length = gr.Label(label="Number of characters")
        generation_cost = gr.Label(label="Generation cost")
        output_audio = gr.Audio()
    input_text.input(fn=get_input_text_len, inputs=input_text, outputs=input_text_length)
    input_text.input(fn=get_generation_cost, inputs=[input_text,tts_model_dropdown], outputs=generation_cost)
    tts_model_dropdown.input(fn=get_generation_cost, inputs=[input_text,tts_model_dropdown], outputs=generation_cost)
    go_btn = gr.Button("Go")
    go_btn.click(fn=create_speech2, inputs=[input_text, tts_model_dropdown, tts_voice_dropdown], outputs=[output_audio])
    clear_btn = gr.Button('Clear')
    clear_btn.click(fn=lambda: '', outputs=input_text)
    

# %% app.ipynb 16
launch_kwargs = {'auth':('username',GRADIO_PASSWORD),
                 'auth_message':'Please log in to Mat\'s TTS App with username: username and password.'}
queue_kwargs = {'default_concurrency_limit':10}

# %% app.ipynb 18
#.py launch
if __name__ == "__main__":
    app.queue(**queue_kwargs)
    app.launch(**launch_kwargs)