File size: 94,388 Bytes
ee10821
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
from datetime import datetime
import math
from typing import Iterator
import argparse
import boto3
import uuid

from io import StringIO
import os
import pathlib
import tempfile
import zipfile
import numpy as np
#import sqlite3
from src.utils import duration_detector
import datetime
import shutil
import json

import torch
from src.modelCache import ModelCache
from src.source import get_audio_source_collection
from src.vadParallel import ParallelContext, ParallelTranscription

# External programs
import ffmpeg
from aws_requests_auth.aws_auth import AWSRequestsAuth
from elasticsearch import Elasticsearch, RequestsHttpConnection
from elasticsearch import helpers
import certifi

#logging
from pytz import timezone
import logging
import sys

logging.Formatter.converter = lambda *args: datetime.datetime.now(tz=timezone('Asia/Kolkata')).timetuple()
logging.basicConfig(
    format="%(asctime)s %(levelname)s: %(message)s",
    level=logging.INFO,
    datefmt="%Y-%m-%d %H:%M:%S",
)

console = logging.StreamHandler(sys.stdout)
log = logging.getLogger(__name__)

# UI
import gradio as gr
import traceback
from src.download import ExceededMaximumDuration, download_url
from src.utils import slugify, write_srt, write_vtt
from src.vad import AbstractTranscription, NonSpeechStrategy, PeriodicTranscriptionConfig, TranscriptionConfig, VadPeriodicTranscription, VadSileroTranscription
from src.whisperContainer import WhisperContainer
session = boto3.Session(
            aws_access_key_id='AKIAZB4KTGHMCFPIP6EV',
                aws_secret_access_key='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',
                )
s3 = session.resource('s3')
#client = boto3.client('dynamodb')

import requests
import os

#openai
import openai
from openai import AzureOpenAI

#OPENAI_API_KEY = "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"
OPENAI_API_KEY = "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"

token = f"Bearer {OPENAI_API_KEY}"

url = "https://api.openai.com/v1/audio/transcriptions"
model_name ="whisper-1"

headers ={
    "Authorization": token
    #"Content-Type": "multipart/form-data"
}

#azure whisper
"""
openai.api_key = '142805a982184d289203b387062bfb29'
openai.api_base = 'https://pragyaawhisper3.openai.azure.com'  # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
openai.api_type = "azure"
openai.api_version = "2023-09-01-preview"
model_name = "whisper"
deployment_id = "whisper3" #This will correspond to the custom name you chose for your deployment when you deployed a model."
audio_language="en"
"""
AZURE_OPENAI_ENDPOINT = 'https://pragyaawhisper3.openai.azure.com/'
AZURE_OPENAI_KEY = '142805a982184d289203b387062bfb29'
MODEL_NAME = 'whisper3'
HEADERS = { "api-key" : AZURE_OPENAI_KEY }

# get the Elasticsearch index name from the environment variables
acengage_index = 'acengage-sessions'
esendpoint = 'search-mediassist-indexer-l5jj553cigi5qbir5f4rdzuhoe.us-east-1.es.amazonaws.com' 
#esendpoint = 'search-prime-indexer-jif4ysiafk74aep2w6elx4pn5q.us-east-1.es.amazonaws.com' 
region = 'us-east-1'

# Create the auth token for the sigv4 signature
"""
session = boto3.session.Session()
credentials = session.get_credentials().get_frozen_credentials()
awsauth = AWSRequestsAuth(
            aws_access_key=credentials.access_key,
                aws_secret_access_key=credentials.secret_key,
                    aws_token=credentials.token,
                        aws_host=esendpoint,
                            aws_region=region,
                                aws_service='es'
                                )
"""
# Connect to the elasticsearch cluster using aws authentication. The lambda function
# must have access in an IAM policy to the ES cluster.
es = Elasticsearch(
            hosts=[{'host': esendpoint, 'port': 443}],
                http_auth=('kibanauser','Threeguys01!'),
                    use_ssl=True,
                        verify_certs=True,
                            ca_certs=certifi.where(),
                                timeout=120,
                                    connection_class=RequestsHttpConnection
                                    )

# Limitations (set to -1 to disable)
DEFAULT_INPUT_AUDIO_MAX_DURATION = 600 # seconds

# Whether or not to automatically delete all uploaded files, to save disk space
DELETE_UPLOADED_FILES = True

# Gradio seems to truncate files without keeping the extension, so we need to truncate the file prefix ourself 
MAX_FILE_PREFIX_LENGTH = 17

# Limit auto_parallel to a certain number of CPUs (specify vad_cpu_cores to get a higher number)
MAX_AUTO_CPU_CORES = 8

LANGUAGES = [ 
 "English", "Chinese", "German", "Spanish", "Russian", "Korean", 
 "French", "Japanese", "Portuguese", "Turkish", "Polish", "Catalan", 
 "Dutch", "Arabic", "Swedish", "Italian", "Indonesian", "Hindi", 
 "Finnish", "Vietnamese", "Hebrew", "Ukrainian", "Greek", "Malay", 
 "Czech", "Romanian", "Danish", "Hungarian", "Tamil", "Norwegian", 
 "Thai", "Urdu", "Croatian", "Bulgarian", "Lithuanian", "Latin", 
 "Maori", "Malayalam", "Welsh", "Slovak", "Telugu", "Persian", 
 "Latvian", "Bengali", "Serbian", "Azerbaijani", "Slovenian", 
 "Kannada", "Estonian", "Macedonian", "Breton", "Basque", "Icelandic", 
 "Armenian", "Nepali", "Mongolian", "Bosnian", "Kazakh", "Albanian",
 "Swahili", "Galician", "Marathi", "Punjabi", "Sinhala", "Khmer", 
 "Shona", "Yoruba", "Somali", "Afrikaans", "Occitan", "Georgian", 
 "Belarusian", "Tajik", "Sindhi", "Gujarati", "Amharic", "Yiddish", 
 "Lao", "Uzbek", "Faroese", "Haitian Creole", "Pashto", "Turkmen", 
 "Nynorsk", "Maltese", "Sanskrit", "Luxembourgish", "Myanmar", "Tibetan",
 "Tagalog", "Malagasy", "Assamese", "Tatar", "Hawaiian", "Lingala", 
 "Hausa", "Bashkir", "Javanese", "Sundanese"
]

WHISPER_MODELS = ["tiny", "base", "small", "medium", "large", "large-v1", "large-v2"]

class WhisperTranscriber:
    def __init__(self, input_audio_max_duration: float = DEFAULT_INPUT_AUDIO_MAX_DURATION, vad_process_timeout: float = None, 
                 vad_cpu_cores: int = 1, delete_uploaded_files: bool = DELETE_UPLOADED_FILES, output_dir: str = None):
        self.model_cache = ModelCache()
        self.parallel_device_list = None
        self.gpu_parallel_context = None
        self.cpu_parallel_context = None
        self.vad_process_timeout = vad_process_timeout
        self.vad_cpu_cores = vad_cpu_cores

        self.vad_model = None
        self.inputAudioMaxDuration = input_audio_max_duration
        self.deleteUploadedFiles = delete_uploaded_files
        self.output_dir = output_dir

    def set_parallel_devices(self, vad_parallel_devices: str):
        self.parallel_device_list = [ device.strip() for device in vad_parallel_devices.split(",") ] if vad_parallel_devices else None

    def set_auto_parallel(self, auto_parallel: bool):
        if auto_parallel:
            if torch.cuda.is_available():
                self.parallel_device_list = [ str(gpu_id) for gpu_id in range(torch.cuda.device_count())]

            self.vad_cpu_cores = min(os.cpu_count(), MAX_AUTO_CPU_CORES)
            print("[Auto parallel] Using GPU devices " + str(self.parallel_device_list) + " and " + str(self.vad_cpu_cores) + " CPU cores for VAD/transcription.")

    # Entry function for the simple tab
    def transcribe_webui_simple(self, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow):
        return self.transcribe_webui(modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)

    # Entry function for the full tab
    def transcribe_webui_full_verbatim(self, client,  process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, 
                                    initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str, 
                                    condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float, 
                                    compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):

        # Handle temperature_increment_on_fallback
        if temperature_increment_on_fallback is not None:
            temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
        else:
            temperature = [temperature]

        return self.transcribe_webui_verbatim(client,  process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, 
                                     initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
                                     condition_on_previous_text=condition_on_previous_text, fp16=fp16,
                                     compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
     # Entry function for the full tab
    def transcribe_webui_full_verbatim_qa(self, client,  process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
                                          qSet1:str, qSet2:str, qSet3:str,qSet4:str,initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str,
                                    condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
                                    compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):

        # Handle temperature_increment_on_fallback
        if temperature_increment_on_fallback is not None:
            temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
        else:
            temperature = [temperature]

        return self.transcribe_webui_verbatim_qa(client,  process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
                                     initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
                                     condition_on_previous_text=condition_on_previous_text, fp16=fp16,
                                     compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
    
    def transcribe_webui_full(self, client,  process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
                                    initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str,
                                    condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
                                    compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):

        # Handle temperature_increment_on_fallback
        if temperature_increment_on_fallback is not None:
            temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
        else:
            temperature = [temperature]

        return self.transcribe_webui(client,  process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
                                     initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
                                     condition_on_previous_text=condition_on_previous_text, fp16=fp16,
                                     compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
    def transcribe_webui(self,client,  process,counsellor,  modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
        validfields = True
        fileId = str(uuid.uuid4())
        try:
            sources = self.__get_source(urlData, multipleFiles, microphoneData)
            if languageName is None:
                languageName = 'english'
            #print("Client:"+client+" ,  "+"Counsellor:"+counsellor+"  ,  "+"Process:"+process)
            log.info(languageName)
            if counsellor is None or counsellor == '' or process is None or process == '':
                print (" Invalid fields")
                validfields = False
                return "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs","There was an error while processing your input. Please retry your input."
            client = 'Other' if client is None or client== '' else client
            #counsellor = 'Select a counsellor from drodown' if counsellor is None or counsellor == ''else counsellor
            #process = 'Select a process from dropdown' if process is None or process == '' else process
            
            client_counsellor = "Client:"+client+" ,  "+"Counsellor:"+counsellor+"  ,  "+"Process:"+process
            try:
                selectedLanguage = languageName.lower() if len(languageName) > 0 else None
                selectedModel = modelName if modelName is not None else "base"

                model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)

                # Result
                download = []
                zip_file_lookup = {}
                text = ""
                vtt = ""

                # Write result
                downloadDirectory = tempfile.mkdtemp()
                source_index = 0

                outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory

                # Execute whisper
                for source in sources:
                    source_prefix = ""

                    if (len(sources) > 1):
                        # Prefix (minimum 2 digits)
                        source_index += 1
                        source_prefix = str(source_index).zfill(2) + "_"
                        #log.info("Transcribing ", fileId+'-'+source.source_path)
                    #raise Exception("Ex")
                    hours, mins, secs = duration_detector(source.source_path)
                    #Log duration in DB before Transcibe line
               
                     # Transcribe
                    """
                    result = self.transcribe_file(model, source.source_path, 'english', task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)

                    source_download, source_text, source_vtt = self.write_result(result, filePrefix, outputDirectory)

                    if len(sources) > 1:
                        # Add new line separators
                        if (len(source_text) > 0):
                            source_text += os.linesep + os.linesep
                        if (len(source_vtt) > 0):
                            source_vtt += os.linesep + os.linesep

                        # Append file name to source text too
                        source_text = source.get_full_name() + ":" + os.linesep + source_text
                        source_vtt = source.get_full_name() + ":" + os.linesep + source_vtt

                    # Add to result
                    download.extend(source_download)
                    text += source_text
                    vtt += source_vtt

                    if (len(sources) > 1):
                        # Zip files support at least 260 characters, but we'll play it safe and use 200
                        zipFilePrefix = slugify(source_prefix + source.get_short_name(max_length=200), allow_unicode=True)

                        # File names in ZIP file can be longer
                        for source_download_file in source_download:
                            # Get file postfix (after last -)
                            filePostfix = os.path.basename(source_download_file).split("-")[-1]
                            zip_file_name = zipFilePrefix + "-" + filePostfix
                            zip_file_lookup[source_download_file] = zip_file_name
                    log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
                    """
                    #openai whisper
                    
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
                    response = None
                    try:
                        with open(source.source_path,"rb") as file:
                            file_content = file.read()

                        payload = {
                      "name": os.path.basename(source.source_path),
                      # "response_format": "json",
                      "prompt": "transcribe this Chapter",
                      "language": 'en',
                      "model": model_name
                    }
                        print("payload", payload)
                        files = {
                       "file": (os.path.basename(source.source_path), file_content, "audio/mp3")
                         }

                        response = requests.post(url, headers=headers, data=payload, files=files)
                        log.info(response.json())
                    except Exception:
                        log.info(response)
                        log.info("Error occurred while reading openai response")
                        print(traceback.format_exc())
                        return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
                    
                    """
                    #azure whisper
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
                    response = None
                    try:
                        with open(source.source_path,"rb") as file:
                            response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
                                 headers=HEADERS,
                                 files={'file': file})
                            log.info(response.json())
                    except Exception:
                        log.info(response)
                        log.info("Error occurred while reading openai response")
                        print(traceback.format_exc())
                        return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
                     """
                text = '',
                if "text" in response.json():
                    text = response.json()["text"]
                    output_files = []
                    output_files.append(self.__create_file(text, outputDirectory,fileId + "-transcript.txt"));


                    bucket = 'acengage-bucket-v09kjo18oktg'
                    try:
                       for f in output_files:
                           print('source_text..', os.path.abspath(f))
                           s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
                    except:
                       print("Error while writing to s3, proceed")

                else:
                    text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'

                return client_counsellor,text

            finally:
                # Cleanup source
                if self.deleteUploadedFiles and validfields:
                    for source in sources:
                        print("Deleting source file " + source.source_path)

                        try:
                            bucket = 'acengage-bucket-v09kjo18oktg'
                            key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
                            s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
                            file_url = "https://"+bucket+".s3.amazonaws.com/"+key
                            #Log duration in DB before Transcibe line
                            try:
                                doc = {
                                        'client': client,
                                        'counsellor': counsellor,
                                        'process': process,
                                        'language':languageName,
                                        'file': os.path.basename(source.source_path),
                                                       'hours': hours,
                                                       'mins': mins,
                                                       'secs': secs,
                                                       'request_time': datetime.datetime.now(),
                                                       'audio_url':file_url
                                         }
                                res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
                                #logger.info(json.dumps(res, indent=4))
                                data_string = json.dumps(doc, indent=2, default=str)
                                key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
                                s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
                            except Exception:
                                   print ("Error occurred while inserting duration data")
                                   print(traceback.format_exc())
                            os.remove(source.source_path)
                        except Exception as e:
                            # Ignore error - it's just a cleanup
                            print("Error deleting source file " + source.source_path + ": " + str(e))
        
        except ExceededMaximumDuration as e:
            return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s")
        except Exception as ex:
            print(traceback.format_exc())
            #return client_counsellor, [],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
            return client_counsellor,"There was an error while processing your input. Please retry your input."

    def transcribe_webui_verbatim(self,client,  process,counsellor,  modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
        validfields = True
        fileId = str(uuid.uuid4())
        try:
            sources = self.__get_source(urlData, multipleFiles, microphoneData)
            if languageName is None:
                languageName = 'english'
            #print("Client:"+client+" ,  "+"Counsellor:"+counsellor+"  ,  "+"Process:"+process)
            #log.info("Language Chosen: "+ languageName)
            if counsellor is None or counsellor == '' or process is None or process == '':
                print (" Invalid fields")
                validfields = False
                return "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs",[],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
            client = 'Other' if client is None or client== '' else client
            #counsellor = 'Select a counsellor from drodown' if counsellor is None or counsellor == ''else counsellor
            #process = 'Select a process from dropdown' if process is None or process == '' else process
            
            client_counsellor = "Client:"+client+" ,  "+"Counsellor:"+counsellor+"  ,  "+"Process:"+process
            try:
                selectedLanguage = languageName.lower() if len(languageName) > 0 else None
                selectedModel = modelName if modelName is not None else "base"

                model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)

                # Result
                download = []
                zip_file_lookup = {}
                text = ""
                vtt = ""

                # Write result
                downloadDirectory = tempfile.mkdtemp()
                source_index = 0

                outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory

                # Execute whisper
                for source in sources:
                    source_prefix = ""

                    if (len(sources) > 1):
                        # Prefix (minimum 2 digits)
                        source_index += 1
                        source_prefix = str(source_index).zfill(2) + "_"
                        #log.info("Transcribing ", fileId+'-'+source.source_path)
                    #raise Exception("Ex")
                    hours, mins, secs = duration_detector(source.source_path)
                    #Log duration in DB before Transcibe line

                    # Transcribe
                    """
                    result = self.transcribe_file(model, source.source_path, 'english', task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)

                    source_download, source_text, source_vtt = self.write_result(result, filePrefix, outputDirectory)

                    if len(sources) > 1:
                        # Add new line separators
                        if (len(source_text) > 0):
                            source_text += os.linesep + os.linesep
                        if (len(source_vtt) > 0):
                            source_vtt += os.linesep + os.linesep

                        # Append file name to source text too
                        source_text = source.get_full_name() + ":" + os.linesep + source_text
                        source_vtt = source.get_full_name() + ":" + os.linesep + source_vtt

                    # Add to result
                    download.extend(source_download)
                    text += source_text
                    vtt += source_vtt

                    if (len(sources) > 1):
                        # Zip files support at least 260 characters, but we'll play it safe and use 200
                        zipFilePrefix = slugify(source_prefix + source.get_short_name(max_length=200), allow_unicode=True)

                        # File names in ZIP file can be longer
                        for source_download_file in source_download:
                            # Get file postfix (after last -)
                            filePostfix = os.path.basename(source_download_file).split("-")[-1]
                            zip_file_name = zipFilePrefix + "-" + filePostfix
                            zip_file_lookup[source_download_file] = zip_file_name
                    log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
                    """
                    #openai whisper
                    
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
                    response = None
                    try:
                        with open(source.source_path,"rb") as file:
                            file_content = file.read()

                        payload = {
                      "name": os.path.basename(source.source_path),
                      # "response_format": "json",
                      "prompt": "transcribe this Chapter",
                      "language": 'en',
                      "model": model_name
                    }
                        print("payload", payload)
                        files = {
                       "file": (os.path.basename(source.source_path), file_content, "audio/mp3")
                         }

                        response = requests.post(url, headers=headers, data=payload, files=files)
                        log.info(response.json())
                    except Exception:
                        log.info(response)
                        log.info("Error occurred while reading openai response")
                        print(traceback.format_exc())
                        return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
                     
                    """
                    #azure whisper
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
                    response = None
                    try:
                        with open(source.source_path,"rb") as file:
                            response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
                                 headers=HEADERS,
                                 files={'file': file})
                            log.info(response.json())
                    except Exception:
                        log.info(response)
                        log.info("Error occurred while reading openai response")
                        print(traceback.format_exc())
                        return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
                     """
                text = ''
                verbatimAzure = ''
                if "text" in response.json(): 
                    text = response.json()["text"]
                    output_files = []
                    output_files.append(self.__create_file(text, outputDirectory, filePrefix + "-transcript.txt"));

                    #openai.api_type = "azure"
                    #openai.api_base = "https://pragyaaai.openai.azure.com/"
                    #openai.api_version = "2023-03-15-preview"
                    #openai.api_key = "9ba4e0dcfbf841fbb946c55c52caae1b"

                    #openai.api_key = OPENAI_API_KEY
                    api_base = 'https://pragyaagpt4.openai.azure.com/'
                    api_key="9fb5af1332a648b1bba4198731e389bd"
                    deployment_name = 'pragyaagpt4turbo'
                    api_version = '2023-12-01-preview' # this might change in the future

                    azureClient = AzureOpenAI(
    api_key=api_key,
    api_version=api_version,
    base_url=f"{api_base}openai/deployments/{deployment_name}/",
)
                    prompt = "Create a detailed summary in just one paragraph, in first person , as if the employees is himself/ herself speaking .The sentence should always start from I worked in the organization. A minimum of 150 words need to be captured verbatim. Remove prefixes like Mr. Mrs. in the name.Provide more information in role and reasons of leaving.  In red flag calls where abusive or rude language is spoken from managers, such instances need to be captured in the double inverted commas " " and all such reasons that led the employee to leave due to the manager. For example, \"I will make you lose your job,\" etc., \"You are useless.\". Keep the abusive language if any in its original tone and don't translate it. Don't use short forms as in example , Example: Should not or would not should not be replaced by Shouldn't or wouldn't .Capture only one main reason , not many reasons for leaving and elaborate it. In case of read flags on manager using abusive language capture all instances of abusive words, rude and inappropriate language used and capture them within inverted commas. Specify tenure at the organisation in years and months , designation. Remove the name of the organisation employee last worked with and just mention last organisation . Specify only the main or primary reason of leaving the organisation in detail, all negative sentiments on manager or organisation such as manager's rude behavior, read flags if any, was the employee happy or unhappy at the organization, remove rating information of managers if available. Exclude employee's rating information. Mention hike percentage if available.  Exclude organisation joining and leaving dates. Include manager's name and designation towards beginning of the paragraph . If retention details is mentioned ,mention that before the current company details mentioned by employee. Exclude any survey related discussions. Drop employee's name in the summary. Mentioned notice period if it's is mentioned. \n ###Example of good output### \n - 'I worked in my last organization for a period of 3 years and 2 months as a software engineer in the department of Engineering in Bangalore. My reporting manager was Mr. Rakesh, who was the senior Engineering Manager and my skip-level manager was Mr. Sanjay who was a Director.I had a good experience working in the organization for 3 years. In my day-to-day role, I was working as a developer.I left the organization because of career growth. My manager or the HR tried to retain me promising me a promotion.I served the notice period of 90 days. I am currently working at IBM, Banglore, as a Technical Lead and I got 60% hike.'\n - I worked with Tata Capital as a Relationship Manager in the Department of Supply Chain Finance for 2 years. I reported to Himanshu Sood- ASM. He was a very genuine guy, and I was lucky to have started my career under his mentorship. However, the main reason for leaving the organization was the Regional Sales Manager, Rahul Sharma, who was biased towards some employees and practiced favoritism. He used to allocate leads to his preferred RMs (did not want to disclose the names) and not to me. Also, he used to talk highly about them and try to take them to another level. But he never appreciated me, which was affecting my motivation, confidence, and quality of work. He was biased by the rating system as well. According to the company policy, one could only get a default rating in the first six months. But his preferred R.M. was getting a very good rating after 6 months. My rating was just B+. As he was allocating leads to his favorites, they could earn double the incentives I was earning, even after doing the same job, and that affected me a lot. Even he used to talk rudely with me while behaving politely with his loved ones. I have been facing this issue for the last two years. I informed my Manager about this, and he used to take the situation under control and motivate me. That was the only reason I was there for 2 years. I did not approach anybody else about this issue. In the last 2 years, 8–9 people, including Rakes Thawal, left the organization because of his biased behavior. My Manager tried to retain me by promising me to give a better appraisal next year, but there was no formal assurance, so I put down my papers. Currently, I am working as an ASM at SG Global Finco Limited, with a salary of 83%.' Finally also mention all names of employees left the organisation for similar reasons of leaving."

                    if process=='CE':
                        prompt = "Create a detailed summary in just one paragraph, in second person , as someone else is speaking on behalf of employee. Specify last working day of the candidate. Specify if the candidate has accepted the offer or not, current organisation, date of joining in the new organisation, all reasons for leaving the organisation,counter offer details like offered CTC, designation and counter company name. For offers declined, specify details similar to candidates joining. Include counter offer details as applicable , if any.\n ###Example of good output### \n - '1.FIRST CALL DECLINE- The candidate declined the offer of Siemens a month back and joined Amazon on the 6th of November. She said that Amazon had matched her expectations in terms of compensation. Siemens had given her 30 LPA. She was expecting around 35 LPA. During the interview also had a discussion regarding the same, but it was informed to her that the budget was around 30 LPA to 31 LPA. She had accepted the offer of Siemens. She was giving an interview for Amazon parallelly but received the offer from Amazon way after Siemens's offer. The joining date of Siemens was also in the month of November. She was initially in touch with HR Manisha and HR did call her, but she couldn't answer the call as she was in the meeting. When she tried to connect with HR Manisha, she got to know that HR had already left the organization. She tried to connect with other HR but did not receive any response. She had sent a couple of emails to Siemens regarding the counteroffer but did not receive any response. Then she decided to decline the offer. She was happy with the role and designation offered by Siemens. She was also fine with the location and hybrid work mode. The candidate also mentioned that the role offered by Amazon is similar to the role offered by Siemens. She was previously working for Bosch and the last working day was on the 30th of October. She was happy with the recruitment process. RF was captured. The highlights and benefits of the company were shared."

                    try:
                        """
                        result = openai.ChatCompletion.create(
                     #     engine="gpt35turbo",
                            model="gpt-4-1106-preview",
                            messages=[{"role":"system","content":prompt},
                                      {"role": "user","content":text}],
                          temperature=0.7,
                          max_tokens=800,
                          top_p=0.95,
                          frequency_penalty=0,
                          presence_penalty=0,
                          stop=None)
                        """
                        result = azureClient.chat.completions.create(
    model=deployment_name,
     messages=[{"role":"system","content":prompt},
                                      {"role": "user","content":text}],
                          temperature=0.7,
                          max_tokens=2000,
                          top_p=0.95,
                          frequency_penalty=0,
                          presence_penalty=0,
                          stop=None
)
                        print("verbatimAzure", result)
                        for choice in result.choices:
                            verbatimAzure += choice.message.content
                    except:
                        print("Error while generating verbatim")
                        traceback.print_exc()
                        verbatimAzure = "Some problem encountered while generating verbatim. The length of transcript could be big or it is taking longer time to process"

                    output_files = []
                    output_files.append(self.__create_file(text, outputDirectory, fileId + "-transcript.txt"));
                    output_files.append(self.__create_file(verbatimAzure, outputDirectory, fileId + "-verbatim.txt"));

                    bucket = 'acengage-bucket-v09kjo18oktg'
                    try:
                       for f in output_files:
                           print('source_text..', os.path.abspath(f))
                           s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
                    except:
                       print("Error while writing to s3, proceed")

                else:
                    text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'

                return client_counsellor,text,verbatimAzure

            finally:
                # Cleanup source
                if self.deleteUploadedFiles and validfields:
                    for source in sources:
                        print("Deleting source file " + source.source_path)

                        try:
                            bucket = 'acengage-bucket-v09kjo18oktg'
                            key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
                            s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
                            file_url = "https://"+bucket+".s3.amazonaws.com/"+key
                            #Log duration in DB before Transcibe line
                            try:
                                doc = {
                                        'client': client,
                                        'counsellor': counsellor,
                                        'process': process,
                                        'language':languageName,
                                        'verbatim':'yes',
                                        'file': os.path.basename(source.source_path),
                                                       'hours': hours,
                                                       'mins': mins,
                                                       'secs': secs,
                                                       'request_time': datetime.datetime.now(),
                                                       'audio_url':file_url
                                         }
                                res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
                                #logger.info(json.dumps(res, indent=4))
                                data_string = json.dumps(doc, indent=2, default=str)
                                key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
                                s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
                            except Exception:
                                   print ("Error occurred while inserting duration data")
                                   print(traceback.format_exc())
                            os.remove(source.source_path)
                        except Exception as e:
                            # Ignore error - it's just a cleanup
                            print("Error deleting source file " + source.source_path + ": " + str(e))
        
        except ExceededMaximumDuration as e:
            return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s"), "[ERROR]"
        except Exception as ex:
            print(traceback.format_exc())
            #return client_counsellor, [],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."

    def transcribe_webui_verbatim_qa(self,client,  process,counsellor,  modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
        validfields = True
        fileId = str(uuid.uuid4())
        try:
            sources = self.__get_source(urlData, multipleFiles, microphoneData)
            if languageName is None:
                languageName = 'english'
            if counsellor is None or counsellor == '' or process is None or process == '':
                print (" Invalid fields")
                validfields = False
                return "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs",[],"There was an error while processing your input. Please retry your input.",("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
            client = 'Other' if client is None or client== '' else client

            client_counsellor = "Client:"+client+" ,  "+"Counsellor:"+counsellor+"  ,  "+"Process:"+process
            try:
                selectedLanguage = languageName.lower() if len(languageName) > 0 else None
                selectedModel = modelName if modelName is not None else "base"

                model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)

                # Result
                download = []
                zip_file_lookup = {}
                text = ""
                vtt = ""

                # Write result
                downloadDirectory = tempfile.mkdtemp()
                source_index = 0

                outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory

                # Execute whisper
                for source in sources:
                    source_prefix = ""

                    if (len(sources) > 1):
                        # Prefix (minimum 2 digits)
                        source_index += 1
                        source_prefix = str(source_index).zfill(2) + "_"
                        #log.info("Transcribing ", fileId+'-'+source.source_path)
                    #raise Exception("Ex")
                    hours, mins, secs = duration_detector(source.source_path)
                    #Log duration in DB before Transcibe line

                    # Transcribe
                    log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
                    # result = self.transcribe_file(model, source.source_path, selectedLanguage, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
                    #openai whisper
                    
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
                    response = None
                    try:
                        with open(source.source_path,"rb") as file:
                            file_content = file.read()

                        payload = {
                      "name": os.path.basename(source.source_path),
                      # "response_format": "json",
                      "prompt": "transcribe this Chapter",
                      "language": 'en',
                      "model": model_name
                    }
                        print("payload", payload)
                        files = {
                       "file": (os.path.basename(source.source_path), file_content, "audio/mp3")
                         }
                        response = requests.post(url, headers=headers, data=payload, files=files)
                        log.info(response.json())
                    except Exception:
                        log.info(response)
                        log.info("Error occurred while reading openai response")
                        print(traceback.format_exc())
                        return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
                    
                    """
                    #azure whisper
                    filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
                    response = None
                    try:
                        with open(source.source_path,"rb") as file:
                            response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
                                 headers=HEADERS,
                                 files={'file': file})
                            log.info(response.json())
                    except Exception:
                        log.info(response)
                        log.info("Error occurred while reading openai response")
                        print(traceback.format_exc())
                        return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
                    """
                text = '',
                qaResult1 = ''
                qaResult2 = ''
                qaResult3 = ''
                qaResult4 = ''
                if "text" in response.json():
                    text = response.json()["text"]
                    
                     #openai.api_key = "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"
                   # openai.api_key = "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"
                    api_base = 'https://pragyaagpt4.openai.azure.com/'
                    api_key="9fb5af1332a648b1bba4198731e389bd"
                    deployment_name = 'pragyaagpt4turbo'
                    api_version = '2023-12-01-preview' # this might change in the future

                    azureClient = AzureOpenAI(
    api_key=api_key,
    api_version=api_version,
    base_url=f"{api_base}openai/deployments/{deployment_name}/",
)
                    qaResult1 = azureClient.chat.completions.create(
    model=deployment_name,
    messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list. provide the answers in first person as if employee is answering.\n1.What triggered your decision to leave? \n2.Who spoke to you after you resigned? \n3.In your opinion did they make a genuine effort to retain you? \n4.What could the organization have done to retain you?  "},
                                {"role": "user","content":text}],
    temperature= 0.05,
    max_tokens=2000,
    top_p= 1,
    frequency_penalty= 0,
    presence_penalty= 0,
    stop=None
)

                    #log.info("result 1",qaResult1)
                    qaResult1 = qaResult1.choices[0].message.content

                    qaResult2 = azureClient.chat.completions.create(
    model=deployment_name,
    messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list. provide the answers in first person as if employee is answering. \n1.Role clarity- Were you given clarity about your role before you joined? If less than 7, why? \n2.On-boarding process- Did your on-boarding process go on smoothly and on time? If less than 7, why? \n3.Time taken for the recruitment process- Was the overall interview organized and quick? If less than 7, why? If less than 7, why? \n4.Hand-holding- Were you given the required support, guidance and knowledge transfer for your new role? If less than 7 ,why?\n5.JD and current role match- Does your current role match the JD that was provided to you at the time of joining? If less than 7, why? \n6.What was done well during the overall recruitment process? \n7.What could have been done better during the overall recruitment process? "}, {"role": "user","content":text}],
    temperature= 0.05,
    max_tokens=256,
    top_p= 1,
    frequency_penalty= 0,
    presence_penalty= 0,
    stop=None
)

                    #log.info("result 2",qaResult2)
                    #log.info(qaResult2['choices'][0]['message']['content'])
                    qaResult2 = qaResult2.choices[0].message.content

                    qaResult3 = azureClient.chat.completions.create(
    model=deployment_name,
    messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list.  follow the instructions provided at the end of last question \n1.What is your supervisor's name? \n2.What is your supervisor's designation? \n3.Subject knowledge - Do you believe your manager was competent to be able to deal with the issues you and your team mates have during your workday? If less than 7, why? \n4.Team management- How effectively did your manager work with the resources provided to him/her to get the task at hand completed? If less than 7, why? \n5.Being unbiased- Did your Manager give fair opportunities to everyone in the team? If less than 7, why? \n6.Offering growth opportunities- Did you Manager encourage growth and allow you to explore new tasks? \n7.Providing feedback - Was the feedback provided by the manager to you fair and clear which outlined a clear way for you to grow as an individual? If less than 7, why? \n8.Given a chance would you like to work with your current manager in the future? \n9.Senior leadership - opportunity to interact and visibility . If less than 7, why? \n10.Role satisfaction - having a sense of direction with what you do and having the required tools/ resources to do this. If less than 7, why? \n11.Rewards and Recognition- being rewarded and recognized adequately for hard work and effort.If less than 7, why? \n12.Performance Management System(includes Growth Opportunities)- level of transparency in the appraisal and promotion process. \n13.Work-Life Balance- being able maintain a healthy balance between work life and personal life?If less than 7, why? \n###Instrutions### \nprovide the answers in first person as if employee is answering. format the answers in readable way. Please follow few instructions in instructions section befoew questions .\nInstructions: In case Name and Designation asked, provide the anaswer as in the example below .\n Example of Answer: Supervisors name: Bishwajit Samanth \n Designation: Director . In case employee is giving a rating and comments, proviem them as in example. \nExample of answer: Ratings: 2/10 , Comments: There was minimal interaction with the junior resources and he wasn't even aware of what the other team members were doing."}, {"role": "user","content":text}],
    temperature= 0.05,
    max_tokens=256,
    top_p= 1,
    frequency_penalty= 0,
    presence_penalty= 0,
    stop=None
)                   
                    #log.info("result 3",qaResult3)
                    #log.info(qaResult3['choices'][0]['message']['content'])
                    qaResult3 = qaResult3.choices[0].message.content

                    qaResult4 = azureClient.chat.completions.create(
    model=deployment_name,
    messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list.  provide the answers in first person as if employee is answering. \n1.How likely are you to recommend the organization to you friends and family to work in on a scale of 0-10 (0 being the lowest)? \n2.eNPS Comments \n3.What is the one thing you liked the most about the organization? \n4.Would you be willing to re-join? \n5.Where are you working now? \n6.Did you join the new company in the same industry as you were working for in the previous company? \n7.What is your current designation? \n8.How much of a hike have you received? "}, {"role": "user","content":text}],
    temperature= 0.05,
    max_tokens=256,
    top_p= 1,
    frequency_penalty= 0,
    presence_penalty= 0,
    stop=None
)
                    #log.info("result 4",qaResult4)
                    #log.info(qaResult4['choices'][0]['message']['content'])
                    qaResult4 = qaResult4.choices[0].message.content

                    output_files = []
                    output_files.append(self.__create_file(text, outputDirectory, fileId + "-transcript.txt"));

                    bucket = 'acengage-bucket-v09kjo18oktg'
                    try:
                       for f in output_files:
                           print('source_text..', os.path.abspath(f))
                           s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
                    except:
                       print("Error while writing to s3, proceed")

                else:
                    text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'

                return client_counsellor,text,qaResult1,qaResult2,qaResult3,qaResult4

            finally:
                # Cleanup source
                if self.deleteUploadedFiles and validfields:
                    for source in sources:
                        print("Deleting source file " + source.source_path)

                        try:
                            bucket = 'acengage-bucket-v09kjo18oktg'
                            key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
                            s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
                            file_url = "https://"+bucket+".s3.amazonaws.com/"+key
                            #Log duration in DB before Transcibe line
                            try:
                                doc = {
                                        'client': client,
                                        'counsellor': counsellor,
                                        'process': process,
                                        'language':languageName,
                                        'verbatim_with_qa':'yes',
                                        'file': os.path.basename(source.source_path),
                                                       'hours': hours,
                                                       'mins': mins,
                                                       'secs': secs,
                                                       'request_time': datetime.datetime.now(),
                                                       'audio_url':file_url
                                         }
                                res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
                                #logger.info(json.dumps(res, indent=4))
                                data_string = json.dumps(doc, indent=2, default=str)
                                key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
                                s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
                            except Exception:
                                   print ("Error occurred while inserting duration data")
                                   print(traceback.format_exc())
                            os.remove(source.source_path)
                        except Exception as e:
                            # Ignore error - it's just a cleanup
                            print("Error deleting source file " + source.source_path + ": " + str(e))

        except ExceededMaximumDuration as e:
            return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s"), "[ERROR]"
        except Exception as ex:
            print(traceback.format_exc())
            #return client_counsellor, [],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."

    def transcribe_file(self, model: WhisperContainer, audio_path: str, language: str, task: str = None, vad: str = None, 
                        vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1, **decodeOptions: dict):
        
        initial_prompt = decodeOptions.pop('initial_prompt', None)

        if ('task' in decodeOptions):
            task = decodeOptions.pop('task')

        # Callable for processing an audio file
        whisperCallable = model.create_callback(language, task, initial_prompt, **decodeOptions)

        # The results
        if (vad == 'silero-vad'):
            # Silero VAD where non-speech gaps are transcribed
            process_gaps = self._create_silero_config(NonSpeechStrategy.CREATE_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
            result = self.process_vad(audio_path, whisperCallable, self.vad_model, process_gaps)
        elif (vad == 'silero-vad-skip-gaps'):
            # Silero VAD where non-speech gaps are simply ignored
            skip_gaps = self._create_silero_config(NonSpeechStrategy.SKIP, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
            result = self.process_vad(audio_path, whisperCallable, self.vad_model, skip_gaps)
        elif (vad == 'silero-vad-expand-into-gaps'):
            # Use Silero VAD where speech-segments are expanded into non-speech gaps
            expand_gaps = self._create_silero_config(NonSpeechStrategy.EXPAND_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
            result = self.process_vad(audio_path, whisperCallable, self.vad_model, expand_gaps)
        elif (vad == 'periodic-vad'):
            # Very simple VAD - mark every 5 minutes as speech. This makes it less likely that Whisper enters an infinite loop, but
            # it may create a break in the middle of a sentence, causing some artifacts.
            periodic_vad = VadPeriodicTranscription()
            period_config = PeriodicTranscriptionConfig(periodic_duration=vadMaxMergeSize, max_prompt_window=vadPromptWindow)
            result = self.process_vad(audio_path, whisperCallable, periodic_vad, period_config)

        else:
            if (self._has_parallel_devices()):
                # Use a simple period transcription instead, as we need to use the parallel context
                periodic_vad = VadPeriodicTranscription()
                period_config = PeriodicTranscriptionConfig(periodic_duration=math.inf, max_prompt_window=1)

                result = self.process_vad(audio_path, whisperCallable, periodic_vad, period_config)
            else:
                # Default VAD
                result = whisperCallable.invoke(audio_path, 0, None, None)

        return result

    def process_vad(self, audio_path, whisperCallable, vadModel: AbstractTranscription, vadConfig: TranscriptionConfig):
        if (not self._has_parallel_devices()):
            # No parallel devices, so just run the VAD and Whisper in sequence
            return vadModel.transcribe(audio_path, whisperCallable, vadConfig)

        gpu_devices = self.parallel_device_list

        if (gpu_devices is None or len(gpu_devices) == 0):
            # No GPU devices specified, pass the current environment variable to the first GPU process. This may be NULL.
            gpu_devices = [os.environ.get("CUDA_VISIBLE_DEVICES", None)]

        # Create parallel context if needed
        if (self.gpu_parallel_context is None):
            # Create a context wih processes and automatically clear the pool after 1 hour of inactivity
            self.gpu_parallel_context = ParallelContext(num_processes=len(gpu_devices), auto_cleanup_timeout_seconds=self.vad_process_timeout)
        # We also need a CPU context for the VAD
        if (self.cpu_parallel_context is None):
            self.cpu_parallel_context = ParallelContext(num_processes=self.vad_cpu_cores, auto_cleanup_timeout_seconds=self.vad_process_timeout)

        parallel_vad = ParallelTranscription()
        return parallel_vad.transcribe_parallel(transcription=vadModel, audio=audio_path, whisperCallable=whisperCallable,  
                                                config=vadConfig, cpu_device_count=self.vad_cpu_cores, gpu_devices=gpu_devices, 
                                                cpu_parallel_context=self.cpu_parallel_context, gpu_parallel_context=self.gpu_parallel_context) 

    def _has_parallel_devices(self):
        return (self.parallel_device_list is not None and len(self.parallel_device_list) > 0) or self.vad_cpu_cores > 1

    def _concat_prompt(self, prompt1, prompt2):
        if (prompt1 is None):
            return prompt2
        elif (prompt2 is None):
            return prompt1
        else:
            return prompt1 + " " + prompt2

    def _create_silero_config(self, non_speech_strategy: NonSpeechStrategy, vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1):
        # Use Silero VAD 
        if (self.vad_model is None):
            self.vad_model = VadSileroTranscription()

        config = TranscriptionConfig(non_speech_strategy = non_speech_strategy, 
                max_silent_period=vadMergeWindow, max_merge_size=vadMaxMergeSize, 
                segment_padding_left=vadPadding, segment_padding_right=vadPadding, 
                max_prompt_window=vadPromptWindow)

        return config

    def write_result(self, result: dict, source_name: str, output_dir: str):
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        text = result["text"]
        language = result["language"]
        languageMaxLineWidth = self.__get_max_line_width(language)

        print("Max line width " + str(languageMaxLineWidth))
        vtt = self.__get_subs(result["segments"], "vtt", languageMaxLineWidth)
        srt = self.__get_subs(result["segments"], "srt", languageMaxLineWidth)

        output_files = []
        output_files.append(self.__create_file(srt, output_dir, source_name + "-subs.srt"));
        output_files.append(self.__create_file(vtt, output_dir, source_name + "-subs.vtt"));
        output_files.append(self.__create_file(text, output_dir, source_name + "-transcript.txt"));

        dest = '/content/drive/MyDrive/aceNgage_transcripts/'
        # try:
            # if not os.path.exists(os.path.dirname(dest)):
                # os.makedirs(os.path.dirname(dest))
        # except OSError as err:
            # print(err)
        # for f in output_files:
            # print('source_text..', os.path.abspath(f))
            # shutil.copy(os.path.abspath(f),dest)
        bucket = 'acengage-bucket-v09kjo18oktg'
        try:
            for f in output_files:
                print('source_text..', os.path.abspath(f))
                s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
        except:
            print("Error while writing to s3, proceed")
        return output_files, text, vtt

    def clear_cache(self):
        self.model_cache.clear()
        self.vad_model = None

    def __get_source(self, urlData, multipleFiles, microphoneData):
        return get_audio_source_collection(urlData, multipleFiles, microphoneData, self.inputAudioMaxDuration)

    def __get_max_line_width(self, language: str) -> int:
        if (language and language.lower() in ["japanese", "ja", "chinese", "zh"]):
            # Chinese characters and kana are wider, so limit line length to 40 characters
            return 40
        else:
            # TODO: Add more languages
            # 80 latin characters should fit on a 1080p/720p screen
            return 80

    def __get_subs(self, segments: Iterator[dict], format: str, maxLineWidth: int) -> str:
        segmentStream = StringIO()

        if format == 'vtt':
            write_vtt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
        elif format == 'srt':
            write_srt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
        else:
            raise Exception("Unknown format " + format)

        segmentStream.seek(0)
        return segmentStream.read()

    def __create_file(self, text: str, directory: str, fileName: str) -> str:
        # Write the text to a file
        with open(os.path.join(directory, fileName), 'w+', encoding="utf-8") as file:
            file.write(text)

        return file.name

    def close(self):
        print("Closing parallel contexts")
        self.clear_cache()

        if (self.gpu_parallel_context is not None):
            self.gpu_parallel_context.close()
        if (self.cpu_parallel_context is not None):
            self.cpu_parallel_context.close()
def create_ui(input_audio_max_duration, share=False, server_name: str = None, server_port: int = 7860, 
              default_model_name: str = "medium", default_vad: str = None, vad_parallel_devices: str = None, 
              vad_process_timeout: float = None, vad_cpu_cores: int = 1, auto_parallel: bool = False, 
              output_dir: str = None):
    ui = WhisperTranscriber(input_audio_max_duration, vad_process_timeout, vad_cpu_cores, DELETE_UPLOADED_FILES, output_dir)

    # Specify a list of devices to use for parallel processing
    ui.set_parallel_devices(vad_parallel_devices)
    ui.set_auto_parallel(auto_parallel)

    ui_description = "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs " 
    #ui_description += " audio and is also a multi-task model that can perform multilingual speech recognition "
    #ui_description += " as well as speech translation and language identification. "

    #ui_description += "\n\n\n\nFor longer audio files (>10 minutes) not in English, it is recommended that you select Silero VAD (Voice Activity Detector) in the VAD option."

    #if input_audio_max_duration > 0:
       # ui_description += "\n\n" + "Max audio file length: " + str(input_audio_max_duration) + " s"

    #ui_article = "Read the [documentation here](https://gitlab.com/aadnk/whisper-webui/-/blob/main/docs/options.md)"
    import requests
    results = []
    def getAudios(agent, dest,fromDate, toDate):
        url_out = 'https://api-smartflo.tatateleservices.com/v1/call/records?direction=outbound&limit=100'
        p = {
          "from_date":str(fromDate),
          "to_date":str(toDate),
          "agents":str(agent),
          "destination":str(dest)
        }
        resp = requests.get(url_out, params=p,
           headers={'Content-Type':'application/json',
               'Authorization': 'Bearer {}'.
               format('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjg5ODkyLCJpc3MiOiJodHRwczpcL1wvY2xvdWRwaG9uZS50YXRhdGVsZXNlcnZpY2VzLmNvbVwvdG9rZW5cL2dlbmVyYXRlIiwiaWF0IjoxNjcyMTM0MjYzLCJleHAiOjE5NzIxMzQyNjMsIm5iZiI6MTY3MjEzNDI2MywianRpIjoiN3hqR25ydGZyUWprMmZjdSJ9.-nno38JWqGMXu_djqYw2ExO_IhfACebjfMN-Tb1pgCQ')})
        data = resp.json()


        results = []
        # Now you can access Json
        for i in data['results']:
            client_number = str(i['client_number']) if i['client_number'] is not None else ''
            call_duration = str(i['call_duration']) if i['call_duration'] is not None else ''
            end_stamp = str(i['end_stamp']) if i['end_stamp'] is not None else ''
            agent_id=''
            if len(i["call_flow"])>1:
                agent_id = i["call_flow"][1]["id"]
            call_type='Outbound'
            recording_url = [client_number,call_duration,agent_id, call_type,end_stamp,i['recording_url']]
            results.append(recording_url)

        url_in = 'https://api-smartflo.tatateleservices.com/v1/call/records?direction=inbound&limit=100'
        p = {
          "from_date":str(fromDate),
          "to_date":str(toDate),
          "agents":str(agent),
          "destination":str(dest)
        }
        resp = requests.get(url_in, params=p,
           headers={'Content-Type':'application/json',
               'Authorization': 'Bearer {}'.
               format('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjg5ODkyLCJpc3MiOiJodHRwczpcL1wvY2xvdWRwaG9uZS50YXRhdGVsZXNlcnZpY2VzLmNvbVwvdG9rZW5cL2dlbmVyYXRlIiwiaWF0IjoxNjcyMTM0MjYzLCJleHAiOjE5NzIxMzQyNjMsIm5iZiI6MTY3MjEzNDI2MywianRpIjoiN3hqR25ydGZyUWprMmZjdSJ9.-nno38JWqGMXu_djqYw2ExO_IhfACebjfMN-Tb1pgCQ')})
        data = resp.json()


        # Now you can access Json
        for i in data['results']:
            client_number = str(i['client_number']) if i['client_number'] is not None else ''
            call_duration = str(i['call_duration']) if i['call_duration'] is not None else ''
            end_stamp = str(i['end_stamp']) if i['end_stamp'] is not None else ''
            agent_id=''
            if len(i["call_flow"])>1:
                agent_id = i["call_flow"][1]["id"]
            call_type = 'Inbound'
            recording_url = [client_number,call_duration,agent_id, call_type,end_stamp,i['recording_url']]
            results.append(recording_url)
        return results
    io1 = gr.Interface(
    fn=getAudios,
    inputs=[gr.Textbox(label="Agent Id"),gr.Textbox(label="Destination",placeholder="10 digit phone number"),
    gr.Textbox(label="From Date",placeholder="yyyy-mm-dd"), gr.Textbox(label="To Date", placeholder="yyyy-mm-dd")],
    outputs=[gr.Dataframe(
            headers=["Candidate Number", "Duration (in seconds)", "Agent Id", 'Call Type', "Call End Time", "Recording URL"],
            datatype=["str", "str","str","str", "str", "str"],
            label="Recordings",wrap=True
        )],
    #outputs=[gr.Radio(label="Results")],
    )

    
    simple_inputs = lambda : [
        gr.Dropdown(choices=["Siemens", "Sprinto","ABB", "UNext","Hetero and Hetero Biopharma","Hetero Formulation and R&D","Carelon Campus","Carelon","R1 RCM","Reach Mobile","Narayana Health","Narayana health 2",
                             "AllState","CITI","Wells Fargo","Hindalco","Vodafone"], label="Client"),
       # gr.Dropdown(choices=["Anushree Shetti", "Manshi Y","Taskeen Ahmed","Tabrez","Varsha Amarnath","Kanwagi Kaushik","Hemani Shah","Seema Singh","Chaya Ramesh",
        #                     "Kajal Khanna","Vandana Vijeshwar","Elizabeth Sam","Sharanya Selvam","Neha Prasad","Swati Shyam","Lakshmi Thanuja","Saniya Afreen","Smita Alex","Punit Chandok",
         #                    "Vanessa"], label="Counsellor"),

        gr.Dropdown(choices=["Exits", "CE", "NHE"], label="Process (*)"),
        gr.Dropdown(choices=["Riah", "Aliya","Bhavana","Charan Deep","Aparna Kathirvelu","Jetal Patel","Saqib Chisti","Mohammed Rehan","Milli Das","Furkan Khursheen","Anshumala Shahi","Preksha","Parvathy AN","Iman Sareen","Pooja","Kajal Devkar","Khushali Jain","Shaik Salma Banu","Ananya Sethi","Alexiss Steffi","Sree Priya","Anu Agustine","Sandhiya","Hameeda Khan","Hisba","Deepshikha","Veena","Anusha","Lakshmi M","Nafisha A","Pinki Bhakta","Priyadarshi K","Nikita Alex","Yashika Haswani","Leon Augustine","Krishnendu","Swaroopa Shivaprasad","Aparna","Ananaya","Khushi","Yawer","Anuradha","Sirisha","Malavika","Spurthi","Sonali","Japhia","Arwa Nadir","Ramya K","Deepsikha Banerjee", "Geetanjali Srivastava","Sweta Sridhar","Karuna Sruthi","Anoushka Chandrashekar Chandavarkar","Ranjitha","Muskan Sukhwani","Harshitha Prabhu","Supreetha S","Ananya Srinivas","Sadia Aijaz","Japhia","Arwa Nadir","Anoushka Chandrasekhar","Ranjitha","Muskan Sukhwani","Vinnie Thampan","Nida Parveen", "Betsy Abraham","Dimple Sangvi","Evangeline Marandee","Sweety Kumbhare","Leonardo Banerji","Anjali Sadana","Ayushi Nagotia","Prajwala","Milind Kumar","Dimple Sanghvi","Sonia Mohanta","Himsuta Sharma", "Paramita Deogharia","Neelam Shalin", "Divya Kancharana", "Anchal Srivastav","Soumya Kuntoji", "Taskeen A","Suchi Agarwal","Yasmin Yunus","Shreshtha Rana","Halima Sadia","Tanisha Priyadarshini","Sheetal Raveendran Alias","Vignesh Anudharaj","Vignesh Amudharaj","Erlene Elizabeth Scaria","Shilpa Rajeev","Sowmya G R","Bhaskar Jyoti Das","Riya Sharma","Sunnil Kumar","Zainab Jawadwala","Shweta Verma","Siddhi P", "Rashmi", "Khishali Jain", "Ashwini P","Vikashene","Mir Uzair","Aaquib Altaf","Aishwarya Tharun","Jyoti Karkal","Naomi Talari","Tanya Dingar","Tabrez Abbaz","Hemani Shah","Sweta N","Diti Bamboli",
                             "Sneha Lal","Farhan Ahmed","Fathima Jabeen","Taskeen A","Nida Naaz","Dilna Francis","Jattley","Hiten Ashar","Vinisha Ashwin","Aparna Sharma","Krishnendu Ashok","Ruth Sneha Inbasekeran","Tasneem Rangwala","Liwina Winson",'Catherine Kaping', 'Florence Jennifher ', 'Ashwini P', 'Charchika Singh', 'Aaprajita Kumari', 'Kavini M', 'Palak Maheshwari', 'Swati Mg', 'Syeda Ashraf', 'Vinutha Ks ', 'Afelia Datta', 'Bandana Tripathi', 'Shiva Sinha', 'Pooja Mishra', 'Jayashree Balachandran', 'Anushree Shetti ', 'Varsha Amarnath', 'Anjali Nair', 'Chaitra Shree', 'Kanwagi Kaushik', 'Shweta Tiwari', 'Thanusri S', 'Shraddha Waghmare', 'Jeena Rajan', 'Swapna Sharmili', 'Manshi Y', 'Samhitha Hn', 'Chaya Ramesh', 'Swati Jha', 'Ritika Verma', 'Sarika Arora', 'Seema Gupta', 'Kamaljeet Kaur', 'Preksha Jain', 'Anisha Regmi', 'Monika Srivastava', 'Neeriksha Mohan', 'Mahima Jha', 'Prakamya Suman', 'Sana Shaikh', 'Hemani Shah', 'Archana Jain', 'Sruthi Rajan', 'Archana Hiremath', 'Mayak Mehta', 'Ashish Rana', 'Anzal Farooq ', 'Rashu Singh ', 'Muskan Shrivastava', 'Lubna Sheikh', 'Rakshitha V', 'Sruthi Ts', 'Remeez Imtiyaz', 'Navneet Kour', 'Steffi P', 'Srusti N', 'Priyanka Sarkar', 'Gladys J', 'Swati S', 'Sharanya Selvam', 'Neha Prasad', 'Lakshmi Thanuja', 'Taniya Tehreen ', 'Elizabeth Sam', 'Indumathi Nargunan', 'Swathi Shyam', 'Divya Rajvaidya', 'Feba Abraham', 'Shreyasi Roy', 'Akanksha Srivastava', 'Preeti G', 'Khanna Kajal', 'Priyanka Kumar', 'Sneha Rh', 'Vidhi Thapar', 'Sama Naqvi', 'Saniya Afreen', 'Saima Elahi', 'Vanessa Clancy'], label="Counsellor (*)"),
        gr.Dropdown(choices=WHISPER_MODELS, value=default_model_name, label="Model"),
        gr.Dropdown(choices=sorted(LANGUAGES), label="Language", visible=False),
        gr.Text(label="URL (YouTube, etc.)"),
        gr.File(label="Upload Files", file_count="multiple"),
        gr.Audio(source="microphone", type="filepath", label="Microphone Input"),


        gr.Dropdown(choices=["transcribe", "translate"], label="Task",visible=False),
        gr.Dropdown(choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], value=default_vad, label="VAD",visible=False),
        gr.Number(label="VAD - Merge Window (s)", precision=0, value=5,visible=False),
        gr.Number(label="VAD - Max Merge Size (s)", precision=0, value=30,visible=False),
        gr.Number(label="VAD - Padding (s)", precision=None, value=1,visible=False),
        gr.Number(label="VAD - Prompt Window (s)", precision=None, value=3,visible=False)
    ]
    
    io2 = gr.Interface(fn=ui.transcribe_webui, description=ui_description, article='', inputs=[   
        
        gr.Dropdown(choices=["Siemens", "Sprinto","ABB", "UNext","Hetero and Hetero Biopharma","Hetero Formulation and R&D","Carelon Campus","Carelon","R1 RCM","Reach Mobile","Narayana Health","Narayana health 2",
                             "AllState","CITI","Wells Fargo","Hindalco","Vodafone"], label="Client"),
       # gr.Dropdown(choices=["Anushree Shetti", "Manshi Y","Taskeen Ahmed","Tabrez","Varsha Amarnath","Kanwagi Kaushik","Hemani Shah","Seema Singh","Chaya Ramesh",
        #                     "Kajal Khanna","Vandana Vijeshwar","Elizabeth Sam","Sharanya Selvam","Neha Prasad","Swati Shyam","Lakshmi Thanuja","Saniya Afreen","Smita Alex","Punit Chandok",
         #                    "Vanessa"], label="Counsellor"),

        gr.Dropdown(choices=["Exits", "CE", "NHE"], label="Process (*)"),
        gr.Dropdown(choices=["Riah", "Aliya","Japhia","Arwa Nadir","Anoushka Chandrasekhar","Ranjitha","Muskan Sukhwani","Vinnie Thampan","Jyoti Karkal","Naomi Talari","Tanya Dingar","Tabrez Abbaz","Hemani Shah","Sweta N","Diti Bamboli",
                             "Sneha Lal","Farhan Ahmed","Fathima Jabeen","Taskeen A","Nida Naaz","Dilna Francis","Jattley","Liwina Winson",'Catherine Kaping', 'Florence Jennifher ', 'Ashwini P', 'Charchika Singh', 'Aaprajita Kumari', 'Kavini M', 'Palak Maheshwari', 'Swati Mg', 'Syeda Ashraf', 'Vinutha Ks ', 'Afelia Datta', 'Bandana Tripathi', 'Shiva Sinha', 'Pooja Mishra', 'Jayashree Balachandran', 'Anushree Shetti ', 'Varsha Amarnath', 'Anjali Nair', 'Chaitra Shree', 'Kanwagi Kaushik', 'Shweta Tiwari', 'Thanusri S', 'Shraddha Waghmare', 'Jeena Rajan', 'Swapna Sharmili', 'Manshi Y', 'Samhitha Hn', 'Chaya Ramesh', 'Swati Jha', 'Ritika Verma', 'Sarika Arora', 'Seema Gupta', 'Kamaljeet Kaur', 'Preksha Jain', 'Anisha Regmi', 'Monika Srivastava', 'Neeriksha Mohan', 'Mahima Jha', 'Prakamya Suman', 'Sana Shaikh', 'Hemani Shah', 'Archana Jain', 'Sruthi Rajan', 'Archana Hiremath', 'Mayak Mehta', 'Ashish Rana', 'Anzal Farooq ', 'Rashu Singh ', 'Muskan Shrivastava', 'Lubna Sheikh', 'Rakshitha V', 'Sruthi Ts', 'Remeez Imtiyaz', 'Navneet Kour', 'Steffi P', 'Srusti N', 'Priyanka Sarkar', 'Gladys J', 'Swati S', 'Sharanya Selvam', 'Neha Prasad', 'Lakshmi Thanuja', 'Taniya Tehreen ', 'Elizabeth Sam', 'Indumathi Nargunan', 'Swathi Shyam', 'Divya Rajvaidya', 'Feba Abraham', 'Shreyasi Roy', 'Akanksha Srivastava', 'Preeti G', 'Khanna Kajal', 'Priyanka Kumar', 'Sneha Rh', 'Vidhi Thapar', 'Sama Naqvi', 'Saniya Afreen', 'Saima Elahi', 'Vanessa Clancy'], label="Counsellor (*)"),
        gr.Dropdown(choices=WHISPER_MODELS, value=default_model_name, label="Model"),
        gr.Dropdown(choices=sorted(LANGUAGES), label="Language"),
        gr.Text(label="URL (YouTube, etc.)"),
        gr.File(label="Upload Files", file_count="multiple"),
        gr.Audio(source="microphone", type="filepath", label="Microphone Input"),
        

        gr.Dropdown(choices=["transcribe", "translate"], label="Task",visible=False),
        gr.Dropdown(choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], value=default_vad, label="VAD",visible=False),
        gr.Number(label="VAD - Merge Window (s)", precision=0, value=5,visible=False),
        gr.Number(label="VAD - Max Merge Size (s)", precision=0, value=30,visible=False),
        gr.Number(label="VAD - Padding (s)", precision=None, value=1,visible=False),
        gr.Number(label="VAD - Prompt Window (s)", precision=None, value=3,visible=False)
    ], outputs=[
        gr.Textbox(label="Client, Counsellor, Process"),
        gr.File(label="Download"),
        gr.Text(label="Transcription"), 
        gr.Text(label="Segments")
    ])
    """
    io3 = gr.Interface(fn=ui.transcribe_webui_full, description=ui_description, article='', inputs=[
        *simple_inputs(),
        gr.Dropdown(choices=["prepend_first_segment", "prepend_all_segments"], value=app_config.vad_initial_prompt_mode, label="VAD - Initial Prompt Mode"),
        gr.TextArea(label="Initial Prompt"),
        gr.Number(label="Temperature", value=app_config.temperature),
        gr.Number(label="Best Of - Non-zero temperature", value=app_config.best_of, precision=0),
        gr.Number(label="Beam Size - Zero temperature", value=app_config.beam_size, precision=0),
        gr.Number(label="Patience - Zero temperature", value=app_config.patience),
        gr.Number(label="Length Penalty - Any temperature", value=app_config.length_penalty),
        gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value=app_config.suppress_tokens),
        gr.Checkbox(label="Condition on previous text", value=app_config.condition_on_previous_text),
        gr.Checkbox(label="FP16", value=app_config.fp16),
        gr.Number(label="Temperature increment on fallback", value=app_config.temperature_increment_on_fallback),
        gr.Number(label="Compression ratio threshold", value=app_config.compression_ratio_threshold),
        gr.Number(label="Logprob threshold", value=app_config.logprob_threshold),
        gr.Number(label="No speech threshold", value=app_config.no_speech_threshold)
    ], outputs=[
        gr.File(label="Download"),
        gr.Text(label="Transcription"),
        gr.Text(label="Segments")
    ])
    """
    io3 = gr.Interface(fn=ui.transcribe_webui_full, description=ui_description, article='', inputs=[
        *simple_inputs(),
        gr.TextArea(label="Initial Prompt", visible=False),
        gr.Number(label="Temperature", value=0, visible=False),
        gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
        gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
        gr.Number(label="Patience - Zero temperature", value=None,visible=False),
        gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
        gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
        gr.Checkbox(label="Condition on previous text", value=True,visible=False),
        gr.Checkbox(label="FP16", value=True,visible=False),
        gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
        gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
        gr.Number(label="Logprob threshold", value=-1.0,visible=False),
        gr.Number(label="No speech threshold", value=0.6,visible=False)
    ], outputs=[
        gr.Textbox(label="Client, Counsellor, Process"),
        #gr.File(label="Download"),
        gr.Text(label="Transcription"),
    ])

    io4 = gr.Interface(fn=ui.transcribe_webui_full_verbatim, description=ui_description, article='', inputs=[
        *simple_inputs(),
        gr.TextArea(label="Initial Prompt", visible=False),
        gr.Number(label="Temperature", value=0, visible=False),
        gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
        gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
        gr.Number(label="Patience - Zero temperature", value=None,visible=False),
        gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
        gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
        gr.Checkbox(label="Condition on previous text", value=True,visible=False),
        gr.Checkbox(label="FP16", value=True,visible=False),
        gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
        gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
        gr.Number(label="Logprob threshold", value=-1.0,visible=False),
        gr.Number(label="No speech threshold", value=0.6,visible=False)
    ], outputs=[
        gr.Textbox(label="Client, Counsellor, Process"),
        #gr.File(label="Download"),
        gr.Text(label="Transcription"),
        gr.Text(label="Proposed Verbatim - Please review & update as required")
        #gr.Text(label="Segments")
    ])

    io5 = gr.Interface(fn=ui.transcribe_webui_full_verbatim_qa, description=ui_description, article='', inputs=[
        *simple_inputs(),
        gr.TextArea(label="REASONS FOR LEAVING AND REACTION TO REASON FOR LEAVING",value="1.What triggered your decision to leave? \n2.Who spoke to you after you resigned? \n3.In your opinion did they make a genuine effort to retain you? \n4.What could the organization have done to retain you? "),
        gr.TextArea(label="RECRUITMENT FEEDBACK (0-12 MONTHS TENURE) (Rate on a scale of 1-10)",value="1.Role clarity- Were you given clarity about your role before you joined? If less than 7, why? \n2.On-boarding process- Did your on-boarding process go on smoothly and on time? If less than 7, why? \n3.Time taken for the recruitment process- Was the overall interview organized and quick? If less than 7, why? If less than 7, why? \n4.Hand-holding- Were you given the required support, guidance and knowledge transfer for your new role? If less than 7 ,why?\n5.JD and current role match- Does your current role match the JD that was provided to you at the time of joining? If less than 7, why? \n6.What was done well during the overall recruitment process? \n7.What could have been done better during the overall recruitment process? "),
        gr.TextArea(label="SURVEY QUESTIONS (Rate on a scale of 1-10)",value="1.What is your supervisor's name? \n2.What is your supervisor's designation? \n3.Subject knowledge - Do you believe your manager was competent to be able to deal with the issues you and your team mates have during your workday? If less than 7, why? \n4.Team management- How effectively did your manager work with the resources provided to him/her to get the task at hand completed? If less than 7, why? \n5.Being unbiased- Did your Manager give fair opportunities to everyone in the team? If less than 7, why? \n6.Offering growth opportunities- Did you Manager encourage growth and allow you to explore new tasks? \n7.Providing feedback - Was the feedback provided by the manager to you fair and clear which outlined a clear way for you to grow as an individual? If less than 7, why? \n8.Given a chance would you like to work with your current manager in the future? \n9.Senior leadership - opportunity to interact and visibility . If less than 7, why? \n10.Role satisfaction - having a sense of direction with what you do and having the required tools/ resources to do this. If less than 7, why? \n11.Rewards and Recognition- being rewarded and recognized adequately for hard work and effort.If less than 7, why? \n12.Performance Management System(includes Growth Opportunities)- level of transparency in the appraisal and promotion process. \n13.Work-Life Balance- being able maintain a healthy balance between work life and personal life?If less than 7, why?"),
        gr.TextArea(label="APPRECIATIVE ENQUIRY",value="1.How likely are you to recommend the organization to you friends and family to work in on a scale of 0-10 (0 being the lowest)? \n2.eNPS Comments \n3.What is the one thing you liked the most about the organization? \n4.Would you be willing to re-join? \n5.Where are you working now? \n6.Did you join the new company in the same industry as you were working for in the previous company? \n7.What is your current designation? \n8.How much of a hike have you received? "),
        gr.TextArea(label="Initial Prompt", visible=False),
        gr.Number(label="Temperature", value=0, visible=False),
        gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
        gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
        gr.Number(label="Patience - Zero temperature", value=None,visible=False),
        gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
        gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
        gr.Checkbox(label="Condition on previous text", value=True,visible=False),
        gr.Checkbox(label="FP16", value=True,visible=False),
        gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
        gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
        gr.Number(label="Logprob threshold", value=-1.0,visible=False),
        gr.Number(label="No speech threshold", value=0.6,visible=False)
    ], outputs=[
        gr.Textbox(label="Client, Counsellor, Process"),
        gr.Text(label="Transcription"),
        gr.Text(label="Answers For Questionnaire 3 - Set 1"),
        gr.Text(label="Answers For Questionnaire 3 - Set 2"),
        gr.Text(label="Answers For Questionnaire 3 - Set 3"),
        gr.Text(label="Answers For Questionnaire 3 - Set 4"),
    ])

    
    #demo.launch(share=share, server_name=server_name, server_port=server_port)
    gr.TabbedInterface(
    [io1, io3,io4, io5], ["Pragyaa Select", "Pragyaa Transcribe", "Pragyaa Transcribe With Verbatim","Pragyaa Transcribe With Questionnaire"]
).queue(concurrency_count=5).launch(share=share, server_name=server_name, server_port=server_port)

    
    # Clean up
    ui.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("--input_audio_max_duration", type=int, default=DEFAULT_INPUT_AUDIO_MAX_DURATION, help="Maximum audio file length in seconds, or -1 for no limit.")
    parser.add_argument("--share", type=bool, default=False, help="True to share the app on HuggingFace.")
    parser.add_argument("--server_name", type=str, default=None, help="The host or IP to bind to. If None, bind to localhost.")
    parser.add_argument("--server_port", type=int, default=7860, help="The port to bind to.")
    parser.add_argument("--default_model_name", type=str, choices=WHISPER_MODELS, default="medium", help="The default model name.")
    parser.add_argument("--default_vad", type=str, default="silero-vad", help="The default VAD.")
    parser.add_argument("--vad_parallel_devices", type=str, default="", help="A commma delimited list of CUDA devices to use for parallel processing. If None, disable parallel processing.")
    parser.add_argument("--vad_cpu_cores", type=int, default=1, help="The number of CPU cores to use for VAD pre-processing.")
    parser.add_argument("--vad_process_timeout", type=float, default="1800", help="The number of seconds before inactivate processes are terminated. Use 0 to close processes immediately, or None for no timeout.")
    parser.add_argument("--auto_parallel", type=bool, default=False, help="True to use all available GPUs and CPU cores for processing. Use vad_cpu_cores/vad_parallel_devices to specify the number of CPU cores/GPUs to use.")
    parser.add_argument("--output_dir", "-o", type=str, default=None, help="directory to save the outputs")

    args = parser.parse_args().__dict__
    create_ui(**args)