File size: 43,647 Bytes
0edab04
 
 
 
99246a0
0edab04
 
 
 
 
 
 
666e796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
99246a0
0edab04
 
666e796
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
666e796
990159e
 
0edab04
666e796
dc3a0c9
990159e
0edab04
990159e
 
 
666e796
 
 
 
 
 
951a5b3
 
 
 
990159e
666e796
990159e
 
 
 
666e796
 
 
990159e
0edab04
 
 
 
99246a0
666e796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99246a0
0edab04
 
 
 
 
 
 
 
 
 
 
 
 
4db1bc1
0edab04
 
 
 
 
666e796
0edab04
d9a62b3
 
0a2958b
 
 
 
 
8dde6b0
 
0a2958b
 
 
 
666e796
 
 
99246a0
 
4db1bc1
 
666e796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
 
 
99246a0
8dde6b0
 
666e796
 
 
 
 
 
 
 
 
8dde6b0
 
06719d4
8dde6b0
 
 
 
 
 
99246a0
c59a6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99246a0
666e796
0edab04
8dde6b0
0edab04
 
666e796
 
 
 
 
99246a0
666e796
 
 
 
 
 
 
 
 
 
 
 
 
 
72e0f08
666e796
 
 
 
c59a6cf
 
 
666e796
 
 
 
 
0edab04
 
 
 
99246a0
666e796
0edab04
666e796
 
 
 
 
 
 
 
 
0edab04
 
666e796
 
 
 
 
 
c59a6cf
 
 
 
666e796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0edab04
 
0a2958b
 
99246a0
c59a6cf
0a2958b
 
 
c59a6cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2958b
 
 
 
99246a0
c59a6cf
0a2958b
 
 
 
99246a0
666e796
 
 
 
 
 
 
 
0a2958b
 
d9a62b3
 
99246a0
666e796
 
 
 
 
 
 
 
 
951a5b3
666e796
 
 
 
 
 
 
 
 
99246a0
d9a62b3
 
 
 
 
c59a6cf
 
 
 
 
d9a62b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99246a0
d9a62b3
 
 
 
 
7c60390
666e796
17d79ff
 
d9a62b3
17d79ff
7c60390
17d79ff
7c60390
 
17d79ff
 
d9a62b3
17d79ff
 
 
 
 
8dde6b0
17d79ff
 
d9a62b3
17d79ff
d9a62b3
17d79ff
 
 
 
 
d9a62b3
 
0a2958b
 
99246a0
0a2958b
 
c59a6cf
 
 
 
 
 
 
 
 
0a2958b
 
 
 
 
 
 
 
 
 
 
c59a6cf
 
 
 
0a2958b
 
666e796
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2958b
 
99246a0
666e796
 
c59a6cf
 
 
 
 
 
 
 
 
666e796
 
 
 
7c60390
 
 
666e796
 
7c60390
666e796
 
 
7c60390
 
 
 
 
666e796
c59a6cf
 
 
 
666e796
 
7c60390
 
99246a0
7c60390
 
 
 
 
 
c59a6cf
 
 
 
 
 
 
 
 
 
7c60390
 
666e796
 
99246a0
c59a6cf
 
 
 
 
 
 
 
 
 
99246a0
0a2958b
 
 
 
 
7c60390
c59a6cf
7c60390
666e796
1c742b7
7c60390
0a2958b
666e796
c59a6cf
 
 
 
 
666e796
0a2958b
c59a6cf
0a2958b
 
666e796
0a2958b
 
 
 
 
666e796
0a2958b
666e796
0a2958b
 
 
 
 
 
 
 
7c60390
0a2958b
 
 
 
 
 
 
 
 
0edab04
 
99246a0
666e796
0edab04
 
 
7c60390
 
 
0edab04
 
 
 
99246a0
0edab04
 
 
 
 
 
 
 
 
e419f45
 
99246a0
e419f45
 
 
 
 
666e796
e419f45
666e796
 
 
 
 
 
 
e419f45
666e796
e419f45
 
 
0edab04
 
99246a0
666e796
0edab04
 
e0d016a
 
666e796
 
e0d016a
 
 
 
99246a0
666e796
 
 
 
 
 
 
7c60390
666e796
 
 
 
99246a0
666e796
 
 
 
 
 
 
 
 
 
 
99246a0
666e796
e0d016a
8dde6b0
0edab04
 
666e796
 
7c60390
666e796
 
 
 
99246a0
c59a6cf
 
 
 
636fd12
c59a6cf
 
 
 
 
99246a0
 
4db1bc1
 
 
 
 
 
 
 
 
 
 
 
 
99246a0
 
 
 
 
 
 
 
 
4db1bc1
99246a0
 
c59a6cf
 
4db1bc1
99246a0
 
 
 
 
 
 
 
 
 
 
 
666e796
1c742b7
99246a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4db1bc1
 
99246a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b9e17f
99246a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4db1bc1
99246a0
 
 
 
 
4db1bc1
 
 
 
 
99246a0
 
 
 
4db1bc1
99246a0
 
2b9e17f
666e796
 
 
c59a6cf
 
666e796
 
4db1bc1
 
0edab04
99246a0
4db1bc1
99246a0
 
0edab04
 
1c742b7
 
 
 
 
 
0edab04
e419f45
666e796
0edab04
c59a6cf
 
 
 
 
 
 
 
