cdactvm's picture
Create app.py
aeac508 verified
raw
history blame
6.32 kB
import warnings
warnings.filterwarnings("ignore")
import os
import re
import pywt
import librosa
import webrtcvad
import nbimporter
import torchaudio
import numpy as np
import gradio as gr
import scipy.signal
import soundfile as sf
from scipy.io.wavfile import write
from transformers import pipeline
from transformers import AutoProcessor
from pyctcdecode import build_ctcdecoder
from transformers import Wav2Vec2ProcessorWithLM
from scipy.signal import butter, lfilter, wiener
from text2int import text_to_int
from isNumber import is_number
from Text2List import text_to_list
from convert2list import convert_to_list
from processDoubles import process_doubles
from replaceWords import replace_words
from applyVad import apply_vad
from wienerFilter import wiener_filter
from highPassFilter import high_pass_filter
from waveletDenoise import wavelet_denoise
from scipy.signal import butter, lfilter, wiener
asr_model = pipeline("automatic-speech-recognition", model="cdactvm/punjabi-wav2vec-bert")
# Function to apply a high-pass filter
def high_pass_filter(audio, sr, cutoff=300):
nyquist = 0.5 * sr
normal_cutoff = cutoff / nyquist
b, a = butter(1, normal_cutoff, btype='high', analog=False)
filtered_audio = lfilter(b, a, audio)
return filtered_audio
# Function to apply wavelet denoising
def wavelet_denoise(audio, wavelet='db1', level=1):
coeffs = pywt.wavedec(audio, wavelet, mode='per')
sigma = np.median(np.abs(coeffs[-level])) / 0.5
uthresh = sigma * np.sqrt(2 * np.log(len(audio)))
coeffs[1:] = [pywt.threshold(i, value=uthresh, mode='soft') for i in coeffs[1:]]
return pywt.waverec(coeffs, wavelet, mode='per')
# Function to apply a Wiener filter for noise reduction
def apply_wiener_filter(audio):
return wiener(audio)
def createlex(filename):
# Initialize an empty dictionary
data_dict = {}
# Open the file and read it line by line
with open(filename, "r", encoding="utf-8") as f:
for line in f:
# Strip newline characters and split by tab
key, value = line.strip().split("\t")
# Add to dictionary
data_dict[key] = value
return data_dict
lex=createlex("num_words_ta.txt")
def addnum(inlist):
sum=0
for num in inlist:
sum+=int(num)
return sum
from rapidfuzz import process
def get_val(word, lexicon):
threshold = 80 # Minimum similarity score
length_difference = 4
#length_range = (4, 6) # Acceptable character length range (min, max)
# Find the best match above the similarity threshold
result = process.extractOne(word, lexicon.keys(), score_cutoff=threshold)
#print (result)
if result:
match, score, _ = result
#print(lexicon[match])
#return lexicon[match]
if abs(len(match) - len(word)) <= length_difference:
#if length_range[0] <= len(match) <= length_range[1]:
return lexicon[match]
else:
return None
else:
return None
def convert2num(input, lex):
input += " #" # Add a period for termination
words = input.split()
i = 0
num = 0
outstr = ""
digit_end = True
numlist = []
addflag = False
# Process the words
while i < len(words):
#checkwordlist = handleSpecialnum(words[i])
# Handle special numbers
#if len(checkwordlist) == 2:
# words[i] = checkwordlist[0]
# words.insert(i + 1, checkwordlist[1]) # Collect new word for later processing
# Get numerical value of the word
numval = get_val(words[i], lex)
if numval is not None:
if words[i][-4:] in ('த்து', 'ற்று'):
addflag = True
numlist.append(numval)
else:
if addflag:
numlist.append(numval)
num = addnum(numlist)
outstr += str(num) + " "
addflag = False
numlist = []
else:
outstr += " " + str(numval) + " "
digit_end = False
else:
if addflag:
num = addnum(numlist)
outstr += str(num) + " " + words[i] + " "
addflag = False
numlist = []
else:
outstr += words[i] + " "
if not digit_end:
digit_end = True
# Move to the next word
i += 1
# Final processing
outstr = outstr.replace('#','') # Remove trailing spaces
return outstr
# Function to handle speech recognition
def recognize_speech(audio_file):
audio, sr = librosa.load(audio_file, sr=16000)
audio = high_pass_filter(audio, sr)
audio = apply_wiener_filter(audio)
denoised_audio = wavelet_denoise(audio)
result = asr_model(denoised_audio)
text_value = result['text']
cleaned_text = text_value.replace("<s>", "")
cleaned_text=convert2num(cleaned_text,lex)
# converted_to_list = convert_to_list(cleaned_text, text_to_list())
# processed_doubles = process_doubles(converted_to_list)
# replaced_words = replace_words(processed_doubles)
# converted_text = text_to_int(replaced_words)
return cleaned_text
def sel_lng(lng, mic=None, file=None):
if mic is not None:
audio = mic
elif file is not None:
audio = file
else:
return "You must either provide a mic recording or a file"
if lng == "model_1":
return recognize_speech(audio)
# elif lng == "model_2":
# return transcribe_hindi_new(audio)
# elif lng== "model_3":
# return transcribe_hindi_lm(audio)
# elif lng== "model_4":
# return Noise_cancellation_function(audio)
demo=gr.Interface(
fn=sel_lng,
inputs=[
gr.Dropdown([
"model_1"],label="Select Model"),
gr.Audio(sources=["microphone","upload"], type="filepath"),
],
outputs=[
"textbox"
],
title="Automatic Speech Recognition",
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",
).launch()