cdactvm commited on
Commit
7859771
·
verified ·
1 Parent(s): fb454ed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -0
app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.filterwarnings("ignore")
3
+
4
+ import os
5
+ import re
6
+ import pywt
7
+ import librosa
8
+ import webrtcvad
9
+ import nbimporter
10
+ import torchaudio
11
+ import numpy as np
12
+ import gradio as gr
13
+ import scipy.signal
14
+ import soundfile as sf
15
+ from scipy.io.wavfile import write
16
+ from transformers import pipeline
17
+ from transformers import AutoProcessor
18
+ from pyctcdecode import build_ctcdecoder
19
+ from transformers import Wav2Vec2ProcessorWithLM
20
+ # from text2int import text_to_int
21
+ # from isNumber import is_number
22
+ # from Text2List import text_to_list
23
+ # from convert2list import convert_to_list
24
+ # from processDoubles import process_doubles
25
+ # from replaceWords import replace_words
26
+ # from applyVad import apply_vad
27
+ # from wienerFilter import wiener_filter
28
+ # from highPassFilter import high_pass_filter
29
+ # from waveletDenoise import wavelet_denoise
30
+ from scipy.signal import butter, lfilter, wiener
31
+
32
+ asr_model_telugu = pipeline("automatic-speech-recognition", model="cdactvm/telugu_w2v-bert_model")
33
+ asr_model_kannada = pipeline("automatic-speech-recognition", model="cdactvm/w2v_bert_kannada_030125")
34
+
35
+ def createlex(filename):
36
+ #filename = "num_map.txt"
37
+
38
+ # Initialize an empty dictionary
39
+ data_dict = {}
40
+
41
+ # Open the file and read it line by line
42
+ with open(filename, "r", encoding="utf-8") as f:
43
+ for line in f:
44
+ # Strip newline characters and split by tab
45
+ key, value = line.strip().split("\t")
46
+ # Add to dictionary
47
+ data_dict[key] = value
48
+ return data_dict
49
+
50
+ tellex=createlex("num_words_tel.txt")
51
+ kanlex=createlex("num_words_kn.txt")
52
+ def addnum(inlist):
53
+ sum=0
54
+ for num in inlist:
55
+ sum+=int(num)
56
+
57
+ return sum
58
+
59
+ from rapidfuzz import process
60
+ def get_val(word, lexicon):
61
+ threshold = 80 # Minimum similarity score
62
+ length_difference = 4
63
+ #length_range = (4, 6) # Acceptable character length range (min, max)
64
+
65
+ # Find the best match above the similarity threshold
66
+ result = process.extractOne(word, lexicon.keys(), score_cutoff=threshold)
67
+ print (result)
68
+ if result:
69
+ match, score, _ = result
70
+ #print(lexicon[match])
71
+ #return lexicon[match]
72
+ if abs(len(match) - len(word)) <= length_difference:
73
+ #if length_range[0] <= len(match) <= length_range[1]:
74
+ return lexicon[match]
75
+ else:
76
+ return None
77
+ else:
78
+ return None
79
+ def convert2numtel(input, lex):
80
+ input += " #" # Add a period for termination
81
+ words = input.split()
82
+ i = 0
83
+ num = 0
84
+ outstr = ""
85
+ digit_end = True
86
+ numlist = []
87
+ addflag = False
88
+ prevword=""
89
+ single_list=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,15,17,18,19]
90
+ # Process the words
91
+ while i < len(words):
92
+ #checkwordlist = handleSpecialnum(words[i])
93
+
94
+ # Handle special numbers
95
+ #if len(checkwordlist) == 2:
96
+ # words[i] = checkwordlist[0]
97
+ # words.insert(i + 1, checkwordlist[1]) # Collect new word for later processing
98
+
99
+ # Get numerical value of the word
100
+ numval = get_val(words[i], lex)
101
+ if numval is not None:
102
+ if prevword not in single_list:
103
+ addflag = True
104
+ numlist.append(numval)
105
+ else:
106
+ if addflag:
107
+ numlist.append(numval)
108
+ num = addnum(numlist)
109
+ outstr += str(num) + " "
110
+ addflag = False
111
+ numlist = []
112
+ else:
113
+ outstr += " " + str(numval) + " "
114
+ digit_end = False
115
+ prevword=numval
116
+ else:
117
+ prevword=""
118
+ if addflag:
119
+ num = addnum(numlist)
120
+ outstr += str(num) + " " + words[i] + " "
121
+ addflag = False
122
+ numlist = []
123
+ else:
124
+ outstr += words[i] + " "
125
+ if not digit_end:
126
+ digit_end = True
127
+
128
+ # Move to the next word
129
+ i += 1
130
+
131
+ # Final processing
132
+ outstr = outstr.replace('#','') # Remove trailing spaces
133
+ return outstr
134
+
135
+ def convert2numkn(input, lex):
136
+ input += " ######" # Add a period for termination
137
+ words = input.split()
138
+ i = 0
139
+ num = 0
140
+ outstr = ""
141
+ digit_end = True
142
+ numlist = []
143
+ addflag = False
144
+
145
+ prevword = []
146
+
147
+ # Process the words
148
+ while i < len(words):
149
+
150
+ # Get numerical value of the word
151
+ numval = get_val(words[i], lex)
152
+ if len(prevword)>=3:
153
+ prevword.pop(0)
154
+ prevword.append(words[i])
155
+ else:
156
+ prevword.append(words[i])
157
+ if numval is not None:
158
+
159
+ addflag = True
160
+
161
+ numlist.append(numval)
162
+
163
+ else:
164
+
165
+
166
+ #print("word--->"+words[i])
167
+ #print("addflagword--->"+str(addflag))
168
+ prevwords=" ".join(prevword)
169
+ #print("prev word--->"+prevwords)
170
+ numval=get_val(prevwords,lex)
171
+ if numval is not None:
172
+ #addflag=True
173
+ #print("numval " +numval)
174
+ numlist=[]
175
+ #print("First outstr--->"+outstr)
176
+
177
+
178
+ outwords = outstr.split()
179
+ outstr=" ".join(outwords[:-1])
180
+ #print("outstr--->"+outstr)
181
+
182
+ outstr += " " + str(numval) + " "
183
+ #print(" aoutstr--->"+outstr)
184
+ numval=0
185
+ addflag=False
186
+
187
+ else:
188
+ if addflag:
189
+ num = addnum(numlist)
190
+ outstr += str(num) + " " + words[i] + " "
191
+ #print("penlast outstr--->"+outstr)
192
+ addflag = False
193
+ numlist = []
194
+ else:
195
+ outstr += words[i] + " "
196
+ #print("last outstr--->"+outstr)
197
+ if not digit_end:
198
+ digit_end = True
199
+
200
+
201
+
202
+ # Move to the next word
203
+ i += 1
204
+
205
+ # Final processing
206
+ outstr = outstr.replace('#','') # Remove trailing spaces
207
+ return outstr
208
+
209
+ # Function to apply a high-pass filter
210
+ def high_pass_filter(audio, sr, cutoff=300):
211
+ nyquist = 0.5 * sr
212
+ normal_cutoff = cutoff / nyquist
213
+ b, a = butter(1, normal_cutoff, btype='high', analog=False)
214
+ filtered_audio = lfilter(b, a, audio)
215
+ return filtered_audio
216
+
217
+ # Function to apply wavelet denoising
218
+ def wavelet_denoise(audio, wavelet='db1', level=1):
219
+ coeffs = pywt.wavedec(audio, wavelet, mode='per')
220
+ sigma = np.median(np.abs(coeffs[-level])) / 0.5
221
+ uthresh = sigma * np.sqrt(2 * np.log(len(audio)))
222
+ coeffs[1:] = [pywt.threshold(i, value=uthresh, mode='soft') for i in coeffs[1:]]
223
+ return pywt.waverec(coeffs, wavelet, mode='per')
224
+
225
+ # Function to apply a Wiener filter for noise reduction
226
+ def apply_wiener_filter(audio):
227
+ return wiener(audio)
228
+
229
+
230
+ # Function to handle speech recognition
231
+ def recognize_speech_telugu(audio_file):
232
+ audio, sr = librosa.load(audio_file, sr=16000)
233
+ #audio = high_pass_filter(audio, sr)
234
+ #audio = apply_wiener_filter(audio)
235
+ #denoised_audio = wavelet_denoise(audio)
236
+ #result = asr_model_telugu(denoised_audio)
237
+ result = asr_model_telugu(audio)
238
+ text_value = result['text']
239
+ print (text_value)
240
+ cleaned_text = text_value.replace("<s>", "")
241
+ converted_text=convert2numtel(cleaned_text,tellex)
242
+ # cleaned_text=convert2num(cleaned_text,lex)
243
+ # converted_to_list = convert_to_list(cleaned_text, text_to_list())
244
+ # processed_doubles = process_doubles(converted_to_list)
245
+ # replaced_words = replace_words(processed_doubles)
246
+ # converted_text = text_to_int(replaced_words)
247
+ return cleaned_text +" -----------------> " + converted_text
248
+ #return cleaned_text
249
+
250
+ # Function to handle speech recognition
251
+ def recognize_speech_kannada(audio_file):
252
+ audio, sr = librosa.load(audio_file, sr=16000)
253
+ audio = high_pass_filter(audio, sr)
254
+ audio = apply_wiener_filter(audio)
255
+ denoised_audio = wavelet_denoise(audio)
256
+ result = asr_model_kannada(denoised_audio)
257
+ text_value = result['text']
258
+ cleaned_text = text_value.replace("[UNK]", "")
259
+ converted_text=convert2numkn(cleaned_text,kanlex)
260
+ #converted_text=convert2num(cleaned_text,lex)
261
+ # cleaned_text=convert2num(cleaned_text,lex)
262
+ # converted_to_list = convert_to_list(cleaned_text, text_to_list())
263
+ # processed_doubles = process_doubles(converted_to_list)
264
+ # replaced_words = replace_words(processed_doubles)
265
+ # converted_text = text_to_int(replaced_words)
266
+ return cleaned_text +" -----------------> " + converted_text
267
+
268
+ def sel_lng(lng, mic=None, file=None):
269
+ if mic is not None:
270
+ audio = mic
271
+ elif file is not None:
272
+ audio = file
273
+ else:
274
+ return "You must either provide a mic recording or a file"
275
+
276
+ if lng == "Telugu":
277
+ return recognize_speech_telugu(audio)
278
+ elif lng == "Kannada":
279
+ return recognize_speech_kannada(audio)
280
+ # elif lng== "model_3":
281
+ # return transcribe_hindi_lm(audio)
282
+ # elif lng== "model_4":
283
+ # return Noise_cancellation_function(audio)
284
+
285
+
286
+ demo=gr.Interface(
287
+ fn=sel_lng,
288
+
289
+ inputs=[
290
+ gr.Dropdown([
291
+ "Telugu","Kannada"],label="Select Model"),
292
+ gr.Audio(sources=["microphone","upload"], type="filepath"),
293
+ ],
294
+ outputs=[
295
+ "textbox"
296
+ ],
297
+ title="Automatic Speech Recognition",
298
+ description = "Demo for Automatic Speech Recognition. Use microphone to record speech. Please press Record button. Initially it will take some time to load the model. The recognized text will appear in the output textbox",
299
+ ).launch()