666e796
c59a6cf
99246a0
4db1bc1
c59a6cf
 
0edab04
666e796
1c742b7
 
c59a6cf
 
 
666e796
 
 
 
c59a6cf
666e796
c59a6cf
666e796
 
 
c59a6cf
666e796
 
 
 
c59a6cf
0edab04
e0d016a
666e796
c59a6cf
 
0edab04
 
 
45b2ac8
 
4db1bc1
990159e
45b2ac8
 
990159e
 
e0d016a
 
 
0a2958b
990159e
 
 
 
4db1bc1
990159e
 
2b9e17f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4db1bc1
2b9e17f
 
 
 
45b2ac8
 
 
0a2958b
990159e
45b2ac8
 
0edab04
 
 
 
 
d9a62b3
0edab04
 
45b2ac8
 
0a2958b
990159e
0edab04
 
 
 
4db1bc1
0edab04
 
666e796
 
 
 
 
c59a6cf
666e796
 
 
0edab04
 
 
 
 
 
 
c59a6cf
0edab04
 
1c742b7
0edab04
 
 
 
 
 
 
4db1bc1
0edab04
 
 
 
 
7c60390
0edab04
 
 
 
 
 
 
 
 
 
337790f
 
 
 
 
 
 
 
0edab04
 
 
 
