[Tutor] IndexError: list index out of range

richard kappler richkappler at gmail.com
Sat Nov 30 02:17:54 CET 2013


I have a script that makes use of the Google speech recognition API as
follows:

import shlex

print " say something"
os.system('sox -r 16000 -t alsa default recording.flac silence 1 0.1 1% 1
1.5 1%')
cmd='wget -q -U "Mozilla/5.0" --post-file recording.flac
--header="Content-Type: audio/x-flac; rate=16000" -O - "
http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium"'


args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr=
subprocess.PIPE).communicate()

if not error:
a = eval(output)

#a = eval(open("data.txt").read())
confidence= a['hypotheses'][0]['confidence']
speech=a['hypotheses'][0]['utterance']
 print "you said:   ", speech, "  with  ",confidence,"confidence"

When I run that script by itself, it works fine.

When I insert the script into a larger program, I get the following error:

ERROR:
Traceback (most recent call last):
  File "inga.py", line 146, in <module>
    confidence= a['hypotheses'][0]['confidence']
IndexError: list index out of range

If I understand it correctly, the traceback is telling me that there is no
position [0] in my list, but I don't understand how that can be true. I'm
not using the variable "confidence" anywhere else in the program.

Here's the larger script/program into which the offending bits were
inserted, up to the point of the error:


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import aiml
import commands
import subprocess
import marshal
import datetime
import os
import os.path
from os.path import exists

#######################################################################
#################### read sensors #####################################
#######################################################################

############ environmental ############

def environRead():
    import serial
    from time import sleep

    sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
Temperature Humidity Light'.split())

    arduino = serial.Serial('/dev/ttyACM0', 9600)
    sleep(1)
    line = arduino.readline().strip()
    line = line.lstrip('{').rstrip('}').strip()

    envSense = {}
    for item in line.split(','):
        item = item.strip()
        key, value = item.split(':')
        key = key.strip()
        value = value.strip()
        envSense[key]=int(value)
    return envSense

######## end environmental #######################

########### somatic ##############################

def somaticRead():
    import psutil as ps

    cpu = ps.cpu_percent()
    mem = ps.virtual_memory()
    disk = ps.disk_usage('/')
# need code to strip % out of disk, leaving just hdd = and some number
# convert it all into a dictionary and return it

############ end somatic ##########################

#######################################################################
################ end sensor read ######################################
#######################################################################


#######################################################################
############## facerec ################################################
#######################################################################

from SimpleCV import Camera
import Image

# initialize camera
cam = Camera()

#snap a picture using the camera
img = cam.getImage()

# find the face
faces =
img.findHaarFeatures('/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml')

if faces:
    for face in faces:
        face.draw()
        # crop at box around detected face
cropped = face.crop()
# save to file for processing
im = cropped.copy()
im.save("temp.png")
#  process image - grayscale and size
im = Image.open("temp.png").convert("L")
im = im.resize((125, 150), Image.ANTIALIAS)
#delete the temp.png file
# filelist = [ f for f in os.listdir(".") if f.endswith(".png") ]
# for f in filelist:
#        os.remove(f)
#save image for face recognizer
        im.save("match.png")

subprocess.check_call(["python", "facerec", "match.png", "faceDbase", "18",
"3"])

filelist = [ f for f in os.listdir(".") if f.endswith(".png") ]
for f in filelist:
    os.remove(f)

tmp = open("namefile.txt")
name = tmp.read()
#print("Hello " + name)
greet = ("Hello " + name)
print greet
festivalCmd = '(SayText "%s")' % greet
subprocess.Popen(['/usr/bin/festival', '-b', festivalCmd])
# need to add functions for not finding or not recognizing a face

############# return from a function
#def get_face(arg):
#    some_variable = 10 * arg
#    return some_variable

#result = get_face(5)

########################################################################
############## end facerec #############################################
########################################################################

########################################################################
############## sphinx speech rec will go here ##########################
########################################################################

########################################################################
####################### Google speech rec ##############################
########################################################################

import shlex

print " say something"
os.system('sox -r 16000 -t alsa default recording.flac silence 1 0.1 1% 1
1.5 1%')
cmd='wget -q -U "Mozilla/5.0" --post-file recording.flac
--header="Content-Type: audio/x-flac; rate=16000" -O - "
http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium"'


args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr=
subprocess.PIPE).communicate()

if not error:
a = eval(output)

#a = eval(open("data.txt").read())
confidence= a['hypotheses'][0]['confidence']
speech=a['hypotheses'][0]['utterance']
 print "you said:   ", speech, "  with  ",confidence,"confidence"

########################################################################
################# end Google speech rec code ###########################
########################################################################

Any help would be greatly appreciated.

regards, Richard

-- 

*Mater tua criceta fuit, et pater tuo redoluit bacarum sambucus*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131129/e2a86a2c/attachment-0001.html>


More information about the Tutor mailing list