File size: 16,436 Bytes
0edab04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a62b3
0edab04
 
 
 
 
990159e
 
0edab04
dc3a0c9
990159e
0edab04
990159e
 
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a62b3
 
0a2958b
 
 
 
 
 
 
 
 
 
0edab04
 
 
 
 
 
 
d9a62b3
0edab04
 
72e0f08
 
 
 
 
0edab04
 
 
 
 
 
 
 
 
 
 
 
 
0a2958b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9a62b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2958b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
 
 
 
 
 
 
d9a62b3
 
 
 
 
 
 
 
 
 
 
72e0f08
d9a62b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72e0f08
d9a62b3
 
 
 
 
 
 
 
0edab04
 
 
 
 
 
 
 
 
 
 
 
 
 
e419f45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
 
 
 
 
 
 
 
 
0a2958b
 
0edab04
 
 
 
 
 
e419f45
0edab04
 
e419f45
 
0edab04
0a2958b
0edab04
 
 
 
 
45b2ac8
 
 
990159e
45b2ac8
 
990159e
 
 
0a2958b
 
990159e
 
 
 
 
 
 
d9a62b3
45b2ac8
 
 
0a2958b
990159e
45b2ac8
 
0edab04
 
 
 
 
d9a62b3
0edab04
 
45b2ac8
 
