Link to home
Start Free TrialLog in
Avatar of WillNy3
WillNy3

asked on

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!
ASKER CERTIFIED SOLUTION
Avatar of Joseph Gan
Joseph Gan
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of WillNy3
WillNy3

ASKER

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 -.-