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.3k stars 2.39k forks source link

getting 403: forbidden when using google service account credentials json file #530

Open teodorkasap opened 3 years ago

teodorkasap commented 3 years ago

Steps to reproduce

  1. (How do you make the issue happen? Does it happen every time you try it?)

It happens every time I am trying to use my google service account. Without specifying environment variable (the service account) all works fine.

  1. (Make sure to go into as much detail as needed to reproduce the issue. Posting your code here can help us resolve the problem much faster!)

I am getting 403 forbidden when I use the service account json file, as described in the documentation of google and here. The Error message is below:

Could not request results from Google Speech Recognition                 servicerecognition request failed: Forbidden
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/site-packages/speech_recognition/__init__.py", line 840, in recognize_google
    response = urlopen(request, timeout=self.operation_timeout)
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/urllib/request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/urllib/request.py", line 569, in error
    return self._call_chain(*args)
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/urllib/request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/site-packages/speech_recognition/__init__.py", line 697, in threaded_listen
    if running[0]: callback(self, audio)
  File "/home/erolerten/Documents/personal/python projects/speech-recognition-test/guiPyQt2.py", line 99, in handler
    self.handleText(audio)
  File "/home/erolerten/Documents/personal/python projects/speech-recognition-test/guiPyQt2.py", line 136, in handleText
    raise(e)
  File "/home/erolerten/Documents/personal/python projects/speech-recognition-test/guiPyQt2.py", line 122, in handleText
    language=self.language
  File "/home/erolerten/anaconda3/envs/speech-recognition/lib/python3.7/site-packages/speech_recognition/__init__.py", line 842, in recognize_google
    raise RequestError("recognition request failed: {}".format(e.reason))
speech_recognition.RequestError: recognition request failed: Forbidden
  1. (If there are any files, like audio recordings, don't forget to include them.)

As I mentioned all works fine, when I use

def handleText(self, audio):

        try:
            text = self.r.recognize_google(
                audio)
            if text:
                textBuffer.append(text)
                print(text)
            else:
                print('something went wrong')

            # print(self.r.recognize_google(audio))
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition \
                service{0}".format(e))
            raise(e)

as soon as I add the environment variable like below:

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/home/erolerten/Documents/personal/python projects/speech-recognition-test/speech-to-text-test-293813-4d87993e1119.json"

and pass the environment variable as parameter like in the code below

def handleText(self, audio):

        try:
            text = self.r.recognize_google(
                audio,
                key="GOOGLE_APPLICATION_CREDENTIALS",
                language=self.language
                )
            if text:
                textBuffer.append(text)
                print(text)
            else:
                print('something went wrong')

            # print(self.r.recognize_google(audio))
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition \
                service{0}".format(e))
            raise(e)

I get the error I have pasted above

System information

(Delete all the statements that don't apply.)

My system is Ubuntu 18.04.05

My Python version is Python 3.7.1 (anaconda distribution)

My Pip version is pip 20.2.3.

My SpeechRecognition library version is 3.8.1.

My PyAudio library version is 0.2.11

My microphones are: (You can check this by running python -c "import speech_recognition as sr;print(sr.Microphone.list_microphone_names())".)

My working microphones are: ['HDA Intel HDMI: 0 (hw:0,3)', 'HDA Intel HDMI: 1 (hw:0,7)', 'HDA Intel HDMI: 2 (hw:0,8)', 'HDA Intel HDMI: 3 (hw:0,9)', 'HDA Intel HDMI: 4 (hw:0,10)', 'HDA Intel PCH: ALC3232 Analog (hw:1,0)', 'Logitech Mono H650e: USB Audio (hw:2,0)', 'hdmi', 'pulse', 'default']

I did not install PocketSphinx.

teodorkasap commented 3 years ago

I finally have it sorted out. for people like myself, who are not an expert in this field I would like to write it down below and close this ticket myself. the method I have mentioned about should actually look like the following:

def handleText(self, audio):

        try:
            text = self.r.recognize_google(
                audio,
                # key="GOOGLE_APPLICATION_CREDENTIALS",
                language=self.language
            )
            if text:
                textBuffer.append(text)
                print(text)
                self.statusBar().showMessage("received transcription \
                    from Google API")
            else:
                print('something went wrong')

            # print(self.r.recognize_google(audio))
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition \
                service{0}".format(e))
            raise(e)
teodorkasap commented 3 years ago

I believe it is this sleeplessness taking itst toll during the pandemic. I have copied and pasted the wrong code and put it to work as if it was the right one.. I have written the code below and it does not accept the credentials file as valid Json string.


def handleText(self, audio):

        try:
            text = self.r.recognize_google_cloud(
                audio,
                credentials_json="GOOGLE_APPLICATION_CREDENTIALS",
                language=self.language
            )
            if text:
                textBuffer.append(text)
                print(text)
                self.statusBar().showMessage("received transcription \
                    from Google API")
            else:
                print('something went wrong')

            # print(self.r.recognize_google(audio))
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition \
                service{0}".format(e))
            raise(e)

I have seen a similar issue which still hasn't been resolved so therefore I guess I should switch to using Google API without third-party Library