0a2958b
990159e
0edab04
 
 
 
 
 
 
d9a62b3
0edab04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bedf0dc-8d8e-4ede-a9e6-b8f35136aa00",
   "metadata": {},
   "outputs": [],
   "source": [
    "#|default_exp app"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "667802a7-0f36-4136-a381-e66210b20462",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "#tts_openai_secrets.py content:\n",
    "#import os\n",
    "#os.environ['OPENAI_API_KEY'] = 'sk-XXXXXXXXXXXXXXXXXXXXXX'\n",
    "import os\n",
    "secret_import_failed = False\n",
    "try:\n",
    "    _ = os.environ['OPENAI_API_KEY']\n",
    "    print('OPENAI_API_KEY environment variable was found.')\n",
    "except:\n",
    "    print('OPENAI_API_KEY environment variable was not found.')\n",
    "    secret_import_failed = True\n",
    "try:\n",
    "    GRADIO_PASSWORD = os.environ['GRADIO_PASSWORD']\n",
    "    print('GRADIO_PASSWORD environment variable was found.')\n",
    "except:\n",
    "    print('GRADIO_PASSWORD environment variable was not found.')\n",
    "    secret_import_failed = True\n",
    "\n",
    "if secret_import_failed == True:\n",
    "    import tts_openai_secrets\n",
    "    GRADIO_PASSWORD = os.environ['GRADIO_PASSWORD']\n",
    "    print('import tts_openai_secrets succeeded')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d9863fc-969e-409b-8e20-b9c3cd2cc3e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "try:\n",
    "    import nbdev\n",
    "except:\n",
    "    print('to convert this notebook to app.py you need to pip install nbdev')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f486d3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "import gradio as gr\n",
    "import openai\n",
    "from pydub import AudioSegment\n",
    "import io\n",
    "from datetime import datetime\n",
    "from math import ceil\n",
    "from multiprocessing.pool import ThreadPool\n",
    "from functools import partial\n",
    "from tenacity import (\n",
    "    retry,\n",
    "    stop_after_attempt,\n",
    "    wait_random_exponential,\n",
    ")  # for exponential backoff"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ffd33b4-cb9b-4c01-bff6-4c3102854ab6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "try:\n",
    "    tts_models = [o.id for o in openai.models.list().data if 'tts' in o.id]\n",
    "    print('successfully got tts model list:', tts_models)\n",
    "except:\n",
    "    tts_models = ['tts-1']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ddbca5d-4b04-43ab-afaf-430802980e78",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "tts_voices = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8eb7e7d5-7121-4762-b8d1-e5a9539e2b36",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "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.\"\"\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52d373be-3a79-412e-8ca2-92bb443fa52d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "#Number of threads created PER USER REQUEST. This throttels the # of API requests PER USER request. This is in ADDITION to the Gradio threads.\n",
    "OPENAI_CLIENT_TTS_THREADS = 10 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24674094-4d47-4e48-b591-55faabcff8df",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def split_text(input_text, max_length=4000, lookback=1000):\n",
    "    # If the text is shorter than the max_length, return it as is\n",
    "    if len(input_text) <= max_length:\n",
    "        return [input_text]\n",
    "\n",
    "    chunks = []\n",
    "    while input_text:\n",
    "        # Check if the remaining text is shorter than the max_length\n",
    "        if len(input_text) <= max_length:\n",
    "            chunks.append(input_text)\n",
    "            break\n",
    "\n",
    "        # Define the split point, initially set to max_length\n",
    "        split_point = max_length\n",
    "\n",
    "        # Look for a newline in the last 'lookback' characters\n",
    "        newline_index = input_text.rfind('\\n', max_length-lookback, max_length)\n",
    "        if newline_index != -1:\n",
    "            split_point = newline_index + 1  # Include the newline in the current chunk\n",
    "\n",
    "        # If no newline, look for a period followed by space\n",
    "        elif '. ' in input_text[max_length-lookback:max_length]:\n",
    "            # Find the last '. ' in the lookback range\n",
    "            period_index = input_text.rfind('. ', max_length-lookback, max_length)\n",
    "            split_point = period_index + 2  # Split after the space\n",
    "\n",
    "        # Split the text and update the input_text\n",
    "        chunks.append(input_text[:split_point])\n",
    "        input_text = input_text[split_point:]\n",
    "\n",
    "    return chunks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6224ae5-3792-42b2-8392-3abd42998a50",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def concatenate_mp3(mp3_files):\n",
    "    if len(mp3_files) == 1:\n",
    "        return mp3_files[0]\n",
    "    else:\n",
    "        # Initialize an empty AudioSegment object for concatenation\n",
    "        combined = AudioSegment.empty()\n",
    "        \n",
    "        # Write out audio file responses as individual files for debugging\n",
    "        # for idx, mp3_data in enumerate(mp3_files):\n",
    "        #     with open(f'./{idx}.mp3', 'wb') as f:\n",
    "        #         f.write(mp3_data)\n",
    "\n",
    "        # Loop through the list of mp3 binary data\n",
    "        for mp3_data in mp3_files:\n",
    "            # Convert binary data to an audio segment\n",
    "            audio_segment = AudioSegment.from_file(io.BytesIO(mp3_data), format=\"mp3\")\n",
    "            # Concatenate this segment to the combined segment\n",
    "            combined += audio_segment\n",
    "\n",
    "        # Export the combined segment to a new mp3 file\n",
    "        # Use a BytesIO object to handle this in memory\n",
    "        combined_mp3 = io.BytesIO()\n",
    "        combined.export(combined_mp3, format=\"mp3\")\n",
    "\n",
    "        # Seek to the start so it's ready for reading\n",
    "        combined_mp3.seek(0)\n",
    "\n",
    "        return combined_mp3.getvalue()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4691703d-ed0f-4481-8006-b2906289b780",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_speech_openai(chunk_idx, input, model='tts-1', voice='alloy', speed=1.0, **kwargs):\n",
    "    client = openai.OpenAI()\n",
    "    \n",
    "    @retry(wait=wait_random_exponential(min=1, max=180), stop=stop_after_attempt(6))\n",
    "    def _create_speech_with_backoff(**kwargs):\n",
    "        return client.audio.speech.create(**kwargs)\n",
    "    \n",
    "    response = _create_speech_with_backoff(input=input, model=model, voice=voice, speed=speed, **kwargs)\n",
    "    client.close()\n",
    "    return chunk_idx, response.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e34bb4aa-698c-4452-8cda-bd02b38f7122",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_speech2(input_text, model='tts-1', voice='alloy', progress=gr.Progress(), **kwargs):\n",
    "    start = datetime.now()\n",
    "    # Split the input text into chunks\n",
    "    chunks = split_text(input_text)\n",
    "\n",
    "    # Initialize the progress bar\n",
    "    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.\")\n",
    "\n",
    "    # Initialize a list to hold the audio data of each chunk\n",
    "    audio_data = []\n",
    "\n",
    "    # Process each chunk\n",
    "    with ThreadPool(processes=OPENAI_CLIENT_TTS_THREADS) as pool:\n",
    "        results = pool.starmap(\n",
    "            partial(create_speech_openai, model=model, voice=voice, **kwargs), \n",
    "            zip(range(len(chunks)),chunks)\n",
    "        )\n",
    "    audio_data = [o[1] for o in sorted(results)]\n",
    "\n",
    "    # Progress\n",
    "    progress(.9, desc=f\"Merging audio chunks... {(datetime.now()-start).seconds} seconds to process.\")\n",
    "    \n",
    "    # Concatenate the audio data from all chunks\n",
    "    combined_audio = concatenate_mp3(audio_data)\n",
    "\n",
    "    # Final update to the progress bar\n",
    "    progress(1, desc=f\"Processing completed... {(datetime.now()-start).seconds} seconds to process.\")\n",
    "    \n",
    "    print(f\"Processing time: {(datetime.now()-start).seconds} seconds.\")\n",
    "\n",
    "    return combined_audio\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5388e860",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_speech(input_text, model='tts-1', voice='alloy', progress=gr.Progress()):\n",
    "    # Split the input text into chunks\n",
    "    chunks = split_text(input_text)\n",
    "\n",
    "    # Initialize the progress bar\n",
    "    progress(0, desc=\"Starting TTS processing...\")\n",
    "\n",
    "    # Initialize a list to hold the audio data of each chunk\n",
    "    audio_data = []\n",
    "\n",
    "    # Create a client instance for OpenAI\n",
    "    client = openai.OpenAI()\n",
    "\n",
    "    # Calculate the progress increment for each chunk\n",
    "    progress_increment = 1.0 / len(chunks)\n",
    "\n",
    "    # Process each chunk\n",
    "    for i, chunk in enumerate(chunks):\n",
    "        response = client.audio.speech.create(\n",
    "            model=model,\n",
    "            voice=voice,\n",
    "            input=chunk,\n",
    "            speed=1.0\n",
    "        )\n",
    "        # Append the audio content of the response to the list\n",
    "        audio_data.append(response.content)\n",
    "\n",
    "        # Update the progress bar\n",
    "        progress((i + 1) * progress_increment, desc=f\"Processing chunk {i + 1} of {len(chunks)}\")\n",
    "\n",
    "    # Close the client connection\n",
    "    client.close()\n",
    "\n",
    "    # Concatenate the audio data from all chunks\n",
    "    combined_audio = concatenate_mp3(audio_data)\n",
    "\n",
    "    # Final update to the progress bar\n",
    "    progress(1, desc=\"Processing completed\")\n",
    "\n",
    "    return combined_audio\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "236dd8d3-4364-4731-af93-7dcdec6f18a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_input_text_len(input_text):\n",
    "    return len(input_text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0523a158-ee07-48b3-9350-ee39d4deee7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_generation_cost(input_text, tts_model_dropdown):\n",
    "    text_len = len(input_text)\n",
    "    if tts_model_dropdown.endswith('-hd'):\n",
    "        cost = text_len/1000 * 0.03\n",
    "    else:\n",
    "        cost = text_len/1000 * 0.015\n",
    "    return \"${:,.3f}\".format(cost)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4fb3159-579b-4271-bc96-4cd1e2816eca",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "with gr.Blocks(title='OpenAI TTS', head='OpenAI TTS') as app:\n",
    "    gr.Markdown(\"# OpenAI TTS\")\n",
    "    gr.Markdown(\"\"\"Start typing below and then click **Go** to create the speech from your text. The current limit is 4,000 characters. \n",
    "For requests longer than 4,000 chars they will be broken into chunks of 4,000 or less chars automatically.\"\"\")\n",
    "    with gr.Row():\n",
    "        input_text = gr.Textbox(max_lines=100, label=\"Enter text here\")\n",
    "    with gr.Row():\n",
    "        tts_model_dropdown = gr.Dropdown(value='tts-1',choices=tts_models, label='Model')\n",
    "        tts_voice_dropdown = gr.Dropdown(value='alloy',choices=tts_voices,label='Voice')\n",
    "        input_text_length = gr.Label(label=\"Number of characters\")\n",
    "        generation_cost = gr.Label(label=\"Generation cost\")\n",
    "        output_audio = gr.Audio()\n",
    "    input_text.input(fn=get_input_text_len, inputs=input_text, outputs=input_text_length)\n",
    "    input_text.input(fn=get_generation_cost, inputs=[input_text,tts_model_dropdown], outputs=generation_cost)\n",
    "    tts_model_dropdown.input(fn=get_generation_cost, inputs=[input_text,tts_model_dropdown], outputs=generation_cost)\n",
    "    go_btn = gr.Button(\"Go\")\n",
    "    go_btn.click(fn=create_speech2, inputs=[input_text, tts_model_dropdown, tts_voice_dropdown], outputs=[output_audio])\n",
    "    clear_btn = gr.Button('Clear')\n",
    "    clear_btn.click(fn=lambda: '', outputs=input_text)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a00648a1-891b-470b-9959-f5d502055713",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "launch_kwargs = {'auth':('username',GRADIO_PASSWORD),\n",
    "                 'auth_message':'Please log in to Mat\\'s TTS App with username: username and password.'}\n",
    "queue_kwargs = {'default_concurrency_limit':10}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b534fe7-4337-423e-846a-1bdb7cccc4ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "#Notebook launch\n",
    "app.queue(**queue_kwargs)\n",
    "app.launch(**launch_kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cb886d45",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "#.py launch\n",
    "if __name__ == \"__main__\":\n",
    "    app.queue(**queue_kwargs)\n",
    "    app.launch(**launch_kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28e8d888-e790-46fa-bbac-4511b9ab796c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "app.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afbc9699-4d16-4060-88f4-cd1251754cbd",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "gr.close_all()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0420310d-930b-4904-8bd4-3458ad8bdbd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "nbdev.export.nb_export('app.ipynb',lib_path='.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9869749d-bc7c-4e24-9dbc-403f665d6200",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}