pragyaa commited on
Commit
ee10821
1 Parent(s): e81954b

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +1347 -0
  2. requirements.txt +260 -0
app.py ADDED
@@ -0,0 +1,1347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import math
3
+ from typing import Iterator
4
+ import argparse
5
+ import boto3
6
+ import uuid
7
+
8
+ from io import StringIO
9
+ import os
10
+ import pathlib
11
+ import tempfile
12
+ import zipfile
13
+ import numpy as np
14
+ #import sqlite3
15
+ from src.utils import duration_detector
16
+ import datetime
17
+ import shutil
18
+ import json
19
+
20
+ import torch
21
+ from src.modelCache import ModelCache
22
+ from src.source import get_audio_source_collection
23
+ from src.vadParallel import ParallelContext, ParallelTranscription
24
+
25
+ # External programs
26
+ import ffmpeg
27
+ from aws_requests_auth.aws_auth import AWSRequestsAuth
28
+ from elasticsearch import Elasticsearch, RequestsHttpConnection
29
+ from elasticsearch import helpers
30
+ import certifi
31
+
32
+ #logging
33
+ from pytz import timezone
34
+ import logging
35
+ import sys
36
+
37
+ logging.Formatter.converter = lambda *args: datetime.datetime.now(tz=timezone('Asia/Kolkata')).timetuple()
38
+ logging.basicConfig(
39
+ format="%(asctime)s %(levelname)s: %(message)s",
40
+ level=logging.INFO,
41
+ datefmt="%Y-%m-%d %H:%M:%S",
42
+ )
43
+
44
+ console = logging.StreamHandler(sys.stdout)
45
+ log = logging.getLogger(__name__)
46
+
47
+ # UI
48
+ import gradio as gr
49
+ import traceback
50
+ from src.download import ExceededMaximumDuration, download_url
51
+ from src.utils import slugify, write_srt, write_vtt
52
+ from src.vad import AbstractTranscription, NonSpeechStrategy, PeriodicTranscriptionConfig, TranscriptionConfig, VadPeriodicTranscription, VadSileroTranscription
53
+ from src.whisperContainer import WhisperContainer
54
+ session = boto3.Session(
55
+ aws_access_key_id='AKIAZB4KTGHMCFPIP6EV',
56
+ aws_secret_access_key='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',
57
+ )
58
+ s3 = session.resource('s3')
59
+ #client = boto3.client('dynamodb')
60
+
61
+ import requests
62
+ import os
63
+
64
+ #openai
65
+ import openai
66
+ from openai import AzureOpenAI
67
+
68
+ #OPENAI_API_KEY = "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"
69
+ OPENAI_API_KEY = "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"
70
+
71
+ token = f"Bearer {OPENAI_API_KEY}"
72
+
73
+ url = "https://api.openai.com/v1/audio/transcriptions"
74
+ model_name ="whisper-1"
75
+
76
+ headers ={
77
+ "Authorization": token
78
+ #"Content-Type": "multipart/form-data"
79
+ }
80
+
81
+ #azure whisper
82
+ """
83
+ openai.api_key = '142805a982184d289203b387062bfb29'
84
+ openai.api_base = 'https://pragyaawhisper3.openai.azure.com' # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
85
+ openai.api_type = "azure"
86
+ openai.api_version = "2023-09-01-preview"
87
+ model_name = "whisper"
88
+ deployment_id = "whisper3" #This will correspond to the custom name you chose for your deployment when you deployed a model."
89
+ audio_language="en"
90
+ """
91
+ AZURE_OPENAI_ENDPOINT = 'https://pragyaawhisper3.openai.azure.com/'
92
+ AZURE_OPENAI_KEY = '142805a982184d289203b387062bfb29'
93
+ MODEL_NAME = 'whisper3'
94
+ HEADERS = { "api-key" : AZURE_OPENAI_KEY }
95
+
96
+ # get the Elasticsearch index name from the environment variables
97
+ acengage_index = 'acengage-sessions'
98
+ esendpoint = 'search-mediassist-indexer-l5jj553cigi5qbir5f4rdzuhoe.us-east-1.es.amazonaws.com'
99
+ #esendpoint = 'search-prime-indexer-jif4ysiafk74aep2w6elx4pn5q.us-east-1.es.amazonaws.com'
100
+ region = 'us-east-1'
101
+
102
+ # Create the auth token for the sigv4 signature
103
+ """
104
+ session = boto3.session.Session()
105
+ credentials = session.get_credentials().get_frozen_credentials()
106
+ awsauth = AWSRequestsAuth(
107
+ aws_access_key=credentials.access_key,
108
+ aws_secret_access_key=credentials.secret_key,
109
+ aws_token=credentials.token,
110
+ aws_host=esendpoint,
111
+ aws_region=region,
112
+ aws_service='es'
113
+ )
114
+ """
115
+ # Connect to the elasticsearch cluster using aws authentication. The lambda function
116
+ # must have access in an IAM policy to the ES cluster.
117
+ es = Elasticsearch(
118
+ hosts=[{'host': esendpoint, 'port': 443}],
119
+ http_auth=('kibanauser','Threeguys01!'),
120
+ use_ssl=True,
121
+ verify_certs=True,
122
+ ca_certs=certifi.where(),
123
+ timeout=120,
124
+ connection_class=RequestsHttpConnection
125
+ )
126
+
127
+ # Limitations (set to -1 to disable)
128
+ DEFAULT_INPUT_AUDIO_MAX_DURATION = 600 # seconds
129
+
130
+ # Whether or not to automatically delete all uploaded files, to save disk space
131
+ DELETE_UPLOADED_FILES = True
132
+
133
+ # Gradio seems to truncate files without keeping the extension, so we need to truncate the file prefix ourself
134
+ MAX_FILE_PREFIX_LENGTH = 17
135
+
136
+ # Limit auto_parallel to a certain number of CPUs (specify vad_cpu_cores to get a higher number)
137
+ MAX_AUTO_CPU_CORES = 8
138
+
139
+ LANGUAGES = [
140
+ "English", "Chinese", "German", "Spanish", "Russian", "Korean",
141
+ "French", "Japanese", "Portuguese", "Turkish", "Polish", "Catalan",
142
+ "Dutch", "Arabic", "Swedish", "Italian", "Indonesian", "Hindi",
143
+ "Finnish", "Vietnamese", "Hebrew", "Ukrainian", "Greek", "Malay",
144
+ "Czech", "Romanian", "Danish", "Hungarian", "Tamil", "Norwegian",
145
+ "Thai", "Urdu", "Croatian", "Bulgarian", "Lithuanian", "Latin",
146
+ "Maori", "Malayalam", "Welsh", "Slovak", "Telugu", "Persian",
147
+ "Latvian", "Bengali", "Serbian", "Azerbaijani", "Slovenian",
148
+ "Kannada", "Estonian", "Macedonian", "Breton", "Basque", "Icelandic",
149
+ "Armenian", "Nepali", "Mongolian", "Bosnian", "Kazakh", "Albanian",
150
+ "Swahili", "Galician", "Marathi", "Punjabi", "Sinhala", "Khmer",
151
+ "Shona", "Yoruba", "Somali", "Afrikaans", "Occitan", "Georgian",
152
+ "Belarusian", "Tajik", "Sindhi", "Gujarati", "Amharic", "Yiddish",
153
+ "Lao", "Uzbek", "Faroese", "Haitian Creole", "Pashto", "Turkmen",
154
+ "Nynorsk", "Maltese", "Sanskrit", "Luxembourgish", "Myanmar", "Tibetan",
155
+ "Tagalog", "Malagasy", "Assamese", "Tatar", "Hawaiian", "Lingala",
156
+ "Hausa", "Bashkir", "Javanese", "Sundanese"
157
+ ]
158
+
159
+ WHISPER_MODELS = ["tiny", "base", "small", "medium", "large", "large-v1", "large-v2"]
160
+
161
+ class WhisperTranscriber:
162
+ def __init__(self, input_audio_max_duration: float = DEFAULT_INPUT_AUDIO_MAX_DURATION, vad_process_timeout: float = None,
163
+ vad_cpu_cores: int = 1, delete_uploaded_files: bool = DELETE_UPLOADED_FILES, output_dir: str = None):
164
+ self.model_cache = ModelCache()
165
+ self.parallel_device_list = None
166
+ self.gpu_parallel_context = None
167
+ self.cpu_parallel_context = None
168
+ self.vad_process_timeout = vad_process_timeout
169
+ self.vad_cpu_cores = vad_cpu_cores
170
+
171
+ self.vad_model = None
172
+ self.inputAudioMaxDuration = input_audio_max_duration
173
+ self.deleteUploadedFiles = delete_uploaded_files
174
+ self.output_dir = output_dir
175
+
176
+ def set_parallel_devices(self, vad_parallel_devices: str):
177
+ self.parallel_device_list = [ device.strip() for device in vad_parallel_devices.split(",") ] if vad_parallel_devices else None
178
+
179
+ def set_auto_parallel(self, auto_parallel: bool):
180
+ if auto_parallel:
181
+ if torch.cuda.is_available():
182
+ self.parallel_device_list = [ str(gpu_id) for gpu_id in range(torch.cuda.device_count())]
183
+
184
+ self.vad_cpu_cores = min(os.cpu_count(), MAX_AUTO_CPU_CORES)
185
+ print("[Auto parallel] Using GPU devices " + str(self.parallel_device_list) + " and " + str(self.vad_cpu_cores) + " CPU cores for VAD/transcription.")
186
+
187
+ # Entry function for the simple tab
188
+ def transcribe_webui_simple(self, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow):
189
+ return self.transcribe_webui(modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
190
+
191
+ # Entry function for the full tab
192
+ def transcribe_webui_full_verbatim(self, client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
193
+ initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str,
194
+ condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
195
+ compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):
196
+
197
+ # Handle temperature_increment_on_fallback
198
+ if temperature_increment_on_fallback is not None:
199
+ temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
200
+ else:
201
+ temperature = [temperature]
202
+
203
+ return self.transcribe_webui_verbatim(client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
204
+ initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
205
+ condition_on_previous_text=condition_on_previous_text, fp16=fp16,
206
+ compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
207
+ # Entry function for the full tab
208
+ def transcribe_webui_full_verbatim_qa(self, client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
209
+ 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,
210
+ condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
211
+ compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):
212
+
213
+ # Handle temperature_increment_on_fallback
214
+ if temperature_increment_on_fallback is not None:
215
+ temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
216
+ else:
217
+ temperature = [temperature]
218
+
219
+ return self.transcribe_webui_verbatim_qa(client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
220
+ initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
221
+ condition_on_previous_text=condition_on_previous_text, fp16=fp16,
222
+ compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
223
+
224
+ def transcribe_webui_full(self, client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
225
+ initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str,
226
+ condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
227
+ compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):
228
+
229
+ # Handle temperature_increment_on_fallback
230
+ if temperature_increment_on_fallback is not None:
231
+ temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
232
+ else:
233
+ temperature = [temperature]
234
+
235
+ return self.transcribe_webui(client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
236
+ initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
237
+ condition_on_previous_text=condition_on_previous_text, fp16=fp16,
238
+ compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
239
+ def transcribe_webui(self,client, process,counsellor, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
240
+ validfields = True
241
+ fileId = str(uuid.uuid4())
242
+ try:
243
+ sources = self.__get_source(urlData, multipleFiles, microphoneData)
244
+ if languageName is None:
245
+ languageName = 'english'
246
+ #print("Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process)
247
+ log.info(languageName)
248
+ if counsellor is None or counsellor == '' or process is None or process == '':
249
+ print (" Invalid fields")
250
+ validfields = False
251
+ 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."
252
+ client = 'Other' if client is None or client== '' else client
253
+ #counsellor = 'Select a counsellor from drodown' if counsellor is None or counsellor == ''else counsellor
254
+ #process = 'Select a process from dropdown' if process is None or process == '' else process
255
+
256
+ client_counsellor = "Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process
257
+ try:
258
+ selectedLanguage = languageName.lower() if len(languageName) > 0 else None
259
+ selectedModel = modelName if modelName is not None else "base"
260
+
261
+ model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)
262
+
263
+ # Result
264
+ download = []
265
+ zip_file_lookup = {}
266
+ text = ""
267
+ vtt = ""
268
+
269
+ # Write result
270
+ downloadDirectory = tempfile.mkdtemp()
271
+ source_index = 0
272
+
273
+ outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory
274
+
275
+ # Execute whisper
276
+ for source in sources:
277
+ source_prefix = ""
278
+
279
+ if (len(sources) > 1):
280
+ # Prefix (minimum 2 digits)
281
+ source_index += 1
282
+ source_prefix = str(source_index).zfill(2) + "_"
283
+ #log.info("Transcribing ", fileId+'-'+source.source_path)
284
+ #raise Exception("Ex")
285
+ hours, mins, secs = duration_detector(source.source_path)
286
+ #Log duration in DB before Transcibe line
287
+
288
+ # Transcribe
289
+ """
290
+ result = self.transcribe_file(model, source.source_path, 'english', task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
291
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
292
+
293
+ source_download, source_text, source_vtt = self.write_result(result, filePrefix, outputDirectory)
294
+
295
+ if len(sources) > 1:
296
+ # Add new line separators
297
+ if (len(source_text) > 0):
298
+ source_text += os.linesep + os.linesep
299
+ if (len(source_vtt) > 0):
300
+ source_vtt += os.linesep + os.linesep
301
+
302
+ # Append file name to source text too
303
+ source_text = source.get_full_name() + ":" + os.linesep + source_text
304
+ source_vtt = source.get_full_name() + ":" + os.linesep + source_vtt
305
+
306
+ # Add to result
307
+ download.extend(source_download)
308
+ text += source_text
309
+ vtt += source_vtt
310
+
311
+ if (len(sources) > 1):
312
+ # Zip files support at least 260 characters, but we'll play it safe and use 200
313
+ zipFilePrefix = slugify(source_prefix + source.get_short_name(max_length=200), allow_unicode=True)
314
+
315
+ # File names in ZIP file can be longer
316
+ for source_download_file in source_download:
317
+ # Get file postfix (after last -)
318
+ filePostfix = os.path.basename(source_download_file).split("-")[-1]
319
+ zip_file_name = zipFilePrefix + "-" + filePostfix
320
+ zip_file_lookup[source_download_file] = zip_file_name
321
+ log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
322
+ """
323
+ #openai whisper
324
+
325
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
326
+ response = None
327
+ try:
328
+ with open(source.source_path,"rb") as file:
329
+ file_content = file.read()
330
+
331
+ payload = {
332
+ "name": os.path.basename(source.source_path),
333
+ # "response_format": "json",
334
+ "prompt": "transcribe this Chapter",
335
+ "language": 'en',
336
+ "model": model_name
337
+ }
338
+ print("payload", payload)
339
+ files = {
340
+ "file": (os.path.basename(source.source_path), file_content, "audio/mp3")
341
+ }
342
+
343
+ response = requests.post(url, headers=headers, data=payload, files=files)
344
+ log.info(response.json())
345
+ except Exception:
346
+ log.info(response)
347
+ log.info("Error occurred while reading openai response")
348
+ print(traceback.format_exc())
349
+ return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
350
+
351
+ """
352
+ #azure whisper
353
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
354
+ response = None
355
+ try:
356
+ with open(source.source_path,"rb") as file:
357
+ response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
358
+ headers=HEADERS,
359
+ files={'file': file})
360
+ log.info(response.json())
361
+ except Exception:
362
+ log.info(response)
363
+ log.info("Error occurred while reading openai response")
364
+ print(traceback.format_exc())
365
+ return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
366
+ """
367
+ text = '',
368
+ if "text" in response.json():
369
+ text = response.json()["text"]
370
+ output_files = []
371
+ output_files.append(self.__create_file(text, outputDirectory,fileId + "-transcript.txt"));
372
+
373
+
374
+ bucket = 'acengage-bucket-v09kjo18oktg'
375
+ try:
376
+ for f in output_files:
377
+ print('source_text..', os.path.abspath(f))
378
+ s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
379
+ except:
380
+ print("Error while writing to s3, proceed")
381
+
382
+ else:
383
+ text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
384
+
385
+ return client_counsellor,text
386
+
387
+ finally:
388
+ # Cleanup source
389
+ if self.deleteUploadedFiles and validfields:
390
+ for source in sources:
391
+ print("Deleting source file " + source.source_path)
392
+
393
+ try:
394
+ bucket = 'acengage-bucket-v09kjo18oktg'
395
+ key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
396
+ s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
397
+ file_url = "https://"+bucket+".s3.amazonaws.com/"+key
398
+ #Log duration in DB before Transcibe line
399
+ try:
400
+ doc = {
401
+ 'client': client,
402
+ 'counsellor': counsellor,
403
+ 'process': process,
404
+ 'language':languageName,
405
+ 'file': os.path.basename(source.source_path),
406
+ 'hours': hours,
407
+ 'mins': mins,
408
+ 'secs': secs,
409
+ 'request_time': datetime.datetime.now(),
410
+ 'audio_url':file_url
411
+ }
412
+ res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
413
+ #logger.info(json.dumps(res, indent=4))
414
+ data_string = json.dumps(doc, indent=2, default=str)
415
+ key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
416
+ s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
417
+ except Exception:
418
+ print ("Error occurred while inserting duration data")
419
+ print(traceback.format_exc())
420
+ os.remove(source.source_path)
421
+ except Exception as e:
422
+ # Ignore error - it's just a cleanup
423
+ print("Error deleting source file " + source.source_path + ": " + str(e))
424
+
425
+ except ExceededMaximumDuration as e:
426
+ return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s")
427
+ except Exception as ex:
428
+ print(traceback.format_exc())
429
+ #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."
430
+ return client_counsellor,"There was an error while processing your input. Please retry your input."
431
+
432
+ def transcribe_webui_verbatim(self,client, process,counsellor, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
433
+ validfields = True
434
+ fileId = str(uuid.uuid4())
435
+ try:
436
+ sources = self.__get_source(urlData, multipleFiles, microphoneData)
437
+ if languageName is None:
438
+ languageName = 'english'
439
+ #print("Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process)
440
+ #log.info("Language Chosen: "+ languageName)
441
+ if counsellor is None or counsellor == '' or process is None or process == '':
442
+ print (" Invalid fields")
443
+ validfields = False
444
+ 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."
445
+ client = 'Other' if client is None or client== '' else client
446
+ #counsellor = 'Select a counsellor from drodown' if counsellor is None or counsellor == ''else counsellor
447
+ #process = 'Select a process from dropdown' if process is None or process == '' else process
448
+
449
+ client_counsellor = "Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process
450
+ try:
451
+ selectedLanguage = languageName.lower() if len(languageName) > 0 else None
452
+ selectedModel = modelName if modelName is not None else "base"
453
+
454
+ model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)
455
+
456
+ # Result
457
+ download = []
458
+ zip_file_lookup = {}
459
+ text = ""
460
+ vtt = ""
461
+
462
+ # Write result
463
+ downloadDirectory = tempfile.mkdtemp()
464
+ source_index = 0
465
+
466
+ outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory
467
+
468
+ # Execute whisper
469
+ for source in sources:
470
+ source_prefix = ""
471
+
472
+ if (len(sources) > 1):
473
+ # Prefix (minimum 2 digits)
474
+ source_index += 1
475
+ source_prefix = str(source_index).zfill(2) + "_"
476
+ #log.info("Transcribing ", fileId+'-'+source.source_path)
477
+ #raise Exception("Ex")
478
+ hours, mins, secs = duration_detector(source.source_path)
479
+ #Log duration in DB before Transcibe line
480
+
481
+ # Transcribe
482
+ """
483
+ result = self.transcribe_file(model, source.source_path, 'english', task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
484
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
485
+
486
+ source_download, source_text, source_vtt = self.write_result(result, filePrefix, outputDirectory)
487
+
488
+ if len(sources) > 1:
489
+ # Add new line separators
490
+ if (len(source_text) > 0):
491
+ source_text += os.linesep + os.linesep
492
+ if (len(source_vtt) > 0):
493
+ source_vtt += os.linesep + os.linesep
494
+
495
+ # Append file name to source text too
496
+ source_text = source.get_full_name() + ":" + os.linesep + source_text
497
+ source_vtt = source.get_full_name() + ":" + os.linesep + source_vtt
498
+
499
+ # Add to result
500
+ download.extend(source_download)
501
+ text += source_text
502
+ vtt += source_vtt
503
+
504
+ if (len(sources) > 1):
505
+ # Zip files support at least 260 characters, but we'll play it safe and use 200
506
+ zipFilePrefix = slugify(source_prefix + source.get_short_name(max_length=200), allow_unicode=True)
507
+
508
+ # File names in ZIP file can be longer
509
+ for source_download_file in source_download:
510
+ # Get file postfix (after last -)
511
+ filePostfix = os.path.basename(source_download_file).split("-")[-1]
512
+ zip_file_name = zipFilePrefix + "-" + filePostfix
513
+ zip_file_lookup[source_download_file] = zip_file_name
514
+ log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
515
+ """
516
+ #openai whisper
517
+
518
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
519
+ response = None
520
+ try:
521
+ with open(source.source_path,"rb") as file:
522
+ file_content = file.read()
523
+
524
+ payload = {
525
+ "name": os.path.basename(source.source_path),
526
+ # "response_format": "json",
527
+ "prompt": "transcribe this Chapter",
528
+ "language": 'en',
529
+ "model": model_name
530
+ }
531
+ print("payload", payload)
532
+ files = {
533
+ "file": (os.path.basename(source.source_path), file_content, "audio/mp3")
534
+ }
535
+
536
+ response = requests.post(url, headers=headers, data=payload, files=files)
537
+ log.info(response.json())
538
+ except Exception:
539
+ log.info(response)
540
+ log.info("Error occurred while reading openai response")
541
+ print(traceback.format_exc())
542
+ return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
543
+
544
+ """
545
+ #azure whisper
546
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
547
+ response = None
548
+ try:
549
+ with open(source.source_path,"rb") as file:
550
+ response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
551
+ headers=HEADERS,
552
+ files={'file': file})
553
+ log.info(response.json())
554
+ except Exception:
555
+ log.info(response)
556
+ log.info("Error occurred while reading openai response")
557
+ print(traceback.format_exc())
558
+ return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
559
+ """
560
+ text = ''
561
+ verbatimAzure = ''
562
+ if "text" in response.json():
563
+ text = response.json()["text"]
564
+ output_files = []
565
+ output_files.append(self.__create_file(text, outputDirectory, filePrefix + "-transcript.txt"));
566
+
567
+ #openai.api_type = "azure"
568
+ #openai.api_base = "https://pragyaaai.openai.azure.com/"
569
+ #openai.api_version = "2023-03-15-preview"
570
+ #openai.api_key = "9ba4e0dcfbf841fbb946c55c52caae1b"
571
+
572
+ #openai.api_key = OPENAI_API_KEY
573
+ api_base = 'https://pragyaagpt4.openai.azure.com/'
574
+ api_key="9fb5af1332a648b1bba4198731e389bd"
575
+ deployment_name = 'pragyaagpt4turbo'
576
+ api_version = '2023-12-01-preview' # this might change in the future
577
+
578
+ azureClient = AzureOpenAI(
579
+ api_key=api_key,
580
+ api_version=api_version,
581
+ base_url=f"{api_base}openai/deployments/{deployment_name}/",
582
+ )
583
+ 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."
584
+
585
+ if process=='CE':
586
+ 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."
587
+
588
+ try:
589
+ """
590
+ result = openai.ChatCompletion.create(
591
+ # engine="gpt35turbo",
592
+ model="gpt-4-1106-preview",
593
+ messages=[{"role":"system","content":prompt},
594
+ {"role": "user","content":text}],
595
+ temperature=0.7,
596
+ max_tokens=800,
597
+ top_p=0.95,
598
+ frequency_penalty=0,
599
+ presence_penalty=0,
600
+ stop=None)
601
+ """
602
+ result = azureClient.chat.completions.create(
603
+ model=deployment_name,
604
+ messages=[{"role":"system","content":prompt},
605
+ {"role": "user","content":text}],
606
+ temperature=0.7,
607
+ max_tokens=2000,
608
+ top_p=0.95,
609
+ frequency_penalty=0,
610
+ presence_penalty=0,
611
+ stop=None
612
+ )
613
+ print("verbatimAzure", result)
614
+ for choice in result.choices:
615
+ verbatimAzure += choice.message.content
616
+ except:
617
+ print("Error while generating verbatim")
618
+ traceback.print_exc()
619
+ verbatimAzure = "Some problem encountered while generating verbatim. The length of transcript could be big or it is taking longer time to process"
620
+
621
+ output_files = []
622
+ output_files.append(self.__create_file(text, outputDirectory, fileId + "-transcript.txt"));
623
+ output_files.append(self.__create_file(verbatimAzure, outputDirectory, fileId + "-verbatim.txt"));
624
+
625
+ bucket = 'acengage-bucket-v09kjo18oktg'
626
+ try:
627
+ for f in output_files:
628
+ print('source_text..', os.path.abspath(f))
629
+ s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
630
+ except:
631
+ print("Error while writing to s3, proceed")
632
+
633
+ else:
634
+ text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
635
+
636
+ return client_counsellor,text,verbatimAzure
637
+
638
+ finally:
639
+ # Cleanup source
640
+ if self.deleteUploadedFiles and validfields:
641
+ for source in sources:
642
+ print("Deleting source file " + source.source_path)
643
+
644
+ try:
645
+ bucket = 'acengage-bucket-v09kjo18oktg'
646
+ key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
647
+ s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
648
+ file_url = "https://"+bucket+".s3.amazonaws.com/"+key
649
+ #Log duration in DB before Transcibe line
650
+ try:
651
+ doc = {
652
+ 'client': client,
653
+ 'counsellor': counsellor,
654
+ 'process': process,
655
+ 'language':languageName,
656
+ 'verbatim':'yes',
657
+ 'file': os.path.basename(source.source_path),
658
+ 'hours': hours,
659
+ 'mins': mins,
660
+ 'secs': secs,
661
+ 'request_time': datetime.datetime.now(),
662
+ 'audio_url':file_url
663
+ }
664
+ res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
665
+ #logger.info(json.dumps(res, indent=4))
666
+ data_string = json.dumps(doc, indent=2, default=str)
667
+ key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
668
+ s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
669
+ except Exception:
670
+ print ("Error occurred while inserting duration data")
671
+ print(traceback.format_exc())
672
+ os.remove(source.source_path)
673
+ except Exception as e:
674
+ # Ignore error - it's just a cleanup
675
+ print("Error deleting source file " + source.source_path + ": " + str(e))
676
+
677
+ except ExceededMaximumDuration as e:
678
+ return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s"), "[ERROR]"
679
+ except Exception as ex:
680
+ print(traceback.format_exc())
681
+ #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."
682
+
683
+ def transcribe_webui_verbatim_qa(self,client, process,counsellor, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
684
+ validfields = True
685
+ fileId = str(uuid.uuid4())
686
+ try:
687
+ sources = self.__get_source(urlData, multipleFiles, microphoneData)
688
+ if languageName is None:
689
+ languageName = 'english'
690
+ if counsellor is None or counsellor == '' or process is None or process == '':
691
+ print (" Invalid fields")
692
+ validfields = False
693
+ 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."
694
+ client = 'Other' if client is None or client== '' else client
695
+
696
+ client_counsellor = "Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process
697
+ try:
698
+ selectedLanguage = languageName.lower() if len(languageName) > 0 else None
699
+ selectedModel = modelName if modelName is not None else "base"
700
+
701
+ model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)
702
+
703
+ # Result
704
+ download = []
705
+ zip_file_lookup = {}
706
+ text = ""
707
+ vtt = ""
708
+
709
+ # Write result
710
+ downloadDirectory = tempfile.mkdtemp()
711
+ source_index = 0
712
+
713
+ outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory
714
+
715
+ # Execute whisper
716
+ for source in sources:
717
+ source_prefix = ""
718
+
719
+ if (len(sources) > 1):
720
+ # Prefix (minimum 2 digits)
721
+ source_index += 1
722
+ source_prefix = str(source_index).zfill(2) + "_"
723
+ #log.info("Transcribing ", fileId+'-'+source.source_path)
724
+ #raise Exception("Ex")
725
+ hours, mins, secs = duration_detector(source.source_path)
726
+ #Log duration in DB before Transcibe line
727
+
728
+ # Transcribe
729
+ log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
730
+ # result = self.transcribe_file(model, source.source_path, selectedLanguage, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
731
+ #openai whisper
732
+
733
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
734
+ response = None
735
+ try:
736
+ with open(source.source_path,"rb") as file:
737
+ file_content = file.read()
738
+
739
+ payload = {
740
+ "name": os.path.basename(source.source_path),
741
+ # "response_format": "json",
742
+ "prompt": "transcribe this Chapter",
743
+ "language": 'en',
744
+ "model": model_name
745
+ }
746
+ print("payload", payload)
747
+ files = {
748
+ "file": (os.path.basename(source.source_path), file_content, "audio/mp3")
749
+ }
750
+ response = requests.post(url, headers=headers, data=payload, files=files)
751
+ log.info(response.json())
752
+ except Exception:
753
+ log.info(response)
754
+ log.info("Error occurred while reading openai response")
755
+ print(traceback.format_exc())
756
+ return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
757
+
758
+ """
759
+ #azure whisper
760
+ filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
761
+ response = None
762
+ try:
763
+ with open(source.source_path,"rb") as file:
764
+ response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
765
+ headers=HEADERS,
766
+ files={'file': file})
767
+ log.info(response.json())
768
+ except Exception:
769
+ log.info(response)
770
+ log.info("Error occurred while reading openai response")
771
+ print(traceback.format_exc())
772
+ return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
773
+ """
774
+ text = '',
775
+ qaResult1 = ''
776
+ qaResult2 = ''
777
+ qaResult3 = ''
778
+ qaResult4 = ''
779
+ if "text" in response.json():
780
+ text = response.json()["text"]
781
+
782
+ #openai.api_key = "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"
783
+ # openai.api_key = "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"
784
+ api_base = 'https://pragyaagpt4.openai.azure.com/'
785
+ api_key="9fb5af1332a648b1bba4198731e389bd"
786
+ deployment_name = 'pragyaagpt4turbo'
787
+ api_version = '2023-12-01-preview' # this might change in the future
788
+
789
+ azureClient = AzureOpenAI(
790
+ api_key=api_key,
791
+ api_version=api_version,
792
+ base_url=f"{api_base}openai/deployments/{deployment_name}/",
793
+ )
794
+ qaResult1 = azureClient.chat.completions.create(
795
+ model=deployment_name,
796
+ 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? "},
797
+ {"role": "user","content":text}],
798
+ temperature= 0.05,
799
+ max_tokens=2000,
800
+ top_p= 1,
801
+ frequency_penalty= 0,
802
+ presence_penalty= 0,
803
+ stop=None
804
+ )
805
+
806
+ #log.info("result 1",qaResult1)
807
+ qaResult1 = qaResult1.choices[0].message.content
808
+
809
+ qaResult2 = azureClient.chat.completions.create(
810
+ model=deployment_name,
811
+ 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}],
812
+ temperature= 0.05,
813
+ max_tokens=256,
814
+ top_p= 1,
815
+ frequency_penalty= 0,
816
+ presence_penalty= 0,
817
+ stop=None
818
+ )
819
+
820
+ #log.info("result 2",qaResult2)
821
+ #log.info(qaResult2['choices'][0]['message']['content'])
822
+ qaResult2 = qaResult2.choices[0].message.content
823
+
824
+ qaResult3 = azureClient.chat.completions.create(
825
+ model=deployment_name,
826
+ 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}],
827
+ temperature= 0.05,
828
+ max_tokens=256,
829
+ top_p= 1,
830
+ frequency_penalty= 0,
831
+ presence_penalty= 0,
832
+ stop=None
833
+ )
834
+ #log.info("result 3",qaResult3)
835
+ #log.info(qaResult3['choices'][0]['message']['content'])
836
+ qaResult3 = qaResult3.choices[0].message.content
837
+
838
+ qaResult4 = azureClient.chat.completions.create(
839
+ model=deployment_name,
840
+ 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}],
841
+ temperature= 0.05,
842
+ max_tokens=256,
843
+ top_p= 1,
844
+ frequency_penalty= 0,
845
+ presence_penalty= 0,
846
+ stop=None
847
+ )
848
+ #log.info("result 4",qaResult4)
849
+ #log.info(qaResult4['choices'][0]['message']['content'])
850
+ qaResult4 = qaResult4.choices[0].message.content
851
+
852
+ output_files = []
853
+ output_files.append(self.__create_file(text, outputDirectory, fileId + "-transcript.txt"));
854
+
855
+ bucket = 'acengage-bucket-v09kjo18oktg'
856
+ try:
857
+ for f in output_files:
858
+ print('source_text..', os.path.abspath(f))
859
+ s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
860
+ except:
861
+ print("Error while writing to s3, proceed")
862
+
863
+ else:
864
+ text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
865
+
866
+ return client_counsellor,text,qaResult1,qaResult2,qaResult3,qaResult4
867
+
868
+ finally:
869
+ # Cleanup source
870
+ if self.deleteUploadedFiles and validfields:
871
+ for source in sources:
872
+ print("Deleting source file " + source.source_path)
873
+
874
+ try:
875
+ bucket = 'acengage-bucket-v09kjo18oktg'
876
+ key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
877
+ s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
878
+ file_url = "https://"+bucket+".s3.amazonaws.com/"+key
879
+ #Log duration in DB before Transcibe line
880
+ try:
881
+ doc = {
882
+ 'client': client,
883
+ 'counsellor': counsellor,
884
+ 'process': process,
885
+ 'language':languageName,
886
+ 'verbatim_with_qa':'yes',
887
+ 'file': os.path.basename(source.source_path),
888
+ 'hours': hours,
889
+ 'mins': mins,
890
+ 'secs': secs,
891
+ 'request_time': datetime.datetime.now(),
892
+ 'audio_url':file_url
893
+ }
894
+ res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
895
+ #logger.info(json.dumps(res, indent=4))
896
+ data_string = json.dumps(doc, indent=2, default=str)
897
+ key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
898
+ s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
899
+ except Exception:
900
+ print ("Error occurred while inserting duration data")
901
+ print(traceback.format_exc())
902
+ os.remove(source.source_path)
903
+ except Exception as e:
904
+ # Ignore error - it's just a cleanup
905
+ print("Error deleting source file " + source.source_path + ": " + str(e))
906
+
907
+ except ExceededMaximumDuration as e:
908
+ return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s"), "[ERROR]"
909
+ except Exception as ex:
910
+ print(traceback.format_exc())
911
+ #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."
912
+
913
+ def transcribe_file(self, model: WhisperContainer, audio_path: str, language: str, task: str = None, vad: str = None,
914
+ vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1, **decodeOptions: dict):
915
+
916
+ initial_prompt = decodeOptions.pop('initial_prompt', None)
917
+
918
+ if ('task' in decodeOptions):
919
+ task = decodeOptions.pop('task')
920
+
921
+ # Callable for processing an audio file
922
+ whisperCallable = model.create_callback(language, task, initial_prompt, **decodeOptions)
923
+
924
+ # The results
925
+ if (vad == 'silero-vad'):
926
+ # Silero VAD where non-speech gaps are transcribed
927
+ process_gaps = self._create_silero_config(NonSpeechStrategy.CREATE_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
928
+ result = self.process_vad(audio_path, whisperCallable, self.vad_model, process_gaps)
929
+ elif (vad == 'silero-vad-skip-gaps'):
930
+ # Silero VAD where non-speech gaps are simply ignored
931
+ skip_gaps = self._create_silero_config(NonSpeechStrategy.SKIP, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
932
+ result = self.process_vad(audio_path, whisperCallable, self.vad_model, skip_gaps)
933
+ elif (vad == 'silero-vad-expand-into-gaps'):
934
+ # Use Silero VAD where speech-segments are expanded into non-speech gaps
935
+ expand_gaps = self._create_silero_config(NonSpeechStrategy.EXPAND_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
936
+ result = self.process_vad(audio_path, whisperCallable, self.vad_model, expand_gaps)
937
+ elif (vad == 'periodic-vad'):
938
+ # Very simple VAD - mark every 5 minutes as speech. This makes it less likely that Whisper enters an infinite loop, but
939
+ # it may create a break in the middle of a sentence, causing some artifacts.
940
+ periodic_vad = VadPeriodicTranscription()
941
+ period_config = PeriodicTranscriptionConfig(periodic_duration=vadMaxMergeSize, max_prompt_window=vadPromptWindow)
942
+ result = self.process_vad(audio_path, whisperCallable, periodic_vad, period_config)
943
+
944
+ else:
945
+ if (self._has_parallel_devices()):
946
+ # Use a simple period transcription instead, as we need to use the parallel context
947
+ periodic_vad = VadPeriodicTranscription()
948
+ period_config = PeriodicTranscriptionConfig(periodic_duration=math.inf, max_prompt_window=1)
949
+
950
+ result = self.process_vad(audio_path, whisperCallable, periodic_vad, period_config)
951
+ else:
952
+ # Default VAD
953
+ result = whisperCallable.invoke(audio_path, 0, None, None)
954
+
955
+ return result
956
+
957
+ def process_vad(self, audio_path, whisperCallable, vadModel: AbstractTranscription, vadConfig: TranscriptionConfig):
958
+ if (not self._has_parallel_devices()):
959
+ # No parallel devices, so just run the VAD and Whisper in sequence
960
+ return vadModel.transcribe(audio_path, whisperCallable, vadConfig)
961
+
962
+ gpu_devices = self.parallel_device_list
963
+
964
+ if (gpu_devices is None or len(gpu_devices) == 0):
965
+ # No GPU devices specified, pass the current environment variable to the first GPU process. This may be NULL.
966
+ gpu_devices = [os.environ.get("CUDA_VISIBLE_DEVICES", None)]
967
+
968
+ # Create parallel context if needed
969
+ if (self.gpu_parallel_context is None):
970
+ # Create a context wih processes and automatically clear the pool after 1 hour of inactivity
971
+ self.gpu_parallel_context = ParallelContext(num_processes=len(gpu_devices), auto_cleanup_timeout_seconds=self.vad_process_timeout)
972
+ # We also need a CPU context for the VAD
973
+ if (self.cpu_parallel_context is None):
974
+ self.cpu_parallel_context = ParallelContext(num_processes=self.vad_cpu_cores, auto_cleanup_timeout_seconds=self.vad_process_timeout)
975
+
976
+ parallel_vad = ParallelTranscription()
977
+ return parallel_vad.transcribe_parallel(transcription=vadModel, audio=audio_path, whisperCallable=whisperCallable,
978
+ config=vadConfig, cpu_device_count=self.vad_cpu_cores, gpu_devices=gpu_devices,
979
+ cpu_parallel_context=self.cpu_parallel_context, gpu_parallel_context=self.gpu_parallel_context)
980
+
981
+ def _has_parallel_devices(self):
982
+ return (self.parallel_device_list is not None and len(self.parallel_device_list) > 0) or self.vad_cpu_cores > 1
983
+
984
+ def _concat_prompt(self, prompt1, prompt2):
985
+ if (prompt1 is None):
986
+ return prompt2
987
+ elif (prompt2 is None):
988
+ return prompt1
989
+ else:
990
+ return prompt1 + " " + prompt2
991
+
992
+ def _create_silero_config(self, non_speech_strategy: NonSpeechStrategy, vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1):
993
+ # Use Silero VAD
994
+ if (self.vad_model is None):
995
+ self.vad_model = VadSileroTranscription()
996
+
997
+ config = TranscriptionConfig(non_speech_strategy = non_speech_strategy,
998
+ max_silent_period=vadMergeWindow, max_merge_size=vadMaxMergeSize,
999
+ segment_padding_left=vadPadding, segment_padding_right=vadPadding,
1000
+ max_prompt_window=vadPromptWindow)
1001
+
1002
+ return config
1003
+
1004
+ def write_result(self, result: dict, source_name: str, output_dir: str):
1005
+ if not os.path.exists(output_dir):
1006
+ os.makedirs(output_dir)
1007
+
1008
+ text = result["text"]
1009
+ language = result["language"]
1010
+ languageMaxLineWidth = self.__get_max_line_width(language)
1011
+
1012
+ print("Max line width " + str(languageMaxLineWidth))
1013
+ vtt = self.__get_subs(result["segments"], "vtt", languageMaxLineWidth)
1014
+ srt = self.__get_subs(result["segments"], "srt", languageMaxLineWidth)
1015
+
1016
+ output_files = []
1017
+ output_files.append(self.__create_file(srt, output_dir, source_name + "-subs.srt"));
1018
+ output_files.append(self.__create_file(vtt, output_dir, source_name + "-subs.vtt"));
1019
+ output_files.append(self.__create_file(text, output_dir, source_name + "-transcript.txt"));
1020
+
1021
+ dest = '/content/drive/MyDrive/aceNgage_transcripts/'
1022
+ # try:
1023
+ # if not os.path.exists(os.path.dirname(dest)):
1024
+ # os.makedirs(os.path.dirname(dest))
1025
+ # except OSError as err:
1026
+ # print(err)
1027
+ # for f in output_files:
1028
+ # print('source_text..', os.path.abspath(f))
1029
+ # shutil.copy(os.path.abspath(f),dest)
1030
+ bucket = 'acengage-bucket-v09kjo18oktg'
1031
+ try:
1032
+ for f in output_files:
1033
+ print('source_text..', os.path.abspath(f))
1034
+ s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
1035
+ except:
1036
+ print("Error while writing to s3, proceed")
1037
+ return output_files, text, vtt
1038
+
1039
+ def clear_cache(self):
1040
+ self.model_cache.clear()
1041
+ self.vad_model = None
1042
+
1043
+ def __get_source(self, urlData, multipleFiles, microphoneData):
1044
+ return get_audio_source_collection(urlData, multipleFiles, microphoneData, self.inputAudioMaxDuration)
1045
+
1046
+ def __get_max_line_width(self, language: str) -> int:
1047
+ if (language and language.lower() in ["japanese", "ja", "chinese", "zh"]):
1048
+ # Chinese characters and kana are wider, so limit line length to 40 characters
1049
+ return 40
1050
+ else:
1051
+ # TODO: Add more languages
1052
+ # 80 latin characters should fit on a 1080p/720p screen
1053
+ return 80
1054
+
1055
+ def __get_subs(self, segments: Iterator[dict], format: str, maxLineWidth: int) -> str:
1056
+ segmentStream = StringIO()
1057
+
1058
+ if format == 'vtt':
1059
+ write_vtt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
1060
+ elif format == 'srt':
1061
+ write_srt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
1062
+ else:
1063
+ raise Exception("Unknown format " + format)
1064
+
1065
+ segmentStream.seek(0)
1066
+ return segmentStream.read()
1067
+
1068
+ def __create_file(self, text: str, directory: str, fileName: str) -> str:
1069
+ # Write the text to a file
1070
+ with open(os.path.join(directory, fileName), 'w+', encoding="utf-8") as file:
1071
+ file.write(text)
1072
+
1073
+ return file.name
1074
+
1075
+ def close(self):
1076
+ print("Closing parallel contexts")
1077
+ self.clear_cache()
1078
+
1079
+ if (self.gpu_parallel_context is not None):
1080
+ self.gpu_parallel_context.close()
1081
+ if (self.cpu_parallel_context is not None):
1082
+ self.cpu_parallel_context.close()
1083
+ def create_ui(input_audio_max_duration, share=False, server_name: str = None, server_port: int = 7860,
1084
+ default_model_name: str = "medium", default_vad: str = None, vad_parallel_devices: str = None,
1085
+ vad_process_timeout: float = None, vad_cpu_cores: int = 1, auto_parallel: bool = False,
1086
+ output_dir: str = None):
1087
+ ui = WhisperTranscriber(input_audio_max_duration, vad_process_timeout, vad_cpu_cores, DELETE_UPLOADED_FILES, output_dir)
1088
+
1089
+ # Specify a list of devices to use for parallel processing
1090
+ ui.set_parallel_devices(vad_parallel_devices)
1091
+ ui.set_auto_parallel(auto_parallel)
1092
+
1093
+ ui_description = "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs "
1094
+ #ui_description += " audio and is also a multi-task model that can perform multilingual speech recognition "
1095
+ #ui_description += " as well as speech translation and language identification. "
1096
+
1097
+ #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."
1098
+
1099
+ #if input_audio_max_duration > 0:
1100
+ # ui_description += "\n\n" + "Max audio file length: " + str(input_audio_max_duration) + " s"
1101
+
1102
+ #ui_article = "Read the [documentation here](https://gitlab.com/aadnk/whisper-webui/-/blob/main/docs/options.md)"
1103
+ import requests
1104
+ results = []
1105
+ def getAudios(agent, dest,fromDate, toDate):
1106
+ url_out = 'https://api-smartflo.tatateleservices.com/v1/call/records?direction=outbound&limit=100'
1107
+ p = {
1108
+ "from_date":str(fromDate),
1109
+ "to_date":str(toDate),
1110
+ "agents":str(agent),
1111
+ "destination":str(dest)
1112
+ }
1113
+ resp = requests.get(url_out, params=p,
1114
+ headers={'Content-Type':'application/json',
1115
+ 'Authorization': 'Bearer {}'.
1116
+ format('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjg5ODkyLCJpc3MiOiJodHRwczpcL1wvY2xvdWRwaG9uZS50YXRhdGVsZXNlcnZpY2VzLmNvbVwvdG9rZW5cL2dlbmVyYXRlIiwiaWF0IjoxNjcyMTM0MjYzLCJleHAiOjE5NzIxMzQyNjMsIm5iZiI6MTY3MjEzNDI2MywianRpIjoiN3hqR25ydGZyUWprMmZjdSJ9.-nno38JWqGMXu_djqYw2ExO_IhfACebjfMN-Tb1pgCQ')})
1117
+ data = resp.json()
1118
+
1119
+
1120
+ results = []
1121
+ # Now you can access Json
1122
+ for i in data['results']:
1123
+ client_number = str(i['client_number']) if i['client_number'] is not None else ''
1124
+ call_duration = str(i['call_duration']) if i['call_duration'] is not None else ''
1125
+ end_stamp = str(i['end_stamp']) if i['end_stamp'] is not None else ''
1126
+ agent_id=''
1127
+ if len(i["call_flow"])>1:
1128
+ agent_id = i["call_flow"][1]["id"]
1129
+ call_type='Outbound'
1130
+ recording_url = [client_number,call_duration,agent_id, call_type,end_stamp,i['recording_url']]
1131
+ results.append(recording_url)
1132
+
1133
+ url_in = 'https://api-smartflo.tatateleservices.com/v1/call/records?direction=inbound&limit=100'
1134
+ p = {
1135
+ "from_date":str(fromDate),
1136
+ "to_date":str(toDate),
1137
+ "agents":str(agent),
1138
+ "destination":str(dest)
1139
+ }
1140
+ resp = requests.get(url_in, params=p,
1141
+ headers={'Content-Type':'application/json',
1142
+ 'Authorization': 'Bearer {}'.
1143
+ format('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjg5ODkyLCJpc3MiOiJodHRwczpcL1wvY2xvdWRwaG9uZS50YXRhdGVsZXNlcnZpY2VzLmNvbVwvdG9rZW5cL2dlbmVyYXRlIiwiaWF0IjoxNjcyMTM0MjYzLCJleHAiOjE5NzIxMzQyNjMsIm5iZiI6MTY3MjEzNDI2MywianRpIjoiN3hqR25ydGZyUWprMmZjdSJ9.-nno38JWqGMXu_djqYw2ExO_IhfACebjfMN-Tb1pgCQ')})
1144
+ data = resp.json()
1145
+
1146
+
1147
+ # Now you can access Json
1148
+ for i in data['results']:
1149
+ client_number = str(i['client_number']) if i['client_number'] is not None else ''
1150
+ call_duration = str(i['call_duration']) if i['call_duration'] is not None else ''
1151
+ end_stamp = str(i['end_stamp']) if i['end_stamp'] is not None else ''
1152
+ agent_id=''
1153
+ if len(i["call_flow"])>1:
1154
+ agent_id = i["call_flow"][1]["id"]
1155
+ call_type = 'Inbound'
1156
+ recording_url = [client_number,call_duration,agent_id, call_type,end_stamp,i['recording_url']]
1157
+ results.append(recording_url)
1158
+ return results
1159
+ io1 = gr.Interface(
1160
+ fn=getAudios,
1161
+ inputs=[gr.Textbox(label="Agent Id"),gr.Textbox(label="Destination",placeholder="10 digit phone number"),
1162
+ gr.Textbox(label="From Date",placeholder="yyyy-mm-dd"), gr.Textbox(label="To Date", placeholder="yyyy-mm-dd")],
1163
+ outputs=[gr.Dataframe(
1164
+ headers=["Candidate Number", "Duration (in seconds)", "Agent Id", 'Call Type', "Call End Time", "Recording URL"],
1165
+ datatype=["str", "str","str","str", "str", "str"],
1166
+ label="Recordings",wrap=True
1167
+ )],
1168
+ #outputs=[gr.Radio(label="Results")],
1169
+ )
1170
+
1171
+
1172
+ simple_inputs = lambda : [
1173
+ 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",
1174
+ "AllState","CITI","Wells Fargo","Hindalco","Vodafone"], label="Client"),
1175
+ # gr.Dropdown(choices=["Anushree Shetti", "Manshi Y","Taskeen Ahmed","Tabrez","Varsha Amarnath","Kanwagi Kaushik","Hemani Shah","Seema Singh","Chaya Ramesh",
1176
+ # "Kajal Khanna","Vandana Vijeshwar","Elizabeth Sam","Sharanya Selvam","Neha Prasad","Swati Shyam","Lakshmi Thanuja","Saniya Afreen","Smita Alex","Punit Chandok",
1177
+ # "Vanessa"], label="Counsellor"),
1178
+
1179
+ gr.Dropdown(choices=["Exits", "CE", "NHE"], label="Process (*)"),
1180
+ 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",
1181
+ "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 (*)"),
1182
+ gr.Dropdown(choices=WHISPER_MODELS, value=default_model_name, label="Model"),
1183
+ gr.Dropdown(choices=sorted(LANGUAGES), label="Language", visible=False),
1184
+ gr.Text(label="URL (YouTube, etc.)"),
1185
+ gr.File(label="Upload Files", file_count="multiple"),
1186
+ gr.Audio(source="microphone", type="filepath", label="Microphone Input"),
1187
+
1188
+
1189
+ gr.Dropdown(choices=["transcribe", "translate"], label="Task",visible=False),
1190
+ gr.Dropdown(choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], value=default_vad, label="VAD",visible=False),
1191
+ gr.Number(label="VAD - Merge Window (s)", precision=0, value=5,visible=False),
1192
+ gr.Number(label="VAD - Max Merge Size (s)", precision=0, value=30,visible=False),
1193
+ gr.Number(label="VAD - Padding (s)", precision=None, value=1,visible=False),
1194
+ gr.Number(label="VAD - Prompt Window (s)", precision=None, value=3,visible=False)
1195
+ ]
1196
+
1197
+ io2 = gr.Interface(fn=ui.transcribe_webui, description=ui_description, article='', inputs=[
1198
+
1199
+ 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",
1200
+ "AllState","CITI","Wells Fargo","Hindalco","Vodafone"], label="Client"),
1201
+ # gr.Dropdown(choices=["Anushree Shetti", "Manshi Y","Taskeen Ahmed","Tabrez","Varsha Amarnath","Kanwagi Kaushik","Hemani Shah","Seema Singh","Chaya Ramesh",
1202
+ # "Kajal Khanna","Vandana Vijeshwar","Elizabeth Sam","Sharanya Selvam","Neha Prasad","Swati Shyam","Lakshmi Thanuja","Saniya Afreen","Smita Alex","Punit Chandok",
1203
+ # "Vanessa"], label="Counsellor"),
1204
+
1205
+ gr.Dropdown(choices=["Exits", "CE", "NHE"], label="Process (*)"),
1206
+ 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",
1207
+ "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 (*)"),
1208
+ gr.Dropdown(choices=WHISPER_MODELS, value=default_model_name, label="Model"),
1209
+ gr.Dropdown(choices=sorted(LANGUAGES), label="Language"),
1210
+ gr.Text(label="URL (YouTube, etc.)"),
1211
+ gr.File(label="Upload Files", file_count="multiple"),
1212
+ gr.Audio(source="microphone", type="filepath", label="Microphone Input"),
1213
+
1214
+
1215
+ gr.Dropdown(choices=["transcribe", "translate"], label="Task",visible=False),
1216
+ gr.Dropdown(choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], value=default_vad, label="VAD",visible=False),
1217
+ gr.Number(label="VAD - Merge Window (s)", precision=0, value=5,visible=False),
1218
+ gr.Number(label="VAD - Max Merge Size (s)", precision=0, value=30,visible=False),
1219
+ gr.Number(label="VAD - Padding (s)", precision=None, value=1,visible=False),
1220
+ gr.Number(label="VAD - Prompt Window (s)", precision=None, value=3,visible=False)
1221
+ ], outputs=[
1222
+ gr.Textbox(label="Client, Counsellor, Process"),
1223
+ gr.File(label="Download"),
1224
+ gr.Text(label="Transcription"),
1225
+ gr.Text(label="Segments")
1226
+ ])
1227
+ """
1228
+ io3 = gr.Interface(fn=ui.transcribe_webui_full, description=ui_description, article='', inputs=[
1229
+ *simple_inputs(),
1230
+ gr.Dropdown(choices=["prepend_first_segment", "prepend_all_segments"], value=app_config.vad_initial_prompt_mode, label="VAD - Initial Prompt Mode"),
1231
+ gr.TextArea(label="Initial Prompt"),
1232
+ gr.Number(label="Temperature", value=app_config.temperature),
1233
+ gr.Number(label="Best Of - Non-zero temperature", value=app_config.best_of, precision=0),
1234
+ gr.Number(label="Beam Size - Zero temperature", value=app_config.beam_size, precision=0),
1235
+ gr.Number(label="Patience - Zero temperature", value=app_config.patience),
1236
+ gr.Number(label="Length Penalty - Any temperature", value=app_config.length_penalty),
1237
+ gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value=app_config.suppress_tokens),
1238
+ gr.Checkbox(label="Condition on previous text", value=app_config.condition_on_previous_text),
1239
+ gr.Checkbox(label="FP16", value=app_config.fp16),
1240
+ gr.Number(label="Temperature increment on fallback", value=app_config.temperature_increment_on_fallback),
1241
+ gr.Number(label="Compression ratio threshold", value=app_config.compression_ratio_threshold),
1242
+ gr.Number(label="Logprob threshold", value=app_config.logprob_threshold),
1243
+ gr.Number(label="No speech threshold", value=app_config.no_speech_threshold)
1244
+ ], outputs=[
1245
+ gr.File(label="Download"),
1246
+ gr.Text(label="Transcription"),
1247
+ gr.Text(label="Segments")
1248
+ ])
1249
+ """
1250
+ io3 = gr.Interface(fn=ui.transcribe_webui_full, description=ui_description, article='', inputs=[
1251
+ *simple_inputs(),
1252
+ gr.TextArea(label="Initial Prompt", visible=False),
1253
+ gr.Number(label="Temperature", value=0, visible=False),
1254
+ gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
1255
+ gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
1256
+ gr.Number(label="Patience - Zero temperature", value=None,visible=False),
1257
+ gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
1258
+ gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
1259
+ gr.Checkbox(label="Condition on previous text", value=True,visible=False),
1260
+ gr.Checkbox(label="FP16", value=True,visible=False),
1261
+ gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
1262
+ gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
1263
+ gr.Number(label="Logprob threshold", value=-1.0,visible=False),
1264
+ gr.Number(label="No speech threshold", value=0.6,visible=False)
1265
+ ], outputs=[
1266
+ gr.Textbox(label="Client, Counsellor, Process"),
1267
+ #gr.File(label="Download"),
1268
+ gr.Text(label="Transcription"),
1269
+ ])
1270
+
1271
+ io4 = gr.Interface(fn=ui.transcribe_webui_full_verbatim, description=ui_description, article='', inputs=[
1272
+ *simple_inputs(),
1273
+ gr.TextArea(label="Initial Prompt", visible=False),
1274
+ gr.Number(label="Temperature", value=0, visible=False),
1275
+ gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
1276
+ gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
1277
+ gr.Number(label="Patience - Zero temperature", value=None,visible=False),
1278
+ gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
1279
+ gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
1280
+ gr.Checkbox(label="Condition on previous text", value=True,visible=False),
1281
+ gr.Checkbox(label="FP16", value=True,visible=False),
1282
+ gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
1283
+ gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
1284
+ gr.Number(label="Logprob threshold", value=-1.0,visible=False),
1285
+ gr.Number(label="No speech threshold", value=0.6,visible=False)
1286
+ ], outputs=[
1287
+ gr.Textbox(label="Client, Counsellor, Process"),
1288
+ #gr.File(label="Download"),
1289
+ gr.Text(label="Transcription"),
1290
+ gr.Text(label="Proposed Verbatim - Please review & update as required")
1291
+ #gr.Text(label="Segments")
1292
+ ])
1293
+
1294
+ io5 = gr.Interface(fn=ui.transcribe_webui_full_verbatim_qa, description=ui_description, article='', inputs=[
1295
+ *simple_inputs(),
1296
+ 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? "),
1297
+ 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? "),
1298
+ 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?"),
1299
+ 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? "),
1300
+ gr.TextArea(label="Initial Prompt", visible=False),
1301
+ gr.Number(label="Temperature", value=0, visible=False),
1302
+ gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
1303
+ gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
1304
+ gr.Number(label="Patience - Zero temperature", value=None,visible=False),
1305
+ gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
1306
+ gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
1307
+ gr.Checkbox(label="Condition on previous text", value=True,visible=False),
1308
+ gr.Checkbox(label="FP16", value=True,visible=False),
1309
+ gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
1310
+ gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
1311
+ gr.Number(label="Logprob threshold", value=-1.0,visible=False),
1312
+ gr.Number(label="No speech threshold", value=0.6,visible=False)
1313
+ ], outputs=[
1314
+ gr.Textbox(label="Client, Counsellor, Process"),
1315
+ gr.Text(label="Transcription"),
1316
+ gr.Text(label="Answers For Questionnaire 3 - Set 1"),
1317
+ gr.Text(label="Answers For Questionnaire 3 - Set 2"),
1318
+ gr.Text(label="Answers For Questionnaire 3 - Set 3"),
1319
+ gr.Text(label="Answers For Questionnaire 3 - Set 4"),
1320
+ ])
1321
+
1322
+
1323
+ #demo.launch(share=share, server_name=server_name, server_port=server_port)
1324
+ gr.TabbedInterface(
1325
+ [io1, io3,io4, io5], ["Pragyaa Select", "Pragyaa Transcribe", "Pragyaa Transcribe With Verbatim","Pragyaa Transcribe With Questionnaire"]
1326
+ ).queue(concurrency_count=5).launch(share=share, server_name=server_name, server_port=server_port)
1327
+
1328
+
1329
+ # Clean up
1330
+ ui.close()
1331
+
1332
+ if __name__ == '__main__':
1333
+ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
1334
+ 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.")
1335
+ parser.add_argument("--share", type=bool, default=False, help="True to share the app on HuggingFace.")
1336
+ parser.add_argument("--server_name", type=str, default=None, help="The host or IP to bind to. If None, bind to localhost.")
1337
+ parser.add_argument("--server_port", type=int, default=7860, help="The port to bind to.")
1338
+ parser.add_argument("--default_model_name", type=str, choices=WHISPER_MODELS, default="medium", help="The default model name.")
1339
+ parser.add_argument("--default_vad", type=str, default="silero-vad", help="The default VAD.")
1340
+ 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.")
1341
+ parser.add_argument("--vad_cpu_cores", type=int, default=1, help="The number of CPU cores to use for VAD pre-processing.")
1342
+ 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.")
1343
+ 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.")
1344
+ parser.add_argument("--output_dir", "-o", type=str, default=None, help="directory to save the outputs")
1345
+
1346
+ args = parser.parse_args().__dict__
1347
+ create_ui(**args)
requirements.txt ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ acme==1.1.0
2
+ aiofiles==23.2.1
3
+ aiohttp==3.8.6
4
+ aiosignal==1.3.1
5
+ altair==5.1.2
6
+ amqp==5.0.6
7
+ annotated-types==0.6.0
8
+ anyio==3.7.1
9
+ APScheduler==3.9.1
10
+ asgiref==3.5.2
11
+ async-timeout==4.0.3
12
+ attrs==21.2.0
13
+ audioread==3.0.1
14
+ autobahn==21.3.1
15
+ Automat==20.2.0
16
+ autopep8==1.6.0
17
+ aws-requests-auth==0.4.3
18
+ awscli==1.29.76
19
+ billiard==3.6.4.0
20
+ blinker==1.6.3
21
+ boto==2.49.0
22
+ boto3==1.18.34
23
+ botocore==1.21.34
24
+ Brotli==1.1.0
25
+ celery==5.1.2
26
+ certbot==0.40.0
27
+ certbot-apache==0.39.0
28
+ certifi==2021.5.30
29
+ cffi==1.14.6
30
+ channels==3.0.4
31
+ chardet==3.0.4
32
+ charset-normalizer==2.0.4
33
+ cliapp==1.20180812.1
34
+ click==8.1.7
35
+ click-didyoumean==0.0.3
36
+ click-plugins==1.1.1
37
+ click-repl==0.2.0
38
+ cloud-init==23.3.1
39
+ cmdtest==0.32+git
40
+ colorama==0.4.3
41
+ command-not-found==0.3
42
+ ConfigArgParse==0.13.0
43
+ configobj==5.0.6
44
+ constantly==15.1.0
45
+ contourpy==1.1.1
46
+ coreapi==2.3.3
47
+ coreschema==0.0.4
48
+ cryptography==3.4.8
49
+ cycler==0.12.1
50
+ daphne==3.0.2
51
+ dbus-python==1.2.16
52
+ defusedxml==0.7.1
53
+ distro==1.9.0
54
+ distro-info==0.23+ubuntu1.1
55
+ Django==4.0.4
56
+ django-allauth==0.45.0
57
+ django-celery-results==2.2.0
58
+ django-cors-headers==3.8.0
59
+ django-elasticsearch-dsl==7.2.0
60
+ django-elasticsearch-dsl-drf==0.22.2
61
+ django-environ==0.9.0
62
+ django-nine==0.2.5
63
+ django-rest-auth==0.9.5
64
+ django-silk==5.0.1
65
+ django-templated-mail==1.1.1
66
+ djangorestframework==3.12.2
67
+ djangorestframework-simplejwt==4.6.0
68
+ djongo==1.3.6
69
+ dnspython==2.0.0
70
+ docutils==0.16
71
+ drf-yasg==1.21.3
72
+ ec2-hibinit-agent==1.0.0
73
+ elastic-transport==8.4.1
74
+ elasticsearch==7.12.0
75
+ elasticsearch-dsl==7.3.0
76
+ entrypoints==0.3
77
+ et-xmlfile==1.1.0
78
+ exceptiongroup==1.1.3
79
+ fastapi==0.104.0
80
+ ffmpeg==1.4
81
+ ffmpeg-python==0.2.0
82
+ ffmpy==0.3.1
83
+ filelock==3.12.4
84
+ Flask==3.0.0
85
+ Flask-Cors==4.0.0
86
+ fonttools==4.43.1
87
+ frozenlist==1.4.0
88
+ fsspec==2023.10.0
89
+ future==0.18.3
90
+ fuzzywuzzy==0.18.0
91
+ gprof2dot==2022.7.29
92
+ gradio==3.40.0
93
+ gradio_client==0.7.0
94
+ gunicorn==21.2.0
95
+ h11==0.14.0
96
+ hibagent==1.0.1
97
+ httpcore==0.18.0
98
+ httplib2==0.14.0
99
+ httpx==0.25.0
100
+ huggingface-hub==0.18.0
101
+ hyperlink==21.0.0
102
+ idna==3.2
103
+ importlib-metadata==6.8.0
104
+ importlib-resources==6.1.0
105
+ incremental==21.3.0
106
+ inflection==0.5.1
107
+ itsdangerous==2.1.2
108
+ itypes==1.2.0
109
+ Jinja2==3.1.2
110
+ jmespath==0.10.0
111
+ joblib==1.3.2
112
+ josepy==1.2.0
113
+ jsonpatch==1.22
114
+ jsonpointer==2.0
115
+ jsonschema==3.2.0
116
+ keyring==18.0.1
117
+ kiwisolver==1.4.5
118
+ kombu==5.1.0
119
+ language-selector==0.1
120
+ launchpadlib==1.10.13
121
+ lazr.restfulclient==0.14.2
122
+ lazr.uri==1.0.3
123
+ Levenshtein==0.23.0
124
+ linkify-it-py==2.0.2
125
+ lxml==4.9.3
126
+ Markdown==3.1.1
127
+ markdown-it-py==2.2.0
128
+ MarkupSafe==2.1.1
129
+ matplotlib==3.8.0
130
+ mdit-py-plugins==0.3.3
131
+ mdurl==0.1.2
132
+ mock==3.0.5
133
+ more-itertools==10.1.0
134
+ mpmath==1.3.0
135
+ multidict==6.0.4
136
+ mutagen==1.47.0
137
+ netifaces==0.10.4
138
+ networkx==3.2
139
+ nltk==3.8.1
140
+ numpy==1.22.4
141
+ nvidia-cublas-cu12==12.1.3.1
142
+ nvidia-cuda-cupti-cu12==12.1.105
143
+ nvidia-cuda-nvrtc-cu12==12.1.105
144
+ nvidia-cuda-runtime-cu12==12.1.105
145
+ nvidia-cudnn-cu12==8.9.2.26
146
+ nvidia-cufft-cu12==11.0.2.54
147
+ nvidia-curand-cu12==10.3.2.106
148
+ nvidia-cusolver-cu12==11.4.5.107
149
+ nvidia-cusparse-cu12==12.1.0.106
150
+ nvidia-nccl-cu12==2.18.1
151
+ nvidia-nvjitlink-cu12==12.3.52
152
+ nvidia-nvtx-cu12==12.1.105
153
+ oauthlib==3.1.1
154
+ olefile==0.46
155
+ openai==1.12.0
156
+ openpyxl==3.1.2
157
+ orjson==3.9.10
158
+ packaging==21.3
159
+ pandas==1.4.3
160
+ parsedatetime==2.4
161
+ pbr==5.4.5
162
+ pexpect==4.6.0
163
+ pika==1.2.0
164
+ Pillow==9.1.1
165
+ prettytable==2.2.0
166
+ prompt-toolkit==3.0.20
167
+ psutil==5.8.0
168
+ psycopg2==2.8.4
169
+ psycopg2-binary==2.9.9
170
+ pyasn1==0.4.8
171
+ pyasn1-modules==0.2.8
172
+ pycodestyle==2.11.1
173
+ pycparser==2.20
174
+ pycryptodome==3.4.3
175
+ pycryptodomex==3.19.0
176
+ pydantic==2.4.2
177
+ pydantic_core==2.10.1
178
+ pydub==0.25.1
179
+ Pygments==2.16.1
180
+ PyGObject==3.36.0
181
+ PyHamcrest==1.9.0
182
+ PyICU==2.4.2
183
+ PyJWT==2.4.0
184
+ pymacaroons==0.13.0
185
+ pymongo==3.11.2
186
+ PyNaCl==1.3.0
187
+ pyOpenSSL==20.0.1
188
+ pyparsing==3.0.9
189
+ pyRFC3339==1.1
190
+ pyrsistent==0.15.5
191
+ pyserial==3.4
192
+ python-apt==2.0.1+ubuntu0.20.4.1
193
+ python-augeas==0.5.0
194
+ python-dateutil==2.8.2
195
+ python-debian==0.1.36+ubuntu1.1
196
+ python-Levenshtein==0.23.0
197
+ python-multipart==0.0.6
198
+ python3-openid==3.2.0
199
+ pytz==2022.1
200
+ PyYAML==5.3.1
201
+ rapidfuzz==3.4.0
202
+ regex==2023.10.3
203
+ requests==2.26.0
204
+ requests-oauthlib==1.3.0
205
+ requests-toolbelt==0.8.0
206
+ requests-unixsocket==0.2.0
207
+ rich==13.7.0
208
+ roman==2.0.0
209
+ rsa==4.0
210
+ ruamel.yaml==0.17.21
211
+ ruamel.yaml.clib==0.2.6
212
+ s3transfer==0.5.0
213
+ SecretStorage==2.3.1
214
+ semantic-version==2.10.0
215
+ service-identity==21.1.0
216
+ shellingham==1.5.4
217
+ simplejson==3.16.0
218
+ six==1.16.0
219
+ sniffio==1.3.0
220
+ sos==4.5.6
221
+ sqlparse==0.2.4
222
+ ssh-import-id==5.10
223
+ starlette==0.27.0
224
+ stripe==2.56.0
225
+ sympy==1.12
226
+ systemd-python==234
227
+ toml==0.10.2
228
+ tomlkit==0.12.0
229
+ toolz==0.12.0
230
+ torch==2.1.0
231
+ tqdm==4.66.1
232
+ triton==2.1.0
233
+ ttystatus==0.38
234
+ Twisted==22.4.0
235
+ txaio==23.1.1
236
+ typer==0.9.0
237
+ typing_extensions==4.8.0
238
+ tzdata==2022.1
239
+ tzlocal==5.2
240
+ ubuntu-advantage-tools==8001
241
+ uc-micro-py==1.0.2
242
+ ufw==0.36
243
+ unattended-upgrades==0.1
244
+ uritemplate==4.1.1
245
+ urllib3==1.26.6
246
+ uvicorn==0.23.2
247
+ vine==5.0.0
248
+ w3lib==2.1.2
249
+ wadllib==1.3.3
250
+ wcwidth==0.2.5
251
+ websockets==11.0.3
252
+ Werkzeug==3.0.1
253
+ whisper==1.1.10
254
+ yarl==1.9.2
255
+ yt-dlp==2023.10.13
256
+ zipp==3.17.0
257
+ zope.component==4.3.0
258
+ zope.event==4.4
259
+ zope.hookable==5.0.0
260
+ zope.interface==5.4.0