Uberi / speech_recognition

Speech recognition module for Python, supporting several engines and APIs, online and offline.
https://pypi.python.org/pypi/SpeechRecognition/
BSD 3-Clause "New" or "Revised" License
8.16k stars 2.39k forks source link

Python speech_recognition.UnknownValueError #383

Open DanielBDosSantos opened 5 years ago

DanielBDosSantos commented 5 years ago

I'm trying to make a virtual assistant, right now it's suppost to just write down what I say. However when I try to test it it returns,

Traceback (most recent call last): File "/Users/danieldossantos/Desktop/jarvis/chats/main.py", line 14, in speech = r.recognize_google(audio, language = 'pt') File "/Library/Python/2.7/site-packages/speech_recognition/init.py", line 858, in recognize_google if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError() speech_recognition.UnknownValueError

I've checked my code and I haven't found any errors, at least not that I know of,

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone() as s:
    r.adjust_for_ambient_noise(s)

    while True:
        audio = r.listen(s)

        speech = r.recognize_google(audio, language = 'pt')

        print('Você disse: ', speech)
palikar commented 5 years ago

Hey,

it seems that the thing returned from the Google API is somehow not in the format expected by the library. I assume that's because of the language string you pass as argument to the r.recognize_google method. I think it should be language = 'pt-PT instead of language = 'pt. Consult this post for the supported by the Google Speech API languages.

If this does not solve the problem, try calling the method as r.recognize_google(audio, language = 'pt', show_all=True) and then inspect the result.

aruna09 commented 5 years ago

Hey, I was facing the same issue. I was getting an empty line in the console initially. After having mentioned the language and show_all=True, it now shows [] in the terminal.

I am working on a 16.04 ubuntu, python3 and Speech Recognition 3.8.1 This is my code:

import speech_recognition as sr

recognize = sr.Recognizer()

audioFile = "down_to_cases.wav"

with sr.AudioFile(audioFile) as source: print("Start talking: ") audio = recognize.record(source) print("Stop talking.")

try: text = recognize.recognize_google(audio, language='en-IN', show_all=True) print("in the try block") print (text) except Exception as e: print("I am here") print (e)

Thank you for the help.

mohitv789 commented 5 years ago

I am facing this issue with following code:

def SpeechToText():
    r = sr.Recognizer()   #Speech recognition
    audio = sr.AudioFile("resume.wav")
    with audio as source:
        print("Wait. Program Starting")
        audio = r.record(source)
        message = r.recognize_google(audio)
        print("Check: "+message)
    return message
print(SpeechToText())
rejeanchicoine commented 5 years ago

Google require a key now.

sresult = r.recognize_google(audio,key="AIzaSyDRdSN1VaRW27HxA68rZW5FesS2qoPD8", language="fr-FR",show_all=True)

rejeanchicoine commented 5 years ago

I face the same issue after some test ... if I change r.recognize_google(audio) by r.recognize(audio) it's seem to work english only and witout a key... that's pretty strange and I don't know why.

I would like to change language.

kamuridesu commented 5 years ago

Hi, the show_all = True solved it, but show [ ] and this:

You said:  []
You said:  {'alternative': [{'transcript': 'Bom dia', 'confidence': 0.96170539}, {'transcript': 'bom-dia'}, {'transcript': 'é bom dia'}, {'transcript': 'tá bom dia'}], 'final': True}
You said:  []

It's information that I don't need so there's a way to show only the information I need (in this case is the first "Bom dia".

rejeanchicoine commented 5 years ago

Hi, I finally make it work without putting the key and just put the language make sur to put the json,dump abd .encode('utf8') this will prevent error on foreign language.

sFinalResult = r.recognize_google(audio, language='fr-CA') response = json.dumps(sFinalResult, ensure_ascii=False).encode('utf8') print("++++++++++++++++++ " + response + " ++++++++++++++++++++++++")

mr-pourghorban commented 5 years ago

hi how can i user.recognize_google(audio,language="fa-IR" in python when i am offline ?

Paul-gnp commented 4 years ago

hi how can i user.recognize_google(audio,language="fa-IR" in python when i am offline ?

you cant

urvish667 commented 4 years ago

hi how can i user.recognize_google(audio,language="fa-IR" in python when i am offline ?

hi how can i user.recognize_google(audio,language="fa-IR" in python when i am offline ?

you cant

but you can use pocketsphinx package for offline

PrudhviJonnalagadda commented 4 years ago

If we do not mention the language in recognize_google class, what is the default language that it will pick?

yoavh28 commented 4 years ago

Hey, I tried do run a script from edureka's video In youtube and I was facing the same issue. My script should print what I say and it doesn't do it.

This is my code:

import speech_recognition as sr
import webbrowser as wb

r1= sr.Recognizer()
r2= sr.Recognizer()
r3= sr.Recognizer()

with sr.Microphone() as source:
    print('[search edureka: search youtube]')
    print('speak now')
    audio =r3.listen(source)

if 'edureka' in r2.recognize_google(audio):
    r2 = sr.Recognizer()
    url = 'https://www.edureaka.co/'
    with sr.Microphone() as source:
        print('search your query')
        audio = r2.listen(source)

        try:
            get = r1.recognize_google(audio)
            print(get)
            wb.get().open_new(url + get)

        except sr.UnKnownValueError:
            print('error')

        except sr.UnKnownValueError as e:
            print('failed'.format(e))

if 'video' in r1.recognize_google(audio):
    r1=sr.Recognizer()
    url='https://www.youtube.com/results?search_query='
    with sr.Microphone() as source:
        print('search your query: search youtube')
        audio =r2.listen(source)

        try:
            get=r1.recognize_google(audio)
            print(get)
            wb.get().open_new(url+get)

        except sr.UnKnownValueError:
            print('error')

        except sr.UnKnownValueError as e:
            print('failed'.format(e))
print(r2.recognize_google(audio))
anastaciopaulino commented 4 years ago

Oi, o show_all = True resolveu, mas show [] e isto:

You said:  []
You said:  {'alternative': [{'transcript': 'Bom dia', 'confidence': 0.96170539}, {'transcript': 'bom-dia'}, {'transcript': 'é bom dia'}, {'transcript': 'tá bom dia'}], 'final': True}
You said:  []

É uma informação que eu não preciso, então existe uma maneira de mostrar apenas a informação que eu preciso (nesse caso, é o primeiro "Bom dia".

Em vez de meteres o show_all=True inverta a situação, para show_all=False Assim: speech = r.recognize_google (audio, language = "pt", show_all = False)

Ravistar85 commented 4 years ago

Pls help me, Not sure what is the issues

ModuleNotFoundError Traceback (most recent call last) /opt/anaconda3/lib/python3.7/site-packages/speech_recognition/init.py in get_pyaudio() 107 try: --> 108 import pyaudio 109 except ImportError:

ModuleNotFoundError: No module named 'pyaudio'

During handling of the above exception, another exception occurred:

AttributeError Traceback (most recent call last)

in 3 r = sr.Recognizer() 4 ----> 5 with sr.Microphone() as s: 6 r.adjust_for_ambient_noise(s) 7 /opt/anaconda3/lib/python3.7/site-packages/speech_recognition/__init__.py in __init__(self, device_index, sample_rate, chunk_size) 77 78 # set up PyAudio ---> 79 self.pyaudio_module = self.get_pyaudio() 80 audio = self.pyaudio_module.PyAudio() 81 try: /opt/anaconda3/lib/python3.7/site-packages/speech_recognition/__init__.py in get_pyaudio() 108 import pyaudio 109 except ImportError: --> 110 raise AttributeError("Could not find PyAudio; check installation") 111 from distutils.version import LooseVersion 112 if LooseVersion(pyaudio.__version__) < LooseVersion("0.2.11"): AttributeError: Could not find PyAudio; check installation
Diyanah98 commented 4 years ago

Anyone please help i am a beginner but have a project for Virtual Assistant. When i am trying to execute except sr.UnknownValueError: why it always SyntaxError: invalid syntax ????? I know for some of you, this is very basic but for me this is confusing. Thanks for helping

rzw-gh commented 3 years ago

speech_recognition.UnknownValueError is just for noises use try exception like this:

try: query = r.recognize_google(audio, language='en') except Exception as e: return "None"

DEALTALFA commented 3 years ago

Pls help me, Not sure what is the issues

ModuleNotFoundError Traceback (most recent call last) /opt/anaconda3/lib/python3.7/site-packages/speech_recognition/init.py in get_pyaudio() 107 try: --> 108 import pyaudio 109 except ImportError:

ModuleNotFoundError: No module named 'pyaudio'

During handling of the above exception, another exception occurred:

AttributeError Traceback (most recent call last) in 3 r = sr.Recognizer() 4 ----> 5 with sr.Microphone() as s: 6 r.adjust_for_ambient_noise(s) 7

/opt/anaconda3/lib/python3.7/site-packages/speech_recognition/init.py in init(self, device_index, sample_rate, chunk_size) 77 78 # set up PyAudio ---> 79 self.pyaudio_module = self.get_pyaudio() 80 audio = self.pyaudio_module.PyAudio() 81 try:

/opt/anaconda3/lib/python3.7/site-packages/speech_recognition/init.py in get_pyaudio() 108 import pyaudio 109 except ImportError: --> 110 raise AttributeError("Could not find PyAudio; check installation") 111 from distutils.version import LooseVersion 112 if LooseVersion(pyaudio.version) < LooseVersion("0.2.11"):

AttributeError: Could not find PyAudio; check installation

U need to install pyaudio module. Go to terminal if your in window conda install pyaudio This would fix your prblm

himanshudogra commented 3 years ago

Not sure If we have a permanent fix available yet. I was facing the similar issues and dig more into it. Here are my findings.

Testing Code:

import speech_recognition as sr
import pyttsx3

#print(sr.Microphone.list_microphone_names())

print("Welcome to my tools.\n")

r=sr.Recognizer()

with sr.Microphone() as source:
    pyttsx3.speak("Please tell your requirements.")
    audio=r.record(source,duration=5)
    print("We got you.. Please wait while we are working on your requirements.")

i=r.recognize_google(audio,language='en-US')

print(i)

if (("check" in i) or ("show" in i) or ("update" in i) or ("is" in i) or ("tell" in i)) and ((("date" in i) and ("today" in i)) or ("date" in i) or (("today's" in i) and ("date" in i))):
    pyttsx3.speak("Here is today's date.")
    print(sp.getoutput("date"))
else:
    print("We don't support it.")

Output:

(base) ~python3.8 voice_control.py
Welcome to my tools.

We got you.. Please wait while we are working on your requirements.
please show me today's date
Tue Sep  8 19:45:27 IST 2020

Note:

  1. This code is working fine on my MacOS version: 10.15.6 (19G2021) command line as shown in the output above.
  2. Also, working fine in the Jupyter IDE. Please refer link
  3. But not working in Visual Studio Code. Getting below error-
(base) ~python3.8 voice_control.py 
Welcome to my tools.

We got you.. Please wait while we are working on your requirements.
Traceback (most recent call last):
  File "voice_control.py", line 16, in <module>
    i=r.recognize_google(audio,language='en-US')
  File "/Users/hdogra/anaconda3/lib/python3.8/site-packages/speech_recognition/__init__.py", line 858, in recognize_google
    if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError

I would recommend running your code in different platform or IDEs.

elitex45 commented 3 years ago

speech_recognition.UnknownValueError is just for noises use try exception like this:

try: query = r.recognize_google(audio, language='en') except Exception as e: return "None"

this really worked thanks

DenisBurimov commented 3 years ago

Hi, everyone! I've tried everything, that I read above) But in my case, the problem was in choosing microphone. It just was wrong device, because in devices list was 4 similar devices.

import speech_recognition as sr
# for index, name in enumerate(sr.Microphone.list_microphone_names()):
#     print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name))

record = sr.Recognizer()
with sr.Microphone(device_index=1) as source:
    print("Произнесите команду!")
    audio = record.listen(source)
    print("Команда получена")

try:
    # result = record.recognize_google(audio, language="en-EN", show_all=True)
    result = record.recognize_google(audio, language="ru-RU")
    print("Tried")
    print(result)
except sr.UnknownValueError:
    print("Голос не был распознан")
except sr.RequestError:
    print(sr.RequestError)
LofyVintaj commented 2 years ago

This error is due to the fact that the voice is not recognized, or rather its content, perhaps something with a micro, etc. In this case, it is better to write except sr.UnknownValueError:

hiyamgh commented 1 year ago

print("I am here")

You saved my life. Thank you

ghost commented 1 year ago

speech_recognition.UnknownValueError is just for noises use try exception like this:

try: query = r.recognize_google(audio, language='en') except Exception as e: return "None"

try: query = r.recognize_google(audio, language='en') except Exception as e: print "Not speak in this time period"

kentchesley commented 7 months ago

I experienced this error. For me it occurred because there were no spoken words in my audio file.