Skip to content

Instantly share code, notes, and snippets.

@pteacher
Created November 25, 2022 11:13
Show Gist options
  • Save pteacher/6789ff3009621fa131f2e8f8d9db3a49 to your computer and use it in GitHub Desktop.
Save pteacher/6789ff3009621fa131f2e8f8d9db3a49 to your computer and use it in GitHub Desktop.
Python voice recognition using vosk for Turkish language
import os
import wave
from vosk import Model, KaldiRecognizer
import json
import librosa
import soundfile as sf
def get_text_from_voice(filename):
if not os.path.exists("model"):
print ("Please download the model from https://alphacephei.com/vosk/models and unpack as 'model' in the current folder.")
exit (1)
x,_ = librosa.load(filename, sr=16000)
sf.write('tmp.wav', x, 16000)
wf = wave.open('tmp.wav', "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print ("Audio file must be WAV format mono PCM.")
exit (1)
model = Model("model")
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
text_lst =[]
p_text_lst = []
p_str = []
len_p_str = []
txt = [""]
id = 0
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
text_lst.append(rec.Result())
print(rec.Result())
id += 1
txt.append("")
else:
p_text_lst.append(rec.PartialResult())
p = json.loads(rec.PartialResult())["partial"]
txt[id] = p
# print(p)
if len(text_lst) !=0:
jd = json.loads(text_lst[0])
txt_str = jd["text"]
elif len(p_text_lst) !=0:
for i in range(0,len(p_text_lst)):
temp_txt_dict = json.loads(p_text_lst[i])
p_str.append(temp_txt_dict['partial'])
len_p_str = [len(p_str[j]) for j in range(0,len(p_str))]
max_val = max(len_p_str)
indx = len_p_str.index(max_val)
txt_str = p_str[indx]
print(txt_str)
txt.append(txt_str)
else:
txt_str =''
return ". ".join(txt)
res = get_text_from_voice("test.ogg")
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment