pragyaa-app / app.py
pragyaa's picture
Upload app.py
b1c3d0e verified
from datetime import datetime
import math
from typing import Iterator
import argparse
import boto3
import uuid
from io import StringIO
import os
import pathlib
import tempfile
import zipfile
import numpy as np
#import sqlite3
from src.utils import duration_detector
import datetime
import shutil
import json
import torch
from src.modelCache import ModelCache
from src.source import get_audio_source_collection
from src.vadParallel import ParallelContext, ParallelTranscription
# External programs
import ffmpeg
from aws_requests_auth.aws_auth import AWSRequestsAuth
from elasticsearch import Elasticsearch, RequestsHttpConnection
from elasticsearch import helpers
import certifi
#logging
from pytz import timezone
import logging
import sys
logging.Formatter.converter = lambda *args: datetime.datetime.now(tz=timezone('Asia/Kolkata')).timetuple()
logging.basicConfig(
format="%(asctime)s %(levelname)s: %(message)s",
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S",
)
console = logging.StreamHandler(sys.stdout)
log = logging.getLogger(__name__)
# UI
import gradio as gr
import traceback
from src.download import ExceededMaximumDuration, download_url
from src.utils import slugify, write_srt, write_vtt
from src.vad import AbstractTranscription, NonSpeechStrategy, PeriodicTranscriptionConfig, TranscriptionConfig, VadPeriodicTranscription, VadSileroTranscription
from src.whisperContainer import WhisperContainer
session = boto3.Session(
aws_access_key_id='AKIAZB4KTGHMCHLYIZXK',
aws_secret_access_key='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',
)
s3 = session.resource('s3')
#client = boto3.client('dynamodb')
import requests
import os
#openai
import openai
from openai import AzureOpenAI
OPENAI_API_KEY = "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"
#OPENAI_API_KEY = "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"
token = f"Bearer {OPENAI_API_KEY}"
url = "https://api.openai.com/v1/audio/transcriptions"
model_name ="whisper-1"
headers ={
"Authorization": token
#"Content-Type": "multipart/form-data"
}
#azure whisper
"""
openai.api_key = '142805a982184d289203b387062bfb29'
openai.api_base = 'https://pragyaawhisper3.openai.azure.com' # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
openai.api_type = "azure"
openai.api_version = "2023-09-01-preview"
model_name = "whisper"
deployment_id = "whisper3" #This will correspond to the custom name you chose for your deployment when you deployed a model."
audio_language="en"
"""
AZURE_OPENAI_ENDPOINT = 'https://pragyaawhisper3.openai.azure.com/'
AZURE_OPENAI_KEY = '142805a982184d289203b387062bfb29'
MODEL_NAME = 'whisper3'
HEADERS = { "api-key" : AZURE_OPENAI_KEY }
# get the Elasticsearch index name from the environment variables
acengage_index = 'acengage-sessions'
esendpoint = 'search-mediassist-indexer-l5jj553cigi5qbir5f4rdzuhoe.us-east-1.es.amazonaws.com'
#esendpoint = 'search-prime-indexer-jif4ysiafk74aep2w6elx4pn5q.us-east-1.es.amazonaws.com'
region = 'us-east-1'
# Create the auth token for the sigv4 signature
"""
session = boto3.session.Session()
credentials = session.get_credentials().get_frozen_credentials()
awsauth = AWSRequestsAuth(
aws_access_key=credentials.access_key,
aws_secret_access_key=credentials.secret_key,
aws_token=credentials.token,
aws_host=esendpoint,
aws_region=region,
aws_service='es'
)
"""
# Connect to the elasticsearch cluster using aws authentication. The lambda function
# must have access in an IAM policy to the ES cluster.
es = Elasticsearch(
hosts=[{'host': esendpoint, 'port': 443}],
http_auth=('kibanauser','Threeguys01!'),
use_ssl=True,
verify_certs=True,
ca_certs=certifi.where(),
timeout=120,
connection_class=RequestsHttpConnection
)
# Limitations (set to -1 to disable)
DEFAULT_INPUT_AUDIO_MAX_DURATION = 600 # seconds
# Whether or not to automatically delete all uploaded files, to save disk space
DELETE_UPLOADED_FILES = True
# Gradio seems to truncate files without keeping the extension, so we need to truncate the file prefix ourself
MAX_FILE_PREFIX_LENGTH = 17
# Limit auto_parallel to a certain number of CPUs (specify vad_cpu_cores to get a higher number)
MAX_AUTO_CPU_CORES = 8
LANGUAGES = [
"English", "Chinese", "German", "Spanish", "Russian", "Korean",
"French", "Japanese", "Portuguese", "Turkish", "Polish", "Catalan",
"Dutch", "Arabic", "Swedish", "Italian", "Indonesian", "Hindi",
"Finnish", "Vietnamese", "Hebrew", "Ukrainian", "Greek", "Malay",
"Czech", "Romanian", "Danish", "Hungarian", "Tamil", "Norwegian",
"Thai", "Urdu", "Croatian", "Bulgarian", "Lithuanian", "Latin",
"Maori", "Malayalam", "Welsh", "Slovak", "Telugu", "Persian",
"Latvian", "Bengali", "Serbian", "Azerbaijani", "Slovenian",
"Kannada", "Estonian", "Macedonian", "Breton", "Basque", "Icelandic",
"Armenian", "Nepali", "Mongolian", "Bosnian", "Kazakh", "Albanian",
"Swahili", "Galician", "Marathi", "Punjabi", "Sinhala", "Khmer",
"Shona", "Yoruba", "Somali", "Afrikaans", "Occitan", "Georgian",
"Belarusian", "Tajik", "Sindhi", "Gujarati", "Amharic", "Yiddish",
"Lao", "Uzbek", "Faroese", "Haitian Creole", "Pashto", "Turkmen",
"Nynorsk", "Maltese", "Sanskrit", "Luxembourgish", "Myanmar", "Tibetan",
"Tagalog", "Malagasy", "Assamese", "Tatar", "Hawaiian", "Lingala",
"Hausa", "Bashkir", "Javanese", "Sundanese"
]
WHISPER_MODELS = ["tiny", "base", "small", "medium", "large", "large-v1", "large-v2"]
class WhisperTranscriber:
def __init__(self, input_audio_max_duration: float = DEFAULT_INPUT_AUDIO_MAX_DURATION, vad_process_timeout: float = None,
vad_cpu_cores: int = 1, delete_uploaded_files: bool = DELETE_UPLOADED_FILES, output_dir: str = None):
self.model_cache = ModelCache()
self.parallel_device_list = None
self.gpu_parallel_context = None
self.cpu_parallel_context = None
self.vad_process_timeout = vad_process_timeout
self.vad_cpu_cores = vad_cpu_cores
self.vad_model = None
self.inputAudioMaxDuration = input_audio_max_duration
self.deleteUploadedFiles = delete_uploaded_files
self.output_dir = output_dir
def set_parallel_devices(self, vad_parallel_devices: str):
self.parallel_device_list = [ device.strip() for device in vad_parallel_devices.split(",") ] if vad_parallel_devices else None
def set_auto_parallel(self, auto_parallel: bool):
if auto_parallel:
if torch.cuda.is_available():
self.parallel_device_list = [ str(gpu_id) for gpu_id in range(torch.cuda.device_count())]
self.vad_cpu_cores = min(os.cpu_count(), MAX_AUTO_CPU_CORES)
print("[Auto parallel] Using GPU devices " + str(self.parallel_device_list) + " and " + str(self.vad_cpu_cores) + " CPU cores for VAD/transcription.")
# Entry function for the simple tab
def transcribe_webui_simple(self, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow):
return self.transcribe_webui(modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
# Entry function for the full tab
def transcribe_webui_full_verbatim(self, client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str,
condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):
# Handle temperature_increment_on_fallback
if temperature_increment_on_fallback is not None:
temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
else:
temperature = [temperature]
return self.transcribe_webui_verbatim(client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
condition_on_previous_text=condition_on_previous_text, fp16=fp16,
compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
# Entry function for the full tab
def transcribe_webui_full_verbatim_qa(self, client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
qSet1:str, qSet2:str, qSet3:str,qSet4:str,initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str,
condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):
# Handle temperature_increment_on_fallback
if temperature_increment_on_fallback is not None:
temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
else:
temperature = [temperature]
return self.transcribe_webui_verbatim_qa(client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
condition_on_previous_text=condition_on_previous_text, fp16=fp16,
compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
def transcribe_webui_full(self, client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
initial_prompt: str, temperature: float, best_of: int, beam_size: int, patience: float, length_penalty: float, suppress_tokens: str,
condition_on_previous_text: bool, fp16: bool, temperature_increment_on_fallback: float,
compression_ratio_threshold: float, logprob_threshold: float, no_speech_threshold: float):
# Handle temperature_increment_on_fallback
if temperature_increment_on_fallback is not None:
temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
else:
temperature = [temperature]
return self.transcribe_webui(client, process,counsellor,modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow,
initial_prompt=initial_prompt, temperature=temperature, best_of=best_of, beam_size=beam_size, patience=patience, length_penalty=length_penalty, suppress_tokens=suppress_tokens,
condition_on_previous_text=condition_on_previous_text, fp16=fp16,
compression_ratio_threshold=compression_ratio_threshold, logprob_threshold=logprob_threshold, no_speech_threshold=no_speech_threshold)
def transcribe_webui(self,client, process,counsellor, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
validfields = True
fileId = str(uuid.uuid4())
try:
sources = self.__get_source(urlData, multipleFiles, microphoneData)
if languageName is None:
languageName = 'english'
#print("Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process)
log.info(languageName)
if counsellor is None or counsellor == '' or process is None or process == '':
print (" Invalid fields")
validfields = False
return "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs","There was an error while processing your input. Please retry your input."
client = 'Other' if client is None or client== '' else client
#counsellor = 'Select a counsellor from drodown' if counsellor is None or counsellor == ''else counsellor
#process = 'Select a process from dropdown' if process is None or process == '' else process
client_counsellor = "Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process
try:
selectedLanguage = languageName.lower() if len(languageName) > 0 else None
selectedModel = modelName if modelName is not None else "base"
model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)
# Result
download = []
zip_file_lookup = {}
text = ""
vtt = ""
# Write result
downloadDirectory = tempfile.mkdtemp()
source_index = 0
outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory
# Execute whisper
for source in sources:
source_prefix = ""
if (len(sources) > 1):
# Prefix (minimum 2 digits)
source_index += 1
source_prefix = str(source_index).zfill(2) + "_"
#log.info("Transcribing ", fileId+'-'+source.source_path)
#raise Exception("Ex")
hours, mins, secs = duration_detector(source.source_path)
#Log duration in DB before Transcibe line
# Transcribe
"""
result = self.transcribe_file(model, source.source_path, 'english', task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
source_download, source_text, source_vtt = self.write_result(result, filePrefix, outputDirectory)
if len(sources) > 1:
# Add new line separators
if (len(source_text) > 0):
source_text += os.linesep + os.linesep
if (len(source_vtt) > 0):
source_vtt += os.linesep + os.linesep
# Append file name to source text too
source_text = source.get_full_name() + ":" + os.linesep + source_text
source_vtt = source.get_full_name() + ":" + os.linesep + source_vtt
# Add to result
download.extend(source_download)
text += source_text
vtt += source_vtt
if (len(sources) > 1):
# Zip files support at least 260 characters, but we'll play it safe and use 200
zipFilePrefix = slugify(source_prefix + source.get_short_name(max_length=200), allow_unicode=True)
# File names in ZIP file can be longer
for source_download_file in source_download:
# Get file postfix (after last -)
filePostfix = os.path.basename(source_download_file).split("-")[-1]
zip_file_name = zipFilePrefix + "-" + filePostfix
zip_file_lookup[source_download_file] = zip_file_name
log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
"""
#openai whisper
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
response = None
try:
with open(source.source_path,"rb") as file:
file_content = file.read()
payload = {
"name": os.path.basename(source.source_path),
# "response_format": "json",
"prompt": "transcribe this Chapter",
"language": 'en',
"model": model_name
}
print("payload", payload)
files = {
"file": (os.path.basename(source.source_path), file_content, "audio/mp3")
}
response = requests.post(url, headers=headers, data=payload, files=files)
log.info(response.json())
except Exception:
log.info(response)
log.info("Error occurred while reading openai response")
print(traceback.format_exc())
return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
"""
#azure whisper
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
response = None
try:
with open(source.source_path,"rb") as file:
response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
headers=HEADERS,
files={'file': file})
log.info(response.json())
except Exception:
log.info(response)
log.info("Error occurred while reading openai response")
print(traceback.format_exc())
return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
"""
text = '',
if "text" in response.json():
text = response.json()["text"]
output_files = []
output_files.append(self.__create_file(text, outputDirectory,fileId + "-transcript.txt"));
bucket = 'acengage-bucket-v09kjo18oktg'
try:
for f in output_files:
print('source_text..', os.path.abspath(f))
s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
except:
print("Error while writing to s3, proceed")
else:
text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
return client_counsellor,text
finally:
# Cleanup source
if self.deleteUploadedFiles and validfields:
for source in sources:
print("Deleting source file " + source.source_path)
try:
bucket = 'acengage-bucket-v09kjo18oktg'
key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
file_url = "https://"+bucket+".s3.amazonaws.com/"+key
#Log duration in DB before Transcibe line
try:
doc = {
'client': client,
'counsellor': counsellor,
'process': process,
'language':languageName,
'file': os.path.basename(source.source_path),
'hours': hours,
'mins': mins,
'secs': secs,
'request_time': datetime.datetime.now(),
'audio_url':file_url
}
#res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
#logger.info(json.dumps(res, indent=4))
data_string = json.dumps(doc, indent=2, default=str)
key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
except Exception:
print ("Error occurred while inserting duration data")
print(traceback.format_exc())
os.remove(source.source_path)
except Exception as e:
# Ignore error - it's just a cleanup
print("Error deleting source file " + source.source_path + ": " + str(e))
except ExceededMaximumDuration as e:
return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s")
except Exception as ex:
print(traceback.format_exc())
#return client_counsellor, [],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
return client_counsellor,"There was an error while processing your input. Please retry your input."
def transcribe_webui_verbatim(self,client, process,counsellor, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
validfields = True
fileId = str(uuid.uuid4())
try:
sources = self.__get_source(urlData, multipleFiles, microphoneData)
if languageName is None:
languageName = 'english'
#print("Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process)
#log.info("Language Chosen: "+ languageName)
if counsellor is None or counsellor == '' or process is None or process == '':
print (" Invalid fields")
validfields = False
return "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs",[],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
client = 'Other' if client is None or client== '' else client
#counsellor = 'Select a counsellor from drodown' if counsellor is None or counsellor == ''else counsellor
#process = 'Select a process from dropdown' if process is None or process == '' else process
client_counsellor = "Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process
try:
selectedLanguage = languageName.lower() if len(languageName) > 0 else None
selectedModel = modelName if modelName is not None else "base"
model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)
# Result
download = []
zip_file_lookup = {}
text = ""
vtt = ""
# Write result
downloadDirectory = tempfile.mkdtemp()
source_index = 0
outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory
# Execute whisper
for source in sources:
source_prefix = ""
if (len(sources) > 1):
# Prefix (minimum 2 digits)
source_index += 1
source_prefix = str(source_index).zfill(2) + "_"
#log.info("Transcribing ", fileId+'-'+source.source_path)
#raise Exception("Ex")
hours, mins, secs = duration_detector(source.source_path)
#Log duration in DB before Transcibe line
# Transcribe
"""
result = self.transcribe_file(model, source.source_path, 'english', task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
source_download, source_text, source_vtt = self.write_result(result, filePrefix, outputDirectory)
if len(sources) > 1:
# Add new line separators
if (len(source_text) > 0):
source_text += os.linesep + os.linesep
if (len(source_vtt) > 0):
source_vtt += os.linesep + os.linesep
# Append file name to source text too
source_text = source.get_full_name() + ":" + os.linesep + source_text
source_vtt = source.get_full_name() + ":" + os.linesep + source_vtt
# Add to result
download.extend(source_download)
text += source_text
vtt += source_vtt
if (len(sources) > 1):
# Zip files support at least 260 characters, but we'll play it safe and use 200
zipFilePrefix = slugify(source_prefix + source.get_short_name(max_length=200), allow_unicode=True)
# File names in ZIP file can be longer
for source_download_file in source_download:
# Get file postfix (after last -)
filePostfix = os.path.basename(source_download_file).split("-")[-1]
zip_file_name = zipFilePrefix + "-" + filePostfix
zip_file_lookup[source_download_file] = zip_file_name
log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
"""
#openai whisper
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
response = None
try:
with open(source.source_path,"rb") as file:
file_content = file.read()
payload = {
"name": os.path.basename(source.source_path),
# "response_format": "json",
"prompt": "transcribe this Chapter",
"language": 'en',
"model": model_name
}
print("payload", payload)
files = {
"file": (os.path.basename(source.source_path), file_content, "audio/mp3")
}
response = requests.post(url, headers=headers, data=payload, files=files)
log.info(response.json())
except Exception:
log.info(response)
log.info("Error occurred while reading openai response")
print(traceback.format_exc())
return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
"""
#azure whisper
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
response = None
try:
with open(source.source_path,"rb") as file:
response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
headers=HEADERS,
files={'file': file})
log.info(response.json())
except Exception:
log.info(response)
log.info("Error occurred while reading openai response")
print(traceback.format_exc())
return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
"""
text = ''
verbatimAzure = ''
if "text" in response.json():
text = response.json()["text"]
output_files = []
output_files.append(self.__create_file(text, outputDirectory, filePrefix + "-transcript.txt"));
#openai.api_type = "azure"
#openai.api_base = "https://pragyaaai.openai.azure.com/"
#openai.api_version = "2023-03-15-preview"
#openai.api_key = "9ba4e0dcfbf841fbb946c55c52caae1b"
#openai.api_key = OPENAI_API_KEY
api_base = 'https://pragyaagpt4.openai.azure.com/'
api_key="9fb5af1332a648b1bba4198731e389bd"
deployment_name = 'pragyaagpt4turbo'
api_version = '2023-12-01-preview' # this might change in the future
azureClient = AzureOpenAI(
api_key=api_key,
api_version=api_version,
base_url=f"{api_base}openai/deployments/{deployment_name}/",
)
prompt="Create a detailed summary in just one paragraph, in first person, as if the employees is himself/ herself speaking .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. Describe only the main or primary reason of leaving the organisation in detail and skip any other reasons mentioned. Mention all negative sentiments on manager or organisation such as manager's rude behavior, read flags , was the employee happy or unhappy at the organization, remove rating information of managers if available. Manager's rude behavior and words used to be captured as it is and in the same language instead of translating them to English.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 name in the summary. Mentioned notice period if it is mentioned. \n Example outputs: \n I worked in my last organization for 1 year and 11 months as a software engineer in the Retirement Income Solutions Department. My immediate reporting manager was Praveen Kumar Kandy, who was a Principal at Global Services. My tenure there was marked by significant dissatisfaction due to the treatment I received from Praveen. He was biased and not encouraging enough. He consistently made me feel like a lesser part of the team by calling out in meetings that ‘they are contractors, we should not include them’ and excluding me from activities, even going as far as to insult me on calls. This behavior was not only demeaning but also affected my motivation and sense of belonging. Despite completing tasks assigned to others and working overtime, my efforts were never acknowledged, and I never received recognition for my work. I was often expected to take on additional tasks without acknowledgment, working up to 2 AM to complete others' work that went uncredited. He used to be biased towards his team asking them to work from home but would force me to go office to complete the work. The lack of growth opportunities and the fact that my designation did not change despite having the highest rating in my team contributed to my decision to leave. Ultimately, I left the organization because I could no longer tolerate the disrespect and bias from Praveen and the lack of recognition for my contributions .\n I worked in my last organization for around 5 months as a Senior Associate in the Microsoft Dynamics team based in Mumbai. My reporting manager was Mrinmay Paul, an Associate Director. I held a pivotal role where I managed both functional and technical aspects for a client based in Wadala. Due to the absence of any other team members from PwC, I essentially served as the sole point of contact for the client. Overall, my experience with the company was positive. However, the major drawback that led to my decision to leave was the severe lack of work-life balance, primarily due to extensive traveling requirements. Commuting from my residence in Thane to the client's location in Wadala took approximately 2 and a half hours one way, resulting in a total of nearly 5 hours of travel time per day. This consistent travel took a toll on my health, leading to issues such as back pain, lethargy, and a general lack of energy, exacerbated by the crowded conditions during office hours. Despite having a branch of the company conveniently located in Thane, just 15-20 minutes away from my residence, I was specifically assigned to the project requiring my presence at the client location. Despite voicing my concerns to my manager, the project commitment remained unchanged, with promises of potential project changes only after its completion. However, having firsthand knowledge of the project's status and anticipated extensions beyond the communicated deadline of May 2024, I felt compelled to make the decision to resign. Feeling the strain of daily travel demands since October or the first week of November 2023, I found myself unable to dedicate time to my family or maintain a manageable work-life balance. My workdays typically extended from 8 am to 9:30 pm, leaving little room for personal time or relaxation. Consequently, I submitted my resignation on the 27th of November 2023, despite efforts from my manager to retain me by offering a potential project change. Choosing to prioritize my health and well-being, I served a three-month notice period before transitioning to my current role as a Technical Lead at TCS, where I received a notable 25% salary increase. \n I worked with the organization for three years as an Associate in the Transfer Pricing department in Bengaluru. I reported to multiple managers simultaneously, including Sai Vignesh (Manager), Ajay Ruia (Manager), Harsh Pasari (Manager), Rahul Sharma (a Director), Jain Pravo (Manager), Shilpa Jain (Manager) and Upendra Tiwari (Director). While there were aspects of my role that I found fulfilling, the challenges of maintaining a healthy work-life balance became increasingly daunting. The crux of the issue lay in the disjointed nature of my responsibilities. Reporting to multiple managers meant juggling a myriad of deadlines, each with its own set of priorities. Despite my best efforts to manage these conflicting demands, the lack of cohesion among the managerial team posed a significant challenge. My typical workday was a whirlwind of activity, often beginning with early morning calls around 7 or 8 AM, sometimes even before I reached the office. Throughout the day, there was little respite as tasks piled up and client demands took precedence over everything else. Lunch breaks became a luxury I could scarcely afford, with interruptions from urgent calls and pending work being the norm rather than the exception. As the day wore on, the workload only seemed to intensify, stretching well into the late hours of the evening. Even after leaving the office, the demands of the job followed me home, necessitating late-night logins to wrap up pending tasks. Weekends offered little relief, as work commitments encroached on what little personal time I had left. Despite my efforts to address these concerns with my immediate manager and even escalate them to senior leadership within the company, the lack of tangible solutions or support left me feeling overwhelmed. Ultimately, it was the relentless pressure and the toll it took on my health that prompted me to make the difficult decision to part ways with the organization. The mounting workload became increasingly overwhelming, exacerbated by the constant stream of tasks from multiple managers. Although there were brief respites when it seemed like the workload was easing, they were always short-lived. A significant factor contributing to this strain was the high turnover rate within the company. As colleagues left and new ones joined, the distribution of responsibilities became erratic. Whenever someone departed, their workload inevitably shifted to the remaining team members, compounding our already heavy burden. To address these challenges, I reached out to key figures within the company, including Madhavi Rathi (Partner), Eric Mehta (India Lead), and Saumitra Chakraborty (Managing Director), hoping for a resolution. While they expressed sympathy and temporarily lightened my load by redistributing clients and projects, the relief was fleeting. The workload quickly piled up again with new urgent tasks pouring in. Despite attempts to streamline my workload by reducing the number of managers I reported to directly, the issue persisted. Balancing accounts and projects across different managers made organization and prioritization incredibly difficult. It felt as though my workload was beyond my control, with each manager harbouring their own set of expectations, often oblivious to the demands placed by others. The lack of coordination and communication among managers further compounded the stress. Consequently, I frequently found myself working late into the night, sometimes until 11 p.m., just to stay afloat. Maintaining a healthy work-life balance became increasingly elusive, taking a toll on my concentration and overall performance. The perpetual cycle of juggling urgent tasks from multiple managers eventually eroded the quality of my work. Each manager asserted the urgency of their tasks, leaving me feeling overwhelmed and unable to establish boundaries. Despite my efforts to manage the workload, the relentless pressure to prioritize client needs created an environment where respite seemed unattainable. While seasonal spikes in workload were anticipated, the year-round barrage of demands became unsustainable. This became glaringly evident when my mother fell ill, adding another layer of stress to an already precarious situation. As my personal life collided with professional demands, my health began to suffer, leading to a decline in my ability to cope. By mid-2023, the strain became too much to bear. Even the simplest tasks felt insurmountable, and I found myself needing frequent breaks to collect my thoughts. It was clear that the erratic work schedule was taking a significant toll on my well-being, both mentally and physically. In November, I made the difficult decision to resign. Despite the offers of a sabbatical from Prajwala Pai (Partner) and Apurva Bakshi (HR), I felt that a clean break was necessary to prioritize my health. While Prajwala's efforts to retain me were genuine, and her one-on-one conversation with me was appreciated, I ultimately did not feel ready to accept the proposed solutions. I served a notice period of 3 months. I am currently not working anywhere else and am focusing on my health."
if process=='CE':
prompt = "Create a detailed summary in just one paragraph, in second person , as someone else is speaking on behalf of employee. Specify last working day of the candidate. Specify if the candidate has accepted the offer or not, current organisation, date of joining in the new organisation, all reasons for leaving the organisation,counter offer details like offered CTC, designation and counter company name. For offers declined, specify details similar to candidates joining. Include counter offer details as applicable , if any.\n ###Example of good output### \n - '1.FIRST CALL DECLINE- The candidate declined the offer of Siemens a month back and joined Amazon on the 6th of November. She said that Amazon had matched her expectations in terms of compensation. Siemens had given her 30 LPA. She was expecting around 35 LPA. During the interview also had a discussion regarding the same, but it was informed to her that the budget was around 30 LPA to 31 LPA. She had accepted the offer of Siemens. She was giving an interview for Amazon parallelly but received the offer from Amazon way after Siemens's offer. The joining date of Siemens was also in the month of November. She was initially in touch with HR Manisha and HR did call her, but she couldn't answer the call as she was in the meeting. When she tried to connect with HR Manisha, she got to know that HR had already left the organization. She tried to connect with other HR but did not receive any response. She had sent a couple of emails to Siemens regarding the counteroffer but did not receive any response. Then she decided to decline the offer. She was happy with the role and designation offered by Siemens. She was also fine with the location and hybrid work mode. The candidate also mentioned that the role offered by Amazon is similar to the role offered by Siemens. She was previously working for Bosch and the last working day was on the 30th of October. She was happy with the recruitment process. RF was captured. The highlights and benefits of the company were shared."
try:
"""
result = openai.ChatCompletion.create(
# engine="gpt35turbo",
model="gpt-4-1106-preview",
messages=[{"role":"system","content":prompt},
{"role": "user","content":text}],
temperature=0.7,
max_tokens=800,
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
stop=None)
"""
result = azureClient.chat.completions.create(
model=deployment_name,
messages=[{"role":"system","content":prompt},
{"role": "user","content":text}],
temperature=0.7,
max_tokens=2000,
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
stop=None
)
print("verbatimAzure", result)
for choice in result.choices:
verbatimAzure += choice.message.content
except:
print("Error while generating verbatim")
traceback.print_exc()
verbatimAzure = "Some problem encountered while generating verbatim. The length of transcript could be big or it is taking longer time to process"
output_files = []
output_files.append(self.__create_file(text, outputDirectory, fileId + "-transcript.txt"));
output_files.append(self.__create_file(verbatimAzure, outputDirectory, fileId + "-verbatim.txt"));
bucket = 'acengage-bucket-v09kjo18oktg'
try:
for f in output_files:
print('source_text..', os.path.abspath(f))
s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
except:
print("Error while writing to s3, proceed")
else:
text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
return client_counsellor,text,verbatimAzure
finally:
# Cleanup source
if self.deleteUploadedFiles and validfields:
for source in sources:
print("Deleting source file " + source.source_path)
try:
bucket = 'acengage-bucket-v09kjo18oktg'
key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
file_url = "https://"+bucket+".s3.amazonaws.com/"+key
#Log duration in DB before Transcibe line
try:
doc = {
'client': client,
'counsellor': counsellor,
'process': process,
'language':languageName,
'verbatim':'yes',
'file': os.path.basename(source.source_path),
'hours': hours,
'mins': mins,
'secs': secs,
'request_time': datetime.datetime.now(),
'audio_url':file_url
}
#res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
#logger.info(json.dumps(res, indent=4))
data_string = json.dumps(doc, indent=2, default=str)
key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
except Exception:
print ("Error occurred while inserting duration data")
print(traceback.format_exc())
os.remove(source.source_path)
except Exception as e:
# Ignore error - it's just a cleanup
print("Error deleting source file " + source.source_path + ": " + str(e))
except ExceededMaximumDuration as e:
return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s"), "[ERROR]"
except Exception as ex:
print(traceback.format_exc())
#return client_counsellor, [],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
def transcribe_webui_verbatim_qa(self,client, process,counsellor, modelName, languageName, urlData, multipleFiles, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions: dict):
validfields = True
fileId = str(uuid.uuid4())
try:
sources = self.__get_source(urlData, multipleFiles, microphoneData)
if languageName is None:
languageName = 'english'
if counsellor is None or counsellor == '' or process is None or process == '':
print (" Invalid fields")
validfields = False
return "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs",[],"There was an error while processing your input. Please retry your input.",("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
client = 'Other' if client is None or client== '' else client
client_counsellor = "Client:"+client+" , "+"Counsellor:"+counsellor+" , "+"Process:"+process
try:
selectedLanguage = languageName.lower() if len(languageName) > 0 else None
selectedModel = modelName if modelName is not None else "base"
model = WhisperContainer(model_name=selectedModel, cache=self.model_cache)
# Result
download = []
zip_file_lookup = {}
text = ""
vtt = ""
# Write result
downloadDirectory = tempfile.mkdtemp()
source_index = 0
outputDirectory = self.output_dir if self.output_dir is not None else downloadDirectory
# Execute whisper
for source in sources:
source_prefix = ""
if (len(sources) > 1):
# Prefix (minimum 2 digits)
source_index += 1
source_prefix = str(source_index).zfill(2) + "_"
#log.info("Transcribing ", fileId+'-'+source.source_path)
#raise Exception("Ex")
hours, mins, secs = duration_detector(source.source_path)
#Log duration in DB before Transcibe line
# Transcribe
log.info("Source file:"+fileId+'-'+os.path.basename(source.source_path))
# result = self.transcribe_file(model, source.source_path, selectedLanguage, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow, **decodeOptions)
#openai whisper
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
response = None
try:
with open(source.source_path,"rb") as file:
file_content = file.read()
payload = {
"name": os.path.basename(source.source_path),
# "response_format": "json",
"prompt": "transcribe this Chapter",
"language": 'en',
"model": model_name
}
print("payload", payload)
files = {
"file": (os.path.basename(source.source_path), file_content, "audio/mp3")
}
response = requests.post(url, headers=headers, data=payload, files=files)
log.info(response.json())
except Exception:
log.info(response)
log.info("Error occurred while reading openai response")
print(traceback.format_exc())
return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
"""
#azure whisper
filePrefix = slugify(source_prefix + source.get_short_name(), allow_unicode=True)
response = None
try:
with open(source.source_path,"rb") as file:
response = requests.post(f'{AZURE_OPENAI_ENDPOINT}/openai/deployments/{MODEL_NAME}/audio/transcriptions?api-version=2023-09-01-preview',
headers=HEADERS,
files={'file': file})
log.info(response.json())
except Exception:
log.info(response)
log.info("Error occurred while reading openai response")
print(traceback.format_exc())
return client_counsellor,'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
"""
text = '',
qaResult1 = ''
qaResult2 = ''
qaResult3 = ''
qaResult4 = ''
if "text" in response.json():
text = response.json()["text"]
#openai.api_key = "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"
# openai.api_key = "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"
api_base = 'https://pragyaagpt4.openai.azure.com/'
api_key="9fb5af1332a648b1bba4198731e389bd"
deployment_name = 'pragyaagpt4turbo'
api_version = '2023-12-01-preview' # this might change in the future
azureClient = AzureOpenAI(
api_key=api_key,
api_version=api_version,
base_url=f"{api_base}openai/deployments/{deployment_name}/",
)
qaResult1 = azureClient.chat.completions.create(
model=deployment_name,
messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list. provide the answers in first person as if employee is answering.\n1.What triggered your decision to leave? \n2.Who spoke to you after you resigned? \n3.In your opinion did they make a genuine effort to retain you? \n4.What could the organization have done to retain you? "},
{"role": "user","content":text}],
temperature= 0.05,
max_tokens=2000,
top_p= 1,
frequency_penalty= 0,
presence_penalty= 0,
stop=None
)
#log.info("result 1",qaResult1)
qaResult1 = qaResult1.choices[0].message.content
qaResult2 = azureClient.chat.completions.create(
model=deployment_name,
messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list. provide the answers in first person as if employee is answering. \n1.Role clarity- Were you given clarity about your role before you joined? If less than 7, why? \n2.On-boarding process- Did your on-boarding process go on smoothly and on time? If less than 7, why? \n3.Time taken for the recruitment process- Was the overall interview organized and quick? If less than 7, why? If less than 7, why? \n4.Hand-holding- Were you given the required support, guidance and knowledge transfer for your new role? If less than 7 ,why?\n5.JD and current role match- Does your current role match the JD that was provided to you at the time of joining? If less than 7, why? \n6.What was done well during the overall recruitment process? \n7.What could have been done better during the overall recruitment process? "}, {"role": "user","content":text}],
temperature= 0.05,
max_tokens=256,
top_p= 1,
frequency_penalty= 0,
presence_penalty= 0,
stop=None
)
#log.info("result 2",qaResult2)
#log.info(qaResult2['choices'][0]['message']['content'])
qaResult2 = qaResult2.choices[0].message.content
qaResult3 = azureClient.chat.completions.create(
model=deployment_name,
messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list. follow the instructions provided at the end of last question \n1.What is your supervisor's name? \n2.What is your supervisor's designation? \n3.Subject knowledge - Do you believe your manager was competent to be able to deal with the issues you and your team mates have during your workday? If less than 7, why? \n4.Team management- How effectively did your manager work with the resources provided to him/her to get the task at hand completed? If less than 7, why? \n5.Being unbiased- Did your Manager give fair opportunities to everyone in the team? If less than 7, why? \n6.Offering growth opportunities- Did you Manager encourage growth and allow you to explore new tasks? \n7.Providing feedback - Was the feedback provided by the manager to you fair and clear which outlined a clear way for you to grow as an individual? If less than 7, why? \n8.Given a chance would you like to work with your current manager in the future? \n9.Senior leadership - opportunity to interact and visibility . If less than 7, why? \n10.Role satisfaction - having a sense of direction with what you do and having the required tools/ resources to do this. If less than 7, why? \n11.Rewards and Recognition- being rewarded and recognized adequately for hard work and effort.If less than 7, why? \n12.Performance Management System(includes Growth Opportunities)- level of transparency in the appraisal and promotion process. \n13.Work-Life Balance- being able maintain a healthy balance between work life and personal life?If less than 7, why? \n###Instrutions### \nprovide the answers in first person as if employee is answering. format the answers in readable way. Please follow few instructions in instructions section befoew questions .\nInstructions: In case Name and Designation asked, provide the anaswer as in the example below .\n Example of Answer: Supervisors name: Bishwajit Samanth \n Designation: Director . In case employee is giving a rating and comments, proviem them as in example. \nExample of answer: Ratings: 2/10 , Comments: There was minimal interaction with the junior resources and he wasn't even aware of what the other team members were doing."}, {"role": "user","content":text}],
temperature= 0.05,
max_tokens=256,
top_p= 1,
frequency_penalty= 0,
presence_penalty= 0,
stop=None
)
#log.info("result 3",qaResult3)
#log.info(qaResult3['choices'][0]['message']['content'])
qaResult3 = qaResult3.choices[0].message.content
qaResult4 = azureClient.chat.completions.create(
model=deployment_name,
messages=[{"role": "system","content":"basis the call transcript, provide answers for questions below in numbered list. provide the answers in first person as if employee is answering. \n1.How likely are you to recommend the organization to you friends and family to work in on a scale of 0-10 (0 being the lowest)? \n2.eNPS Comments \n3.What is the one thing you liked the most about the organization? \n4.Would you be willing to re-join? \n5.Where are you working now? \n6.Did you join the new company in the same industry as you were working for in the previous company? \n7.What is your current designation? \n8.How much of a hike have you received? "}, {"role": "user","content":text}],
temperature= 0.05,
max_tokens=256,
top_p= 1,
frequency_penalty= 0,
presence_penalty= 0,
stop=None
)
#log.info("result 4",qaResult4)
#log.info(qaResult4['choices'][0]['message']['content'])
qaResult4 = qaResult4.choices[0].message.content
output_files = []
output_files.append(self.__create_file(text, outputDirectory, fileId + "-transcript.txt"));
bucket = 'acengage-bucket-v09kjo18oktg'
try:
for f in output_files:
print('source_text..', os.path.abspath(f))
s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
except:
print("Error while writing to s3, proceed")
else:
text = 'Verbatim file size is bigger than size limit. Please record the verbatim in two parts'
return client_counsellor,text,qaResult1,qaResult2,qaResult3,qaResult4
finally:
# Cleanup source
if self.deleteUploadedFiles and validfields:
for source in sources:
print("Deleting source file " + source.source_path)
try:
bucket = 'acengage-bucket-v09kjo18oktg'
key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.basename(source.source_path)
s3.meta.client.upload_file(Filename=source.source_path, Bucket='acengage-bucket-v09kjo18oktg', Key=key)
file_url = "https://"+bucket+".s3.amazonaws.com/"+key
#Log duration in DB before Transcibe line
try:
doc = {
'client': client,
'counsellor': counsellor,
'process': process,
'language':languageName,
'verbatim_with_qa':'yes',
'file': os.path.basename(source.source_path),
'hours': hours,
'mins': mins,
'secs': secs,
'request_time': datetime.datetime.now(),
'audio_url':file_url
}
#res = es.index(index=acengage_index,body=doc,id= fileId+'-'+os.path.basename(source.source_path))
#logger.info(json.dumps(res, indent=4))
data_string = json.dumps(doc, indent=2, default=str)
key = str(datetime.date.today())+'/audio/'+fileId+'-'+os.path.splitext(os.path.basename(source.source_path))[0]+".json"
s3.meta.client.put_object(Bucket='acengage-bucket-v09kjo18oktg', Key=key, Body=data_string)
except Exception:
print ("Error occurred while inserting duration data")
print(traceback.format_exc())
os.remove(source.source_path)
except Exception as e:
# Ignore error - it's just a cleanup
print("Error deleting source file " + source.source_path + ": " + str(e))
except ExceededMaximumDuration as e:
return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s"), "[ERROR]"
except Exception as ex:
print(traceback.format_exc())
#return client_counsellor, [],("There was an error while processing your input. Please retry your input."), "There was an error while processing your input. Please retry your input."
def transcribe_file(self, model: WhisperContainer, audio_path: str, language: str, task: str = None, vad: str = None,
vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1, **decodeOptions: dict):
initial_prompt = decodeOptions.pop('initial_prompt', None)
if ('task' in decodeOptions):
task = decodeOptions.pop('task')
# Callable for processing an audio file
whisperCallable = model.create_callback(language, task, initial_prompt, **decodeOptions)
# The results
if (vad == 'silero-vad'):
# Silero VAD where non-speech gaps are transcribed
process_gaps = self._create_silero_config(NonSpeechStrategy.CREATE_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
result = self.process_vad(audio_path, whisperCallable, self.vad_model, process_gaps)
elif (vad == 'silero-vad-skip-gaps'):
# Silero VAD where non-speech gaps are simply ignored
skip_gaps = self._create_silero_config(NonSpeechStrategy.SKIP, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
result = self.process_vad(audio_path, whisperCallable, self.vad_model, skip_gaps)
elif (vad == 'silero-vad-expand-into-gaps'):
# Use Silero VAD where speech-segments are expanded into non-speech gaps
expand_gaps = self._create_silero_config(NonSpeechStrategy.EXPAND_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
result = self.process_vad(audio_path, whisperCallable, self.vad_model, expand_gaps)
elif (vad == 'periodic-vad'):
# Very simple VAD - mark every 5 minutes as speech. This makes it less likely that Whisper enters an infinite loop, but
# it may create a break in the middle of a sentence, causing some artifacts.
periodic_vad = VadPeriodicTranscription()
period_config = PeriodicTranscriptionConfig(periodic_duration=vadMaxMergeSize, max_prompt_window=vadPromptWindow)
result = self.process_vad(audio_path, whisperCallable, periodic_vad, period_config)
else:
if (self._has_parallel_devices()):
# Use a simple period transcription instead, as we need to use the parallel context
periodic_vad = VadPeriodicTranscription()
period_config = PeriodicTranscriptionConfig(periodic_duration=math.inf, max_prompt_window=1)
result = self.process_vad(audio_path, whisperCallable, periodic_vad, period_config)
else:
# Default VAD
result = whisperCallable.invoke(audio_path, 0, None, None)
return result
def process_vad(self, audio_path, whisperCallable, vadModel: AbstractTranscription, vadConfig: TranscriptionConfig):
if (not self._has_parallel_devices()):
# No parallel devices, so just run the VAD and Whisper in sequence
return vadModel.transcribe(audio_path, whisperCallable, vadConfig)
gpu_devices = self.parallel_device_list
if (gpu_devices is None or len(gpu_devices) == 0):
# No GPU devices specified, pass the current environment variable to the first GPU process. This may be NULL.
gpu_devices = [os.environ.get("CUDA_VISIBLE_DEVICES", None)]
# Create parallel context if needed
if (self.gpu_parallel_context is None):
# Create a context wih processes and automatically clear the pool after 1 hour of inactivity
self.gpu_parallel_context = ParallelContext(num_processes=len(gpu_devices), auto_cleanup_timeout_seconds=self.vad_process_timeout)
# We also need a CPU context for the VAD
if (self.cpu_parallel_context is None):
self.cpu_parallel_context = ParallelContext(num_processes=self.vad_cpu_cores, auto_cleanup_timeout_seconds=self.vad_process_timeout)
parallel_vad = ParallelTranscription()
return parallel_vad.transcribe_parallel(transcription=vadModel, audio=audio_path, whisperCallable=whisperCallable,
config=vadConfig, cpu_device_count=self.vad_cpu_cores, gpu_devices=gpu_devices,
cpu_parallel_context=self.cpu_parallel_context, gpu_parallel_context=self.gpu_parallel_context)
def _has_parallel_devices(self):
return (self.parallel_device_list is not None and len(self.parallel_device_list) > 0) or self.vad_cpu_cores > 1
def _concat_prompt(self, prompt1, prompt2):
if (prompt1 is None):
return prompt2
elif (prompt2 is None):
return prompt1
else:
return prompt1 + " " + prompt2
def _create_silero_config(self, non_speech_strategy: NonSpeechStrategy, vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1):
# Use Silero VAD
if (self.vad_model is None):
self.vad_model = VadSileroTranscription()
config = TranscriptionConfig(non_speech_strategy = non_speech_strategy,
max_silent_period=vadMergeWindow, max_merge_size=vadMaxMergeSize,
segment_padding_left=vadPadding, segment_padding_right=vadPadding,
max_prompt_window=vadPromptWindow)
return config
def write_result(self, result: dict, source_name: str, output_dir: str):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
text = result["text"]
language = result["language"]
languageMaxLineWidth = self.__get_max_line_width(language)
print("Max line width " + str(languageMaxLineWidth))
vtt = self.__get_subs(result["segments"], "vtt", languageMaxLineWidth)
srt = self.__get_subs(result["segments"], "srt", languageMaxLineWidth)
output_files = []
output_files.append(self.__create_file(srt, output_dir, source_name + "-subs.srt"));
output_files.append(self.__create_file(vtt, output_dir, source_name + "-subs.vtt"));
output_files.append(self.__create_file(text, output_dir, source_name + "-transcript.txt"));
dest = '/content/drive/MyDrive/aceNgage_transcripts/'
# try:
# if not os.path.exists(os.path.dirname(dest)):
# os.makedirs(os.path.dirname(dest))
# except OSError as err:
# print(err)
# for f in output_files:
# print('source_text..', os.path.abspath(f))
# shutil.copy(os.path.abspath(f),dest)
bucket = 'acengage-bucket-v09kjo18oktg'
try:
for f in output_files:
print('source_text..', os.path.abspath(f))
s3.meta.client.upload_file(Filename=os.path.abspath(f), Bucket=bucket, Key=str(datetime.date.today())+'/transcripts/'+os.path.basename(f))
except:
print("Error while writing to s3, proceed")
return output_files, text, vtt
def clear_cache(self):
self.model_cache.clear()
self.vad_model = None
def __get_source(self, urlData, multipleFiles, microphoneData):
return get_audio_source_collection(urlData, multipleFiles, microphoneData, self.inputAudioMaxDuration)
def __get_max_line_width(self, language: str) -> int:
if (language and language.lower() in ["japanese", "ja", "chinese", "zh"]):
# Chinese characters and kana are wider, so limit line length to 40 characters
return 40
else:
# TODO: Add more languages
# 80 latin characters should fit on a 1080p/720p screen
return 80
def __get_subs(self, segments: Iterator[dict], format: str, maxLineWidth: int) -> str:
segmentStream = StringIO()
if format == 'vtt':
write_vtt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
elif format == 'srt':
write_srt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
else:
raise Exception("Unknown format " + format)
segmentStream.seek(0)
return segmentStream.read()
def __create_file(self, text: str, directory: str, fileName: str) -> str:
# Write the text to a file
with open(os.path.join(directory, fileName), 'w+', encoding="utf-8") as file:
file.write(text)
return file.name
def close(self):
print("Closing parallel contexts")
self.clear_cache()
if (self.gpu_parallel_context is not None):
self.gpu_parallel_context.close()
if (self.cpu_parallel_context is not None):
self.cpu_parallel_context.close()
def create_ui(input_audio_max_duration, share=False, server_name: str = None, server_port: int = 7860,
default_model_name: str = "medium", default_vad: str = None, vad_parallel_devices: str = None,
vad_process_timeout: float = None, vad_cpu_cores: int = 1, auto_parallel: bool = False,
output_dir: str = None):
ui = WhisperTranscriber(input_audio_max_duration, vad_process_timeout, vad_cpu_cores, DELETE_UPLOADED_FILES, output_dir)
# Specify a list of devices to use for parallel processing
ui.set_parallel_devices(vad_parallel_devices)
ui.set_auto_parallel(auto_parallel)
ui_description = "Select mandatory fields of Counsellor and Process (marked *) from dropdowns before pressing Submit. Output will be processed only with these Inputs "
#ui_description += " audio and is also a multi-task model that can perform multilingual speech recognition "
#ui_description += " as well as speech translation and language identification. "
#ui_description += "\n\n\n\nFor longer audio files (>10 minutes) not in English, it is recommended that you select Silero VAD (Voice Activity Detector) in the VAD option."
#if input_audio_max_duration > 0:
# ui_description += "\n\n" + "Max audio file length: " + str(input_audio_max_duration) + " s"
#ui_article = "Read the [documentation here](https://gitlab.com/aadnk/whisper-webui/-/blob/main/docs/options.md)"
import requests
results = []
def getAudios(agent, dest,fromDate, toDate):
url_out = 'https://api-smartflo.tatateleservices.com/v1/call/records?direction=outbound&limit=100'
p = {
"from_date":str(fromDate),
"to_date":str(toDate),
"agents":str(agent),
"destination":str(dest)
}
try:
resp = requests.get(url_out, params=p,
headers={'Content-Type':'application/json',
'Authorization': 'Bearer {}'.
format('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0NTM5MDkiLCJpc3MiOiJodHRwczovL2Nsb3VkcGhvbmUudGF0YXRlbGVzZXJ2aWNlcy5jb20vdG9rZW4vZ2VuZXJhdGUiLCJpYXQiOjE3MTIzMjExNjIsImV4cCI6MjAxMjMyMTE2MiwibmJmIjoxNzEyMzIxMTYyLCJqdGkiOiJlbDRvdUp2dFBtWHA4aEtJIn0.-8kK2HDqp84lE7Qz7RUhqhTGn38XYMc87_NZb9DCGbQ')})
data = resp.json()
results = []
# Now you can access Json
for i in data['results']:
client_number = str(i['client_number']) if i['client_number'] is not None else ''
call_duration = str(i['call_duration']) if i['call_duration'] is not None else ''
end_stamp = str(i['end_stamp']) if i['end_stamp'] is not None else ''
agent_id=str(agent)
#if len(i["call_flow"])>1:
# agent_id = i["call_flow"][1]["id"]
call_type='Outbound'
recording_url = [client_number,call_duration,agent_id, call_type,end_stamp,i['recording_url']]
results.append(recording_url)
url_in = 'https://api-smartflo.tatateleservices.com/v1/call/records?direction=inbound&limit=100'
p = {
"from_date":str(fromDate),
"to_date":str(toDate),
"agents":str(agent),
"destination":str(dest)
}
resp = requests.get(url_in, params=p,
headers={'Content-Type':'application/json',
'Authorization': 'Bearer {}'.
format('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0NTM5MDkiLCJpc3MiOiJodHRwczovL2Nsb3VkcGhvbmUudGF0YXRlbGVzZXJ2aWNlcy5jb20vdG9rZW4vZ2VuZXJhdGUiLCJpYXQiOjE3MTIzMjExNjIsImV4cCI6MjAxMjMyMTE2MiwibmJmIjoxNzEyMzIxMTYyLCJqdGkiOiJlbDRvdUp2dFBtWHA4aEtJIn0.-8kK2HDqp84lE7Qz7RUhqhTGn38XYMc87_NZb9DCGbQ')})
data = resp.json()
# Now you can access Json
for i in data['results']:
client_number = str(i['client_number']) if i['client_number'] is not None else ''
call_duration = str(i['call_duration']) if i['call_duration'] is not None else ''
end_stamp = str(i['end_stamp']) if i['end_stamp'] is not None else ''
agent_id=str(agent)
#if len(i["call_flow"])>1:
# agent_id = i["call_flow"][1]["id"]
call_type = 'Inbound'
recording_url = [client_number,call_duration,agent_id, call_type,end_stamp,i['recording_url']]
results.append(recording_url)
return results
except:
raise gr.Error("There is an error in getting urls/audio from Tata Tele apis. Please validate inputs.")
io1 = gr.Interface(
fn=getAudios,
inputs=[gr.Textbox(label="Agent Id"),gr.Textbox(label="Destination",placeholder="10 digit phone number"),
gr.Textbox(label="From Date",placeholder="yyyy-mm-dd"), gr.Textbox(label="To Date", placeholder="yyyy-mm-dd")],
outputs=[gr.Dataframe(
headers=["Candidate Number", "Duration (in seconds)", "Agent Id", 'Call Type', "Call End Time", "Recording URL"],
datatype=["str", "str","str","str", "str", "str"],
label="Recordings",wrap=True
)],
#outputs=[gr.Radio(label="Results")],
)
simple_inputs = lambda : [
gr.Dropdown(choices=["Siemens", "Sprinto","ABB", "UNext","Hetero and Hetero Biopharma","Hetero Formulation and R&D","Carelon Campus","Carelon","R1 RCM","Reach Mobile","Narayana Health","Narayana health 2",
"AllState","CITI","Wells Fargo","Hindalco","Vodafone"], label="Client"),
# gr.Dropdown(choices=["Anushree Shetti", "Manshi Y","Taskeen Ahmed","Tabrez","Varsha Amarnath","Kanwagi Kaushik","Hemani Shah","Seema Singh","Chaya Ramesh",
# "Kajal Khanna","Vandana Vijeshwar","Elizabeth Sam","Sharanya Selvam","Neha Prasad","Swati Shyam","Lakshmi Thanuja","Saniya Afreen","Smita Alex","Punit Chandok",
# "Vanessa"], label="Counsellor"),
gr.Dropdown(choices=["Exits", "CE", "NHE"], label="Process (*)"),
gr.Dropdown(choices=["Riah", "Aliya","Bhavana","Charan Deep","Aparna Kathirvelu","Jetal Patel","Saqib Chisti","Mohammed Rehan","Milli Das","Furkan Khursheen","Anshumala Shahi","Preksha","Parvathy AN","Iman Sareen","Pooja","Kajal Devkar","Khushali Jain","Shaik Salma Banu","Ananya Sethi","Alexiss Steffi","Sree Priya","Anu Agustine","Sandhiya","Hameeda Khan","Hisba","Deepshikha","Veena","Anusha","Lakshmi M","Nafisha A","Pinki Bhakta","Priyadarshi K","Nikita Alex","Yashika Haswani","Leon Augustine","Krishnendu","Swaroopa Shivaprasad","Aparna","Ananaya","Khushi","Yawer","Anuradha","Sirisha","Malavika","Spurthi","Sonali","Japhia","Arwa Nadir","Ramya K","Deepsikha Banerjee", "Geetanjali Srivastava","Sweta Sridhar","Karuna Sruthi","Anoushka Chandrashekar Chandavarkar","Ranjitha","Muskan Sukhwani","Harshitha Prabhu","Supreetha S","Ananya Srinivas","Sadia Aijaz","Japhia","Arwa Nadir","Anoushka Chandrasekhar","Ranjitha","Muskan Sukhwani","Vinnie Thampan","Nida Parveen", "Betsy Abraham","Dimple Sangvi","Evangeline Marandee","Sweety Kumbhare","Leonardo Banerji","Anjali Sadana","Ayushi Nagotia","Prajwala","Milind Kumar","Dimple Sanghvi","Sonia Mohanta","Himsuta Sharma", "Paramita Deogharia","Neelam Shalin", "Divya Kancharana", "Anchal Srivastav","Soumya Kuntoji", "Taskeen A","Suchi Agarwal","Yasmin Yunus","Shreshtha Rana","Halima Sadia","Tanisha Priyadarshini","Sheetal Raveendran Alias","Vignesh Anudharaj","Vignesh Amudharaj","Erlene Elizabeth Scaria","Shilpa Rajeev","Sowmya G R","Bhaskar Jyoti Das","Riya Sharma","Sunnil Kumar","Zainab Jawadwala","Shweta Verma","Siddhi P", "Rashmi", "Khishali Jain", "Ashwini P","Vikashene","Mir Uzair","Aaquib Altaf","Aishwarya Tharun","Jyoti Karkal","Naomi Talari","Tanya Dingar","Tabrez Abbaz","Hemani Shah","Sweta N","Diti Bamboli",
"Sneha Lal","Farhan Ahmed","Fathima Jabeen","Taskeen A","Nida Naaz","Dilna Francis","Jattley","Hiten Ashar","Vinisha Ashwin","Aparna Sharma","Krishnendu Ashok","Ruth Sneha Inbasekeran","Tasneem Rangwala","Liwina Winson",'Catherine Kaping', 'Florence Jennifher ', 'Ashwini P', 'Charchika Singh', 'Aaprajita Kumari', 'Kavini M', 'Palak Maheshwari', 'Swati Mg', 'Syeda Ashraf', 'Vinutha Ks ', 'Afelia Datta', 'Bandana Tripathi', 'Shiva Sinha', 'Pooja Mishra', 'Jayashree Balachandran', 'Anushree Shetti ', 'Varsha Amarnath', 'Anjali Nair', 'Chaitra Shree', 'Kanwagi Kaushik', 'Shweta Tiwari', 'Thanusri S', 'Shraddha Waghmare', 'Jeena Rajan', 'Swapna Sharmili', 'Manshi Y', 'Samhitha Hn', 'Chaya Ramesh', 'Swati Jha', 'Ritika Verma', 'Sarika Arora', 'Seema Gupta', 'Kamaljeet Kaur', 'Preksha Jain', 'Anisha Regmi', 'Monika Srivastava', 'Neeriksha Mohan', 'Mahima Jha', 'Prakamya Suman', 'Sana Shaikh', 'Hemani Shah', 'Archana Jain', 'Sruthi Rajan', 'Archana Hiremath', 'Mayak Mehta', 'Ashish Rana', 'Anzal Farooq ', 'Rashu Singh ', 'Muskan Shrivastava', 'Lubna Sheikh', 'Rakshitha V', 'Sruthi Ts', 'Remeez Imtiyaz', 'Navneet Kour', 'Steffi P', 'Srusti N', 'Priyanka Sarkar', 'Gladys J', 'Swati S', 'Sharanya Selvam', 'Neha Prasad', 'Lakshmi Thanuja', 'Taniya Tehreen ', 'Elizabeth Sam', 'Indumathi Nargunan', 'Swathi Shyam', 'Divya Rajvaidya', 'Feba Abraham', 'Shreyasi Roy', 'Akanksha Srivastava', 'Preeti G', 'Khanna Kajal', 'Priyanka Kumar', 'Sneha Rh', 'Vidhi Thapar', 'Sama Naqvi', 'Saniya Afreen', 'Saima Elahi', 'Vanessa Clancy'], label="Counsellor (*)"),
gr.Dropdown(choices=WHISPER_MODELS, value=default_model_name, label="Model"),
gr.Dropdown(choices=sorted(LANGUAGES), label="Language", visible=False),
gr.Text(label="URL (YouTube, etc.)"),
gr.File(label="Upload Files", file_count="multiple"),
gr.Audio(source="microphone", type="filepath", label="Microphone Input"),
gr.Dropdown(choices=["transcribe", "translate"], label="Task",visible=False),
gr.Dropdown(choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], value=default_vad, label="VAD",visible=False),
gr.Number(label="VAD - Merge Window (s)", precision=0, value=5,visible=False),
gr.Number(label="VAD - Max Merge Size (s)", precision=0, value=30,visible=False),
gr.Number(label="VAD - Padding (s)", precision=None, value=1,visible=False),
gr.Number(label="VAD - Prompt Window (s)", precision=None, value=3,visible=False)
]
io2 = gr.Interface(fn=ui.transcribe_webui, description=ui_description, article='', inputs=[
gr.Dropdown(choices=["Siemens", "Sprinto","ABB", "UNext","Hetero and Hetero Biopharma","Hetero Formulation and R&D","Carelon Campus","Carelon","R1 RCM","Reach Mobile","Narayana Health","Narayana health 2",
"AllState","CITI","Wells Fargo","Hindalco","Vodafone"], label="Client"),
# gr.Dropdown(choices=["Anushree Shetti", "Manshi Y","Taskeen Ahmed","Tabrez","Varsha Amarnath","Kanwagi Kaushik","Hemani Shah","Seema Singh","Chaya Ramesh",
# "Kajal Khanna","Vandana Vijeshwar","Elizabeth Sam","Sharanya Selvam","Neha Prasad","Swati Shyam","Lakshmi Thanuja","Saniya Afreen","Smita Alex","Punit Chandok",
# "Vanessa"], label="Counsellor"),
gr.Dropdown(choices=["Exits", "CE", "NHE"], label="Process (*)"),
gr.Dropdown(choices=["Riah", "Aliya","Japhia","Arwa Nadir","Anoushka Chandrasekhar","Ranjitha","Muskan Sukhwani","Vinnie Thampan","Jyoti Karkal","Naomi Talari","Tanya Dingar","Tabrez Abbaz","Hemani Shah","Sweta N","Diti Bamboli",
"Sneha Lal","Farhan Ahmed","Fathima Jabeen","Taskeen A","Nida Naaz","Dilna Francis","Jattley","Liwina Winson",'Catherine Kaping', 'Florence Jennifher ', 'Ashwini P', 'Charchika Singh', 'Aaprajita Kumari', 'Kavini M', 'Palak Maheshwari', 'Swati Mg', 'Syeda Ashraf', 'Vinutha Ks ', 'Afelia Datta', 'Bandana Tripathi', 'Shiva Sinha', 'Pooja Mishra', 'Jayashree Balachandran', 'Anushree Shetti ', 'Varsha Amarnath', 'Anjali Nair', 'Chaitra Shree', 'Kanwagi Kaushik', 'Shweta Tiwari', 'Thanusri S', 'Shraddha Waghmare', 'Jeena Rajan', 'Swapna Sharmili', 'Manshi Y', 'Samhitha Hn', 'Chaya Ramesh', 'Swati Jha', 'Ritika Verma', 'Sarika Arora', 'Seema Gupta', 'Kamaljeet Kaur', 'Preksha Jain', 'Anisha Regmi', 'Monika Srivastava', 'Neeriksha Mohan', 'Mahima Jha', 'Prakamya Suman', 'Sana Shaikh', 'Hemani Shah', 'Archana Jain', 'Sruthi Rajan', 'Archana Hiremath', 'Mayak Mehta', 'Ashish Rana', 'Anzal Farooq ', 'Rashu Singh ', 'Muskan Shrivastava', 'Lubna Sheikh', 'Rakshitha V', 'Sruthi Ts', 'Remeez Imtiyaz', 'Navneet Kour', 'Steffi P', 'Srusti N', 'Priyanka Sarkar', 'Gladys J', 'Swati S', 'Sharanya Selvam', 'Neha Prasad', 'Lakshmi Thanuja', 'Taniya Tehreen ', 'Elizabeth Sam', 'Indumathi Nargunan', 'Swathi Shyam', 'Divya Rajvaidya', 'Feba Abraham', 'Shreyasi Roy', 'Akanksha Srivastava', 'Preeti G', 'Khanna Kajal', 'Priyanka Kumar', 'Sneha Rh', 'Vidhi Thapar', 'Sama Naqvi', 'Saniya Afreen', 'Saima Elahi', 'Vanessa Clancy'], label="Counsellor (*)"),
gr.Dropdown(choices=WHISPER_MODELS, value=default_model_name, label="Model"),
gr.Dropdown(choices=sorted(LANGUAGES), label="Language"),
gr.Text(label="URL (YouTube, etc.)"),
gr.File(label="Upload Files", file_count="multiple"),
gr.Audio(source="microphone", type="filepath", label="Microphone Input"),
gr.Dropdown(choices=["transcribe", "translate"], label="Task",visible=False),
gr.Dropdown(choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], value=default_vad, label="VAD",visible=False),
gr.Number(label="VAD - Merge Window (s)", precision=0, value=5,visible=False),
gr.Number(label="VAD - Max Merge Size (s)", precision=0, value=30,visible=False),
gr.Number(label="VAD - Padding (s)", precision=None, value=1,visible=False),
gr.Number(label="VAD - Prompt Window (s)", precision=None, value=3,visible=False)
], outputs=[
gr.Textbox(label="Client, Counsellor, Process"),
gr.File(label="Download"),
gr.Text(label="Transcription"),
gr.Text(label="Segments")
])
"""
io3 = gr.Interface(fn=ui.transcribe_webui_full, description=ui_description, article='', inputs=[
*simple_inputs(),
gr.Dropdown(choices=["prepend_first_segment", "prepend_all_segments"], value=app_config.vad_initial_prompt_mode, label="VAD - Initial Prompt Mode"),
gr.TextArea(label="Initial Prompt"),
gr.Number(label="Temperature", value=app_config.temperature),
gr.Number(label="Best Of - Non-zero temperature", value=app_config.best_of, precision=0),
gr.Number(label="Beam Size - Zero temperature", value=app_config.beam_size, precision=0),
gr.Number(label="Patience - Zero temperature", value=app_config.patience),
gr.Number(label="Length Penalty - Any temperature", value=app_config.length_penalty),
gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value=app_config.suppress_tokens),
gr.Checkbox(label="Condition on previous text", value=app_config.condition_on_previous_text),
gr.Checkbox(label="FP16", value=app_config.fp16),
gr.Number(label="Temperature increment on fallback", value=app_config.temperature_increment_on_fallback),
gr.Number(label="Compression ratio threshold", value=app_config.compression_ratio_threshold),
gr.Number(label="Logprob threshold", value=app_config.logprob_threshold),
gr.Number(label="No speech threshold", value=app_config.no_speech_threshold)
], outputs=[
gr.File(label="Download"),
gr.Text(label="Transcription"),
gr.Text(label="Segments")
])
"""
io3 = gr.Interface(fn=ui.transcribe_webui_full, description=ui_description, article='', inputs=[
*simple_inputs(),
gr.TextArea(label="Initial Prompt", visible=False),
gr.Number(label="Temperature", value=0, visible=False),
gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
gr.Number(label="Patience - Zero temperature", value=None,visible=False),
gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
gr.Checkbox(label="Condition on previous text", value=True,visible=False),
gr.Checkbox(label="FP16", value=True,visible=False),
gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
gr.Number(label="Logprob threshold", value=-1.0,visible=False),
gr.Number(label="No speech threshold", value=0.6,visible=False)
], outputs=[
gr.Textbox(label="Client, Counsellor, Process"),
#gr.File(label="Download"),
gr.Text(label="Transcription"),
])
io4 = gr.Interface(fn=ui.transcribe_webui_full_verbatim, description=ui_description, article='', inputs=[
*simple_inputs(),
gr.TextArea(label="Initial Prompt", visible=False),
gr.Number(label="Temperature", value=0, visible=False),
gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
gr.Number(label="Patience - Zero temperature", value=None,visible=False),
gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
gr.Checkbox(label="Condition on previous text", value=True,visible=False),
gr.Checkbox(label="FP16", value=True,visible=False),
gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
gr.Number(label="Logprob threshold", value=-1.0,visible=False),
gr.Number(label="No speech threshold", value=0.6,visible=False)
], outputs=[
gr.Textbox(label="Client, Counsellor, Process"),
#gr.File(label="Download"),
gr.Text(label="Transcription"),
gr.Text(label="Proposed Verbatim - Please review & update as required")
#gr.Text(label="Segments")
])
io5 = gr.Interface(fn=ui.transcribe_webui_full_verbatim_qa, description=ui_description, article='', inputs=[
*simple_inputs(),
gr.TextArea(label="REASONS FOR LEAVING AND REACTION TO REASON FOR LEAVING",value="1.What triggered your decision to leave? \n2.Who spoke to you after you resigned? \n3.In your opinion did they make a genuine effort to retain you? \n4.What could the organization have done to retain you? "),
gr.TextArea(label="RECRUITMENT FEEDBACK (0-12 MONTHS TENURE) (Rate on a scale of 1-10)",value="1.Role clarity- Were you given clarity about your role before you joined? If less than 7, why? \n2.On-boarding process- Did your on-boarding process go on smoothly and on time? If less than 7, why? \n3.Time taken for the recruitment process- Was the overall interview organized and quick? If less than 7, why? If less than 7, why? \n4.Hand-holding- Were you given the required support, guidance and knowledge transfer for your new role? If less than 7 ,why?\n5.JD and current role match- Does your current role match the JD that was provided to you at the time of joining? If less than 7, why? \n6.What was done well during the overall recruitment process? \n7.What could have been done better during the overall recruitment process? "),
gr.TextArea(label="SURVEY QUESTIONS (Rate on a scale of 1-10)",value="1.What is your supervisor's name? \n2.What is your supervisor's designation? \n3.Subject knowledge - Do you believe your manager was competent to be able to deal with the issues you and your team mates have during your workday? If less than 7, why? \n4.Team management- How effectively did your manager work with the resources provided to him/her to get the task at hand completed? If less than 7, why? \n5.Being unbiased- Did your Manager give fair opportunities to everyone in the team? If less than 7, why? \n6.Offering growth opportunities- Did you Manager encourage growth and allow you to explore new tasks? \n7.Providing feedback - Was the feedback provided by the manager to you fair and clear which outlined a clear way for you to grow as an individual? If less than 7, why? \n8.Given a chance would you like to work with your current manager in the future? \n9.Senior leadership - opportunity to interact and visibility . If less than 7, why? \n10.Role satisfaction - having a sense of direction with what you do and having the required tools/ resources to do this. If less than 7, why? \n11.Rewards and Recognition- being rewarded and recognized adequately for hard work and effort.If less than 7, why? \n12.Performance Management System(includes Growth Opportunities)- level of transparency in the appraisal and promotion process. \n13.Work-Life Balance- being able maintain a healthy balance between work life and personal life?If less than 7, why?"),
gr.TextArea(label="APPRECIATIVE ENQUIRY",value="1.How likely are you to recommend the organization to you friends and family to work in on a scale of 0-10 (0 being the lowest)? \n2.eNPS Comments \n3.What is the one thing you liked the most about the organization? \n4.Would you be willing to re-join? \n5.Where are you working now? \n6.Did you join the new company in the same industry as you were working for in the previous company? \n7.What is your current designation? \n8.How much of a hike have you received? "),
gr.TextArea(label="Initial Prompt", visible=False),
gr.Number(label="Temperature", value=0, visible=False),
gr.Number(label="Best Of - Non-zero temperature", value=5, precision=0, visible=False),
gr.Number(label="Beam Size - Zero temperature", value=5, precision=0,visible=False),
gr.Number(label="Patience - Zero temperature", value=None,visible=False),
gr.Number(label="Length Penalty - Any temperature", value=None,visible=False),
gr.Text(label="Suppress Tokens - Comma-separated list of token IDs", value="-1",visible=False),
gr.Checkbox(label="Condition on previous text", value=True,visible=False),
gr.Checkbox(label="FP16", value=True,visible=False),
gr.Number(label="Temperature increment on fallback", value=0.2,visible=False),
gr.Number(label="Compression ratio threshold", value=2.4,visible=False),
gr.Number(label="Logprob threshold", value=-1.0,visible=False),
gr.Number(label="No speech threshold", value=0.6,visible=False)
], outputs=[
gr.Textbox(label="Client, Counsellor, Process"),
gr.Text(label="Transcription"),
gr.Text(label="Answers For Questionnaire 3 - Set 1"),
gr.Text(label="Answers For Questionnaire 3 - Set 2"),
gr.Text(label="Answers For Questionnaire 3 - Set 3"),
gr.Text(label="Answers For Questionnaire 3 - Set 4"),
])
#demo.launch(share=share, server_name=server_name, server_port=server_port)
gr.TabbedInterface(
[io1, io3,io4, io5], ["Pragyaa Select", "Pragyaa Transcribe", "Pragyaa Transcribe With Verbatim","Pragyaa Transcribe With Questionnaire"]
).queue(concurrency_count=5).launch(share=share, server_name=server_name, server_port=server_port)
# Clean up
ui.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--input_audio_max_duration", type=int, default=DEFAULT_INPUT_AUDIO_MAX_DURATION, help="Maximum audio file length in seconds, or -1 for no limit.")
parser.add_argument("--share", type=bool, default=False, help="True to share the app on HuggingFace.")
parser.add_argument("--server_name", type=str, default=None, help="The host or IP to bind to. If None, bind to localhost.")
parser.add_argument("--server_port", type=int, default=7860, help="The port to bind to.")
parser.add_argument("--default_model_name", type=str, choices=WHISPER_MODELS, default="medium", help="The default model name.")
parser.add_argument("--default_vad", type=str, default="silero-vad", help="The default VAD.")
parser.add_argument("--vad_parallel_devices", type=str, default="", help="A commma delimited list of CUDA devices to use for parallel processing. If None, disable parallel processing.")
parser.add_argument("--vad_cpu_cores", type=int, default=1, help="The number of CPU cores to use for VAD pre-processing.")
parser.add_argument("--vad_process_timeout", type=float, default="1800", help="The number of seconds before inactivate processes are terminated. Use 0 to close processes immediately, or None for no timeout.")
parser.add_argument("--auto_parallel", type=bool, default=False, help="True to use all available GPUs and CPU cores for processing. Use vad_cpu_cores/vad_parallel_devices to specify the number of CPU cores/GPUs to use.")
parser.add_argument("--output_dir", "-o", type=str, default=None, help="directory to save the outputs")
args = parser.parse_args().__dict__
create_ui(**args)