AttributeError: 'URLError' object has no attribute 'code'

I am working on a little script which transcribes WAV files located in a local directory using a local host running SpeechRecognition (https://pypi.python.org/pypi/SpeechRecognition/ ). However, for some reason I'm getting an odd error of AttributeError: 'URLError' object has no attribute 'code'.

Here is a trimmed down traceback:

Traceback (most recent call last):
  File "C:\Python34\lib\urllib\request.py", line 1182, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
  File "C:\Python34\lib\http\client.py", line 1088, in request
    self._send_request(method, url, body, headers)
  File "C:\Python34\lib\socket.py", line 494, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "C:\Python34\lib\socket.py", line 533, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\urllib\request.py", line 1210, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "C:\Python34\lib\urllib\request.py", line 1184, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/William/Documents/FlashBulb/userMedia/server.py", line 86, in do_POST
    recognize(output_file)
  File "C:/Users/William/Documents/FlashBulb/userMedia/server.py", line 29, in recognize
    print("Google Speech Recognition thinks you said " + r.recognize_google(audio))
  File "C:\Python34\lib\site-packages\speech_recognition\__init__.py", line 408, in recognize_google
    raise RequestError("recognition connection failed: {0}".format(getattr(e, "reason", "status {0}".format(e.code)))) # use getattr to be compatible with Python 2.6
AttributeError: 'URLError' object has no attribute 'code'
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 62409)


And here is the script:

#!/usr/bin/python

import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import cgi
import speech_recognition as sr

HOST_NAME = 'localhost'
PORT_NUMBER = 10000
ASSETS_DIR = 'assets'

if not os.path.exists(ASSETS_DIR):
    os.mkdir(ASSETS_DIR)


def recognize(wav_file):
    print("Recognizing ", wav_file)
    r = sr.Recognizer()
    r.energy_threshold = 350
    r.pause_threshold = 10.0
    with sr.WavFile(wav_file) as source:
        audio = r.record(source)

    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        print("Google Speech Recognition thinks you said " + r.recognize_google(audio))
        os.remove(wav_file)

    except sr.UnknownValueError as e:
        print(e)
        print("Google Speech Recognition could not understand audio")
        os.remove(wav_file)
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))


class MyHandler(BaseHTTPRequestHandler):
    previous_wav = ""

    def do_GET(self):

        if self.path == "/":
            self.path = "/index.html"

        try:
            sendReply = False
            if self.path.endswith(".html"):
                mimetype = 'text/html'
                sendReply = True
            if self.path.endswith(".js"):
                mimetype = 'application/javascript'
                sendReply = True

            if sendReply:
                # Open the static file requested and send it
                f = open(os.path.join(os.curdir + os.sep + self.path))
                self.send_response(200)
                self.send_header('Content-type', mimetype)
                self.end_headers()
                self.wfile.write(bytes(f.read(), 'utf-8'))
                f.close()
                return

        except IOError:
            self.send_error(404, 'File Not Found: %s' % self.path)

    def do_POST(self):

        if self.path == '/upload':
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={
                    'REQUEST_METHOD':'POST',
                    'CONTENT_TYPE':self.headers['Content-Type'],
                })

            filename = form.getvalue("fname").strip()
            data = form['data'].file.read()
            output_file = os.path.join(os.curdir, ASSETS_DIR, filename)
            open(output_file, "wb").write(data)
            if str(output_file) != MyHandler.previous_wav:
                recognize(output_file)
            MyHandler.previous_wav = str(output_file)
            self.send_response(200)


if __name__ == '__main__':

    server_class = HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))

Open in new window


I would of ran a set trace  but I'm not sure how to do that since it would interrupt the post process. I haven't seen an issue like this before so I'm not sure exactly what is happening. Any help would be awesome!
LVL 1
WillNy3Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Joseph GanSystem AdminCommented:
Try something after this:     except sr.UnknownValueError as e:

return_code = e.code
         if hasattr(e, 'reason'):
             #HTTPError and URLError all have reason attribute.
             print 'We failed to reach a server.'
             print 'Reason: ', e.reason
             print 'code: ', e.code
             return_html = e.reason
         elif hasattr(e, 'code'):
             #Only HTTPError has code attribute.
             print 'The server couldn\'t fulfill the request.'
             print 'Error code: ', e.code
     else:
         # everything is fine

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
WillNy3Author Commented:
Thanks for your help. I still have no ******* clue what happened. This morning it just worked, exact same code, no changes, nothing. I didn't even add in your additional error handling. Gotta love debugging -.-
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.