e0d016a
0edab04
e0d016a
 
 
 
 
 
 
 
 
 
 
 
 
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3bedf0dc-8d8e-4ede-a9e6-b8f35136aa00",
   "metadata": {},
   "outputs": [],
   "source": [
    "#|default_exp app"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2496690-28b2-4a79-89d5-f971b4d6f3d4",
   "metadata": {},
   "source": [
    "# Initialization"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "736caa6e-d79f-46e6-bf42-6594c8b809d4",
   "metadata": {},
   "source": [
    "## Get/Set Environment Variables"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7baadc12-4748-4938-916f-0a256546c181",
   "metadata": {},
   "source": [
    "If you want to run this locally without having to set up the environment variables in your system, you can create a file called `tts_openai_secrets.py` in the root directory with this content:\n",
    "```python\n",
    "import os\n",
    "os.environ['OPENAI_API_KEY'] = 'sk-XXXXXXXXXXXXXXXXXXXXXX'\n",
    "os.environ['CARTESIA_API_KEY'] = 'XXXXXXXXXXXXXXXXXXXXXX'\n",
    "os.environ[\"ALLOWED_OAUTH_PROFILE_USERNAMES\"]= '<huggingface-username1>,<huggingface-username2>'\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "667802a7-0f36-4136-a381-e66210b20462",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OPENAI_API_KEY environment variable was not found.\n",
      "CARTESIA_API_KEY environment variable was not found.\n",
      "ALLOWED_OAUTH_PROFILE_USERNAMES environment variable was not found.\n",
      "import tts_openai_secrets succeeded\n"
     ]
    }
   ],
   "source": [
    "#| export\n",
    "\n",
    "import os\n",
    "secret_import_failed = False\n",
    "try:\n",
    "    # don't need the openai api key in a variable\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",
    "    CARTESIA_API_KEY = os.environ['CARTESIA_API_KEY']\n",
    "    print('CARTESIA_API_KEY environment variable was found.')\n",
    "except:\n",
    "    print('CARTESIA_API_KEY environment variable was not found.')\n",
    "    secret_import_failed = True\n",
    "try:\n",
    "    temp_ALLOWED_OAUTH_PROFILE_USERNAMES = os.environ['ALLOWED_OAUTH_PROFILE_USERNAMES']\n",
    "    ALLOWED_OAUTH_PROFILE_USERNAMES = tuple([o for o in temp_ALLOWED_OAUTH_PROFILE_USERNAMES.split(',') if o not in ('','None')])\n",
    "    del temp_ALLOWED_OAUTH_PROFILE_USERNAMES\n",
    "    print(f'ALLOWED_OAUTH_PROFILE_USERNAMES environment variable was found. {ALLOWED_OAUTH_PROFILE_USERNAMES}')\n",
    "except:\n",
    "    print('ALLOWED_OAUTH_PROFILE_USERNAMES environment variable was not found.')\n",
    "    secret_import_failed = True\n",
    "\n",
    "if secret_import_failed == True:\n",
    "    import tts_openai_secrets\n",
    "    _ = os.environ['OPENAI_API_KEY']\n",
    "    CARTESIA_API_KEY = os.environ['CARTESIA_API_KEY']\n",
    "    ALLOWED_OAUTH_PROFILE_USERNAMES = os.environ['ALLOWED_OAUTH_PROFILE_USERNAMES']\n",
    "    print('import tts_openai_secrets succeeded')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7664bc24-e8a7-440d-851d-eb16dc2d69fb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "REQUIRE_AUTH: False\n"
     ]
    }
   ],
   "source": [
    "#| export\n",
    "# If REQUIRE_AUTH environemnt variable is set to 'false' (from secrets) and HF_SPACE != 1 then we\n",
    "# are running locally and don't require authentication and authorization, otherwise we do.\n",
    "# We are using paid API's so don't want anybody/everybody to be able to use our paid services.\n",
    "if os.environ.get(\"REQUIRE_AUTH\",'true') == 'false' and os.environ.get('HF_SPACE',0) != 1:\n",
    "    REQUIRE_AUTH = False\n",
    "else:\n",
    "    REQUIRE_AUTH = True\n",
    "print('REQUIRE_AUTH:',REQUIRE_AUTH)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c978095-da2a-43f8-9729-3d845e7056f1",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "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": 41,
   "id": "4f486d3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "import os\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 pathlib import Path\n",
    "import uuid\n",
    "from tenacity import (\n",
    "    retry,\n",
    "    stop_after_attempt,\n",
    "    wait_random_exponential,\n",
    ")  # for exponential backoff\n",
    "import traceback\n",
    "# from cartesia.tts import CartesiaTTS\n",
    "import cartesia\n",
    "import requests\n",
    "import urllib\n",
    "import re"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b425ab4-cecd-4760-84fb-b7f2cc44a565",
   "metadata": {},
   "source": [
    "Set the Gradio TEMP directory. This will be used to save audio files that were generated prior to returning them. The reason we are doing this is because if you return a bytesio object to a Gradio audio object it will not contain the file extension and will not be playable in Safari. If you pass the file to the Gradio audio object it will contain the extension. In addition if you pass the filepath instead of bytesio path, when you download the audio it will have the correct file extenion whereas otherwise it will not."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "852a3a1f-462a-41ab-bc94-b5ba12279ae9",
   "metadata": {},
   "source": [
    "## App Settings/Constants"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ecb7f207-0fc2-4d19-a313-356c05776832",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TEMP Dir: /tmp\n"
     ]
    }
   ],
   "source": [
    "#| export\n",
    "TEMP = os.environ.get('GRADIO_TEMP_DIR','/tmp/')\n",
    "TEMP_DIR = Path(TEMP)\n",
    "print('TEMP Dir:', TEMP_DIR)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "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 \n",
    "CARTESIAAI_CLIENT_TTS_THREADS = 3\n",
    "\n",
    "DEFAULT_PROVIDER = 'openai'\n",
    "DEFAULT_MODEL = 'tts-1'\n",
    "DEFAULT_VOICE = 'alloy'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e5d6cac2-0dee-42d8-9b41-184b5be9cc3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "providers = dict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b77ad8d6-3289-463c-b213-1c0cc215b141",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully added OpenAI as Provider\n"
     ]
    }
   ],
   "source": [
    "#| export\n",
    "# Add OpenAI as a provider\n",
    "try:\n",
    "    providers['openai'] = {\n",
    "        'name': 'Open AI',\n",
    "        'models': {o.id: o.id for o in openai.models.list().data if 'tts' in o.id},\n",
    "        'voices': {o:{'id':o,'name':o.title()} for o in ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']},\n",
    "        'settings': {'max_chunk_size': 4000, 'chunk_processing_time': 60, \n",
    "                     'threads': OPENAI_CLIENT_TTS_THREADS,\n",
    "                     'audio_file_conversion_kwargs':{'format': 'mp3'}},\n",
    "    }\n",
    "    print('Successfully added OpenAI as Provider')\n",
    "except Exception as e:\n",
    "    print(f\"\"\"Error: Failed to add OpenAI as a provider.\\nException: {repr(e)}\\nTRACEBACK:\\n\"\"\",traceback.format_exc())\n",
    "# providers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "87fca48b-a16a-4d2b-919c-75e88e4e5eb5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Successfully added Cartesia AI as Provider\n"
     ]
    }
   ],
   "source": [
    "#| export\n",
    "# Add Cartesia AI as a provider\n",
    "try:\n",
    "    providers['cartesiaai'] = {\n",
    "        'name': 'Cartesia AI',\n",
    "        'models': {'upbeat-moon': 'Sonic Turbo English'},\n",
    "        'voices': {v['id']:v for k,v in cartesia.tts.CartesiaTTS().get_voices().items()},\n",
    "        'settings': {'max_chunk_size': 500, 'chunk_processing_time': 20, \n",
    "                     'threads': CARTESIAAI_CLIENT_TTS_THREADS,\n",
    "                     'audio_file_conversion_kwargs':{'format': 'raw', 'frame_rate': 44100, \n",
    "                                                     'channels': 1, 'sample_width': 2}},\n",
    "    }\n",
    "    print('Successfully added Cartesia AI as Provider')\n",
    "except Exception as e:\n",
    "    print(f\"\"\"Error: Failed to add Cartesia AI as a provider.\\nException: {repr(e)}\\nTRACEBACK:\\n\"\"\",traceback.format_exc())\n",
    "# providers"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6bd2e9ed-9dbd-4d5f-a814-2942108b5935",
   "metadata": {},
   "source": [
    "EXAMPLE: providers\n",
    "```python\n",
    "{'openai': {'name': 'Open AI',\n",
    "  'models': {'tts-1-hd-1106': 'tts-1-hd-1106',\n",
    "   'tts-1-hd': 'tts-1-hd',\n",
    "   'tts-1': 'tts-1',\n",
    "   'tts-1-1106': 'tts-1-1106'},\n",
    "  'voices': {'alloy': {'id': 'alloy', 'name': 'Alloy'},\n",
    "   'echo': {'id': 'echo', 'name': 'Echo'},\n",
    "   'fable': {'id': 'fable', 'name': 'Fable'},\n",
    "   'onyx': {'id': 'onyx', 'name': 'Onyx'},\n",
    "   'nova': {'id': 'nova', 'name': 'Nova'},\n",
    "   'shimmer': {'id': 'shimmer', 'name': 'Shimmer'}}},\n",
    " 'cartesiaai': {'name': 'Cartesia AI',\n",
    "  'models': {'upbeat-moon': 'Sonic Turbo English'},\n",
    "  'voices': {'3b554273-4299-48b9-9aaf-eefd438e3941': {'id': '3b554273-4299-48b9-9aaf-eefd438e3941',\n",
    "    'user_id': None,\n",
    "    'is_public': True,\n",
    "    'name': 'Indian Lady',\n",
    "    'description': 'This voice is young, rich, and curious, perfect for a narrator or fictional character',\n",
    "    'created_at': '2024-05-04T18:48:17.006441-07:00',\n",
    "    'embedding': [0.015546328,-0.11384969,0.14146514, ...]},\n",
    "   '63ff761f-c1e8-414b-b969-d1833d1c870c': {'id': '63ff761f-c1e8-414b-b969-d1833d1c870c',\n",
    "    'user_id': None,\n",
    "    'is_public': True,\n",
    "    'name': 'Confident British Man',\n",
    "    'description': 'This voice is disciplined with a British accent, perfect for a commanding character or narrator',\n",
    "    'created_at': '2024-05-04T18:57:31.399193-07:00',\n",
    "    'embedding': [-0.056990184,-0.06531749,-0.05618861,...]}\n",
    "            }\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d1352f28-f761-4e91-a9bc-4efe47552f4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# {v['id']:v['name'] for k,v in cartesia.tts.CartesiaTTS().get_voices().items()},"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a06e16b3-6310-462e-8192-b65ca324d86f",
   "metadata": {},
   "source": [
    "```\n",
    "({'3b554273-4299-48b9-9aaf-eefd438e3941': 'Indian Lady',\n",
    "  '63ff761f-c1e8-414b-b969-d1833d1c870c': 'Confident British Man',\n",
    "  'daf747c6-6bc2-4083-bd59-aa94dce23f5d': 'Middle Eastern Woman',\n",
    "  'ed81fd13-2016-4a49-8fe3-c0d2761695fc': 'Sportsman',\n",
    "  'f114a467-c40a-4db8-964d-aaba89cd08fa': 'Yogaman',\n",
    "  'c45bc5ec-dc68-4feb-8829-6e6b2748095d': 'Movieman',\n",
    "  '87748186-23bb-4158-a1eb-332911b0b708': 'Wizardman',\n",
    "  '98a34ef2-2140-4c28-9c71-663dc4dd7022': 'Southern Man',\n",
    "  '79f8b5fb-2cc8-479a-80df-29f7a7cf1a3e': 'Nonfiction Man',\n",
    "  '36b42fcb-60c5-4bec-b077-cb1a00a92ec6': 'Pilot over Intercom',\n",
    "  '69267136-1bdc-412f-ad78-0caad210fb40': 'Friendly Reading Man',\n",
    "  '15a9cd88-84b0-4a8b-95f2-5d583b54c72e': 'Reading Lady',\n",
    "  '95856005-0332-41b0-935f-352e296aa0df': 'Classy British Man',\n",
    "  'd46abd1d-2d02-43e8-819f-51fb652c1c61': 'Newsman',\n",
    "  '2ee87190-8f84-4925-97da-e52547f9462c': 'Child',\n",
    "  'c2ac25f9-ecc4-4f56-9095-651354df60c0': 'Commercial Lady',\n",
    "  '5345cf08-6f37-424d-a5d9-8ae1101b9377': 'Maria',\n",
    "  'a3520a8f-226a-428d-9fcd-b0a4711a6829': 'Reflective Woman',\n",
    "  'e3827ec5-697a-4b7c-9704-1a23041bbc51': 'Sweet Lady',\n",
    "  'a0e99841-438c-4a64-b679-ae501e7d6091': 'Barbershop Man',\n",
    "  'cd17ff2d-5ea4-4695-be8f-42193949b946': 'Meditation Lady',\n",
    "  'bf991597-6c13-47e4-8411-91ec2de5c466': 'Newslady',\n",
    "  '41534e16-2966-4c6b-9670-111411def906': \"1920's Radioman\",\n",
    "  '79a125e8-cd45-4c13-8a67-188112f4dd22': 'British Lady',\n",
    "  'a167e0f3-df7e-4d52-a9c3-f949145efdab': 'Ted',\n",
    "  '248be419-c632-4f23-adf1-5324ed7dbf1d': 'Hannah',\n",
    "  'c8605446-247c-4d39-acd4-8f4c28aa363c': 'Wise Lady',\n",
    "  '00a77add-48d5-4ef6-8157-71e5437b282d': 'Calm Lady',\n",
    "  '638efaaa-4d0c-442e-b701-3fae16aad012': 'Indian Man',\n",
    "  'd6b6d712-6030-4420-9771-8b35f326fd20': 'Mat 1'},)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "8eb7e7d5-7121-4762-b8d1-e5a9539e2b36",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "CLEAN_TEXT_SYSTEM_PROMPT = \"\"\"You are a helpful expert AI assistant. You are an autoregressive LLM. Your job is to take markdown that was created from a web page html and clean it up so it can be fed to a text to speech model. Remove all hyperlink URL's, navigation references, citations or complex formulas that are not useful when only listening to in audio format. It is also helpful to spell out dates, long numbers, abbreviations, acronym, units etc. For example if you see `50C` in the context of temperature change it to `50 degrees celsius`. If you see an acronym, for example NASA, please spell it out `National Aeronautics and Space Administration`. When you have finished your task please finish the text you return with <<COMPLETE>>. The maximum context length you can return in one shot is 4,000 tokens so you may get cut off. If that happens I will send you another message with the text <<CONTINUE>> and you should continue the task where you had previously left off. This is why I need you finish your response with <<COMPLETE>> once you have fully completed your task.  DO NOT MODIFY THE TEXT IN ANY WAY EXCEPT FOR AS INSTRUCTED HERE.\"\"\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6400d8e-49e8-41b8-ad0e-18bc032682b6",
   "metadata": {},
   "source": [
    "# Main Implementation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "b5b29507-92bc-453d-bcc5-6402c17e9a0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def verify_authorization(profile: gr.OAuthProfile=None) -> str:\n",
    "    print('Profile:', profile)\n",
    "    if REQUIRE_AUTH == False:\n",
    "        return 'WARNING_NO_AUTH_REQUIRED_LOCAL'\n",
    "    elif profile is not None and profile.username in ALLOWED_OAUTH_PROFILE_USERNAMES:\n",
    "        return f\"{profile.username}\"\n",
    "    else:\n",
    "        # print('Unauthorized',profile)\n",
    "        raise PermissionError(f'Your huggingface username ({profile}) is not authorized. Must be set in ALLOWED_OAUTH_PROFILE_USERNAMES environment variable.')\n",
    "        return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "24674094-4d47-4e48-b591-55faabcff8df",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def split_text(input_text, provider):\n",
    "    settings = providers[provider]['settings']\n",
    "    max_length = settings['max_chunk_size']\n",
    "    lookback = max_length // 4\n",
    "        \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": 15,
   "id": "e6224ae5-3792-42b2-8392-3abd42998a50",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def concatenate_audio(files:list, **kwargs):\n",
    "\n",
    "    # Initialize an empty AudioSegment object for concatenation\n",
    "    combined = AudioSegment.empty()\n",
    "\n",
    "    # Loop through the list of mp3 binary data\n",
    "    for data in files:\n",
    "        # Convert binary data to an audio segment\n",
    "        audio_segment = AudioSegment.from_file(io.BytesIO(data), **kwargs)\n",
    "        \n",
    "        # Concatenate this segment to the combined segment\n",
    "        combined += audio_segment\n",
    "\n",
    "    #### Return Bytes Method\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()\n",
    "\n",
    "    #### Return Filepath Method\n",
    "    filepath = TEMP_DIR/(str(uuid.uuid4())+'.mp3')\n",
    "    combined.export(filepath, format=\"mp3\")\n",
    "    print('Saving mp3 file to temp directory: ', filepath)\n",
    "    return str(filepath)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "4691703d-ed0f-4481-8006-b2906289b780",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Added create_speech_func for openai provider\n"
     ]
    }
   ],
   "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\n",
    "if 'openai' in providers.keys():\n",
    "    providers['openai']['settings']['create_speech_func'] = create_speech_openai\n",
    "    print('Added create_speech_func for openai provider')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b1a0a8a-0ff6-44fa-b85c-c80c56bd3a24",
   "metadata": {},
   "source": [
    "```python\n",
    "client.generate(\n",
    "    *,\n",
    "    transcript: str,\n",
    "    voice: List[float],\n",
    "    model_id: str = '',\n",
    "    duration: int = None,\n",
    "    chunk_time: float = None,\n",
    "    stream: bool = False,\n",
    "    websocket: bool = True,\n",
    "    output_format: Union[str, cartesia._types.AudioOutputFormat] = 'fp32',\n",
    "    data_rtype: str = 'bytes',\n",
    ") -> Union[cartesia._types.AudioOutput, Generator[cartesia._types.AudioOutput, NoneType, NoneType]]\n",
    "\n",
    "list(cartesia._types.AudioOutputFormat)\n",
    "[<AudioOutputFormat.FP32: 'fp32'>,\n",
    " <AudioOutputFormat.PCM: 'pcm'>,\n",
    " <AudioOutputFormat.FP32_16000: 'fp32_16000'>,\n",
    " <AudioOutputFormat.FP32_22050: 'fp32_22050'>,\n",
    " <AudioOutputFormat.FP32_44100: 'fp32_44100'>,\n",
    " <AudioOutputFormat.PCM_16000: 'pcm_16000'>,\n",
    " <AudioOutputFormat.PCM_22050: 'pcm_22050'>,\n",
    " <AudioOutputFormat.PCM_44100: 'pcm_44100'>,\n",
    " <AudioOutputFormat.MULAW_8000: 'mulaw_8000'>]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "3420c868-71cb-4ac6-ac65-6f02bfd841d1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Added create_speech_func for create_speech_cartesiaai provider\n"
     ]
    }
   ],
   "source": [
    "#| export\n",
    "def create_speech_cartesiaai(chunk_idx, input, model='upbeat-moon', \n",
    "                             voice='248be419-c632-4f23-adf1-5324ed7dbf1d', #Hannah\n",
    "                             websocket=False, \n",
    "                             output_format='pcm_44100', \n",
    "                             **kwargs):\n",
    "    client = cartesia.tts.CartesiaTTS()\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.generate(**kwargs)\n",
    "    \n",
    "    response = _create_speech_with_backoff(transcript=input, model_id=model, \n",
    "                                           voice=client.get_voice_embedding(voice_id=voice), \n",
    "                                           websocket=websocket, \n",
    "                                           output_format=output_format, \n",
    "                                           **kwargs)\n",
    "    client.close()\n",
    "    return chunk_idx, response[\"audio\"]\n",
    "if 'cartesiaai' in providers.keys():\n",
    "    providers['cartesiaai']['settings']['create_speech_func'] = create_speech_cartesiaai\n",
    "    print('Added create_speech_func for create_speech_cartesiaai provider')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "d0082383-9d03-4b25-b68a-080d0b28caa9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# test\n",
    "# create_speech_cartesiaai(1,\"Hi. What's your name?\", model='upbeat-moon',\n",
    "#               voice='63ff761f-c1e8-414b-b969-d1833d1c870c')\n",
    "# text = \"\"\"Ladies and Gentlemen, gather 'round your radio sets for a special report on a remarkable phenomenon sweeping the nation! It seems a new generation of prodigies is lighting up our schools and captivating communities from coast to coast. Yes, we're talking about gifted children, those bright young minds whose talents and intellects are far beyond their tender years.\n",
    "# In classrooms across the country, educators are reporting an unprecedented wave of exceptional youngsters. These gifted children, some as young as five or six, are astonishing their teachers with feats of arithmetic, literacy, and creativity that rival those of much older students. The age of enlightenment is upon us, and it starts with these brilliant boys and girls!\n",
    "# Take young Tommy Caldwell of Newark, New Jersey, for instance. At the ripe age of seven, Tommy has already mastered algebra and is now diving into the wonders of geometry. His teacher, Miss Grace Whittaker, says she’s never seen such a gifted mathematician in her twenty years of teaching. And Tommy is just one of many!\n",
    "# Then there's little Sally Henderson of Topeka, Kansas. At the tender age of eight, Sally has penned her first book of poetry, a collection that has local literary circles abuzz with excitement. Her vivid imagination and eloquent verse have earned her the nickname “The Young Bard of Topeka.” The town is swelling with pride for their young poetess.\n",
    "# Experts from esteemed institutions like Harvard and Yale are paying close attention to this trend, conducting studies to understand the roots of such exceptional abilities. Some suggest it’s the result of improved nutrition and health care, while others believe it’s the progressive educational methods now being employed in our schools. Regardless of the cause, one thing is clear: America is home to a new generation of geniuses!\n",
    "# Communities are rallying to support these young prodigies, with special programs and schools being established to nurture their extraordinary talents. Parents, teachers, and civic leaders are united in their mission to provide the resources and opportunities these gifted children need to reach their full potential.\n",
    "# So, dear listeners, as you sit by your radios tonight, take heart in the knowledge that our future is bright. With these remarkable young minds leading the way, the possibilities are endless. This is your announcer signing off, wishing you all a splendid evening and a hopeful tomorrow.\"\"\"\n",
    "# _, test_data = create_speech_cartesiaai(1, text, model='upbeat-moon',\n",
    "#               voice='41534e16-2966-4c6b-9670-111411def906')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "649d90a5-9398-4cb5-a1e8-a464d463a11c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# test_file = AudioSegment.from_file(io.BytesIO(test_data), **{'format': 'raw', 'frame_rate': 44100, 'channels': 1, 'sample_width': 2})\n",
    "# test_file.export('./test3.mp3', format=\"mp3\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "e34bb4aa-698c-4452-8cda-bd02b38f7122",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_speech(input_text, provider, model='tts-1', voice='alloy', \n",
    "                  profile: gr.OAuthProfile|None=None, # comment out of running locally\n",
    "                  progress=gr.Progress(), **kwargs):\n",
    "\n",
    "    #Verify auth if it is required. This is very important if this is in a HF space. DO NOT DELETE!!!\n",
    "    if REQUIRE_AUTH: verify_authorization(profile)\n",
    "    start = datetime.now()\n",
    "    \n",
    "    settings = providers[provider]['settings']\n",
    "    create_speech_func = settings['create_speech_func']\n",
    "    chunk_processing_time = settings['chunk_processing_time']\n",
    "    threads = settings['threads']\n",
    "    audio_file_conversion_kwargs = settings['audio_file_conversion_kwargs']\n",
    "    \n",
    "    # Split the input text into chunks\n",
    "    chunks = split_text(input_text, provider=provider)\n",
    "\n",
    "    # Initialize the progress bar\n",
    "    progress(0, desc=f\"Started processing {len(chunks)} text chunks using {threads} threads. ETA is ~{ceil(len(chunks)/threads)*chunk_processing_time/60.} 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=threads) as pool:\n",
    "        results = pool.starmap(\n",
    "            partial(create_speech_func, 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_audio(audio_data, **audio_file_conversion_kwargs)\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": 21,
   "id": "ca2c6f8c-62ed-4ac1-9c2f-e3b2bfb47e8d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# create_speech(\"Hi. What's your name?\", provider='openai', model='tts-1', voice='alloy')\n",
    "# create_speech(\"Hi. What's your name?\", provider='cartesiaai', model='upbeat-moon',\n",
    "#               voice='63ff761f-c1e8-414b-b969-d1833d1c870c')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "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": 23,
   "id": "0523a158-ee07-48b3-9350-ee39d4deee7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_generation_cost(input_text, tts_model_dropdown, provider):\n",
    "    text_len = len(input_text)\n",
    "    if provider == 'openai':\n",
    "        if tts_model_dropdown.endswith('-hd'):\n",
    "            cost = text_len/1000 * 0.03\n",
    "        else:\n",
    "            cost = text_len/1000 * 0.015\n",
    "    elif provider == 'cartesiaai':\n",
    "        cost = text_len/1000 * 0.065\n",
    "    else:\n",
    "        raise ValueError(f'Invalid argument provider: {provider}')\n",
    "    return \"${:,.3f}\".format(cost)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "f4d1ba0b-6960-4e22-8dba-7de70370753a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_model_choices(provider):\n",
    "    return sorted([(v,k) for k,v in providers[provider]['models'].items()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "efa28cf2-548d-439f-bf2a-21a5edbf9eba",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def update_model_choices(provider):\n",
    "    choices = get_model_choices(provider)\n",
    "    return gr.update(choices=choices,value=choices[0][1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "cdc1dde5-5edd-4dbf-bd11-30eb418c571d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_voice_choices(provider, model):\n",
    "    return sorted([(v['name'],v['id']) for v in providers[provider]['voices'].values()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "035c33dd-c8e6-42b4-91d4-6bc5f1b36df3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def update_voice_choices(provider, model):\n",
    "    choices = get_voice_choices(provider, model)\n",
    "    return gr.update(choices=choices,value=choices[0][1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "c97c03af-a377-42e1-93e0-1df957c0e4cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def split_text_as_md(*args, **kwargs):\n",
    "    output = split_text(*args, **kwargs)\n",
    "    return '# Text Splits:\\n' + '<br>----------<br>'.join(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "c5b0156a-f6d4-480a-b7b5-b0899e7520b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def remove_urls_from_markdown(text):\n",
    "    return re.sub(r'\\[([^\\]]+)\\]\\([^\\)]+\\)', r'\\1', text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "db54a6a6-4bdc-430a-b1ea-444c249b77fb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_page_md(url):\n",
    "    # result = requests.get('https://r.jina.ai/'+urllib.parse.quote_plus(url))\n",
    "    result = requests.get('https://r.jina.ai/'+url)\n",
    "    result.raise_for_status()\n",
    "    return remove_urls_from_markdown(result.text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "75891855-6c08-4a42-9ad5-a02e0b43bb3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# test_page_md = get_page_md('https://simonwillison.net/2024/Jun/16/jina-ai-reader/')\n",
    "# test_page_md"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "340089c7-0693-43bc-8fc0-cea4fcd0f3f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "# import json\n",
    "def clean_page_md(text):\n",
    "    max_iters = 15\n",
    "    complete = False\n",
    "    client = openai.OpenAI()\n",
    "\n",
    "    tokens = 0\n",
    "    messages = messages=[\n",
    "        {\"role\": \"system\", \"content\": CLEAN_TEXT_SYSTEM_PROMPT},\n",
    "        {\"role\": \"user\", \"content\": text},\n",
    "        # {\"role\": \"assistant\", \"content\": \"The Los Angeles Dodgers won the World Series in 2020.\"},\n",
    "        # {\"role\": \"user\", \"content\": \"Where was it played?\"}\n",
    "      ]\n",
    "\n",
    "    idx = 0\n",
    "    while complete == False and idx < max_iters:\n",
    "        print('Page Cleaning Iter:',idx)\n",
    "        assert idx < max_iters\n",
    "        idx += 1\n",
    "        response = client.chat.completions.create(\n",
    "          model=\"gpt-4o\",\n",
    "          messages=messages\n",
    "        )\n",
    "        # print(response,'\\n\\n\\n')\n",
    "        response_text = response.choices[0].message.content\n",
    "        if '<<complete>>' in response_text.lower():\n",
    "            complete = True\n",
    "        messages += [\n",
    "            {\"role\": \"assistant\", \"content\": response_text},\n",
    "            {\"role\": \"user\", \"content\": \"Please continue.\"},\n",
    "        ]\n",
    "        tokens += response.usage.total_tokens\n",
    "        # print(json.dumps(messages, indent=4))\n",
    "\n",
    "    client.close()\n",
    "    print('TOKENS CLEANUP:', tokens)\n",
    "    result = ' '.join([o['content'] for o in messages if o['role'] == 'assistant'])\n",
    "    \n",
    "    return result.replace('<<COMPLETE>>','')\n",
    "# res = clean_page_md(test_page_md)\n",
    "# res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "d55dbe5b-83c6-4ba9-836c-48a181badd38",
   "metadata": {},
   "outputs": [],
   "source": [
    "# clean_page_md(get_page_md('https://www.ineteconomics.org/perspectives/blog/from-long-covid-odds-to-lost-iq-points-ongoing-threats-you-dont-know-about'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "7899e7b2-beeb-40a4-a571-a2ccfc7c9618",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_page_text(url:str, ai_clean:bool):\n",
    "    text = get_page_md(url)\n",
    "    if ai_clean:\n",
    "        text = clean_page_md(text)\n",
    "    return text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "e4fb3159-579b-4271-bc96-4cd1e2816eca",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "with gr.Blocks(title='TTS', head='TTS', delete_cache=(3600,3600)) as app:\n",
    "    \n",
    "    ### Define UI ###\n",
    "    gr.Markdown(\"# TTS\")\n",
    "    gr.Markdown(\"\"\"Start typing below and then click **Go** to create the speech from your text.\n",
    "For requests longer than allowed by the API they will be broken into chunks automatically. [Spaces Link](https://matdmiller-tts-openai.hf.space/) | <a href=\"https://matdmiller-tts-openai.hf.space/\" target=\"_blank\">Spaces Link HTML</a>\n",
    "[https://r.jina.ai/](https://r.jina.ai/)\"\"\")\n",
    "    with gr.Row():\n",
    "        input_url = gr.Textbox(max_lines=1, label=\"Optional - Enter a URL\")\n",
    "        input_clean_cb = gr.Checkbox(value=False, label='AI Clean Text')\n",
    "        get_url_content_btn = gr.Button(\"Get URL Contents\")\n",
    "    with gr.Row():\n",
    "        input_text = gr.Textbox(max_lines=100, label=\"Enter text here\")\n",
    "    with gr.Row():\n",
    "        tts_provider_dropdown = gr.Dropdown(value=DEFAULT_PROVIDER,\n",
    "            choices=tuple([(v['name'],k) for k,v in providers.items()]), label='Provider', interactive=True)\n",
    "        tts_model_dropdown = gr.Dropdown(value=DEFAULT_MODEL,choices=get_model_choices(DEFAULT_PROVIDER), \n",
    "                                         label='Model', interactive=True)\n",
    "        tts_voice_dropdown = gr.Dropdown(value=DEFAULT_VOICE,choices=get_voice_choices(DEFAULT_PROVIDER, DEFAULT_MODEL),\n",
    "                                         label='Voice', interactive=True)\n",
    "        input_text_length = gr.Label(label=\"Number of characters\")\n",
    "        generation_cost = gr.Label(label=\"Generation cost\")\n",
    "    with gr.Row():\n",
    "        output_audio = gr.Audio()\n",
    "    go_btn = gr.Button(\"Go\")\n",
    "    clear_btn = gr.Button('Clear')\n",
    "    if REQUIRE_AUTH:\n",
    "        gr.LoginButton()\n",
    "        auth_md = gr.Markdown('')\n",
    "        \n",
    "    chunks_md = gr.Markdown('',label='Chunks')\n",
    "    \n",
    "\n",
    "    ### Define UI Actions ###\n",
    "\n",
    "    get_url_content_btn.click(fn=get_page_text, inputs=[input_url,input_clean_cb], outputs=input_text)\n",
    "    \n",
    "    # input_text \n",
    "    input_text.input(fn=get_input_text_len, inputs=input_text, outputs=input_text_length)\n",
    "    input_text.input(fn=get_generation_cost, \n",
    "                     inputs=[input_text,tts_model_dropdown,tts_provider_dropdown], \n",
    "                     outputs=generation_cost)\n",
    "    input_text.input(fn=split_text_as_md, inputs=[input_text,tts_provider_dropdown], outputs=chunks_md)\n",
    "    \n",
    "    # tts_provider_dropdown\n",
    "    tts_provider_dropdown.change(fn=update_model_choices, inputs=[tts_provider_dropdown], \n",
    "                                 outputs=tts_model_dropdown)\n",
    "    tts_provider_dropdown.change(fn=update_voice_choices, inputs=[tts_provider_dropdown, tts_model_dropdown], \n",
    "                                 outputs=tts_voice_dropdown)\n",
    "    tts_provider_dropdown.change(fn=split_text_as_md, inputs=[input_text,tts_provider_dropdown], outputs=chunks_md)\n",
    "    \n",
    "    # tts_model_dropdown\n",
    "    tts_model_dropdown.change(fn=get_generation_cost, \n",
    "                              inputs=[input_text,tts_model_dropdown,tts_provider_dropdown], outputs=generation_cost)\n",
    "    \n",
    "    \n",
    "    go_btn.click(fn=create_speech, \n",
    "                 inputs=[input_text, tts_provider_dropdown, tts_model_dropdown, tts_voice_dropdown], \n",
    "                 outputs=[output_audio])\n",
    "    \n",
    "    \n",
    "    clear_btn.click(fn=lambda: '', outputs=input_text)\n",
    "\n",
    "    if REQUIRE_AUTH:\n",
    "        app.load(verify_authorization, None, auth_md)\n",
    "    \n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "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",
    "launch_kwargs = {}\n",
    "queue_kwargs = {'default_concurrency_limit':10}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "4b534fe7-4337-423e-846a-1bdb7cccc4ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7860\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": []
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "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": 45,
   "id": "28e8d888-e790-46fa-bbac-4511b9ab796c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Closing server running on port: 7860\n"
     ]
    }
   ],
   "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": 53,
   "id": "0420310d-930b-4904-8bd4-3458ad8bdbd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import nbdev\n",
    "nbdev.export.nb_export('app.ipynb',lib_path='.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9869749d-bc7c-4e24-9dbc-403f665d6200",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b4fe405-b58a-471f-9ce9-e52104012409",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "gradio1",
   "language": "python",
   "name": "gradio1"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}