- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
当我尝试运行我的 python 文件时,我在 python3 和 python on raspbian 上都安装了语音识别,我收到以下错误
(hhsmartmirror) pi@raspberrypi:~/AI-Smart-Mirror $ python bot.py Traceback (most recent call last): File "bot.py", line 13, in from speech import Speech File "/home/pi/AI-Smart-Mirror/speech.py", line 3, in import speech_recognition as sr ImportError: No module named speech_recognition
代码文件:
#bot.py
#speechrecognition, pyaudio, brew install portaudio
import sys
sys.path.append("./")
import requests
import datetime
import dateutil.parser
import json
import traceback
from nlg import NLG
from speech import Speech
from knowledge import Knowledge
from vision import Vision
my_name = "Aaron"
launch_phrase = "ok mirror"
use_launch_phrase = True
weather_api_token = "Bearer d1e49b263abd08d422822b72b4c3eec4"
wit_ai_token = "Bearer CL47LPKJWMNDNWPVMY4RPTZR3JDCZ2GZ"
debugger_enabled = True
camera = 0
class Bot(object):
def __init__(self):
self.nlg = NLG(user_name=my_name)
self.speech = Speech(launch_phrase=launch_phrase, debugger_enabled=debugger_enabled)
self.knowledge = Knowledge(weather_api_token)
self.vision = Vision(camera=camera)
def start(self):
"""
Main loop. Waits for the launch phrase, then decides an action.
:return:
"""
while True:
requests.get("http://localhost:8080/clear")
if self.vision.recognize_face():
print "Found face"
if use_launch_phrase:
recognizer, audio = self.speech.listen_for_audio()
if self.speech.is_call_to_action(recognizer, audio):
self.__acknowledge_action()
self.decide_action()
else:
self.decide_action()
def decide_action(self):
"""
Recursively decides an action based on the intent.
:return:
"""
recognizer, audio = self.speech.listen_for_audio()
# received audio data, now we'll recognize it using Google Speech Recognition
speech = self.speech.google_speech_recognition(recognizer, audio)
if speech is not None:
try:
r = requests.get('https://api.wit.ai/message?v=20160918&q=%s' % speech,
headers={"Authorization": wit_ai_token})
print r.text
json_resp = json.loads(r.text)
entities = None
intent = None
if 'entities' in json_resp and 'Intent' in json_resp['entities']:
entities = json_resp['entities']
intent = json_resp['entities']['Intent'][0]["value"]
print intent
if intent == 'greeting':
self.__text_action(self.nlg.greet())
elif intent == 'snow white':
self.__text_action(self.nlg.snow_white())
elif intent == 'weather':
self.__weather_action(entities)
elif intent == 'news':
self.__news_action()
elif intent == 'maps':
self.__maps_action(entities)
elif intent == 'holidays':
self.__holidays_action()
elif intent == 'appearance':
self.__appearance_action()
elif intent == 'user status':
self.__user_status_action(entities)
elif intent == 'user name':
self.__user_name_action()
elif intent == 'personal status':
self.__personal_status_action()
elif intent == 'joke':
self.__joke_action()
elif intent == 'insult':
self.__insult_action()
return
elif intent == 'appreciation':
self.__appreciation_action()
return
else: # No recognized intent
self.__text_action("I'm sorry, I don't know about that yet.")
return
except Exception as e:
print "Failed wit!"
print(e)
traceback.print_exc()
self.__text_action("I'm sorry, I couldn't understand what you meant by that")
return
self.decide_action()
def __joke_action(self):
joke = self.nlg.joke()
if joke is not None:
self.__text_action(joke)
else:
self.__text_action("I couldn't find any jokes")
def __user_status_action(self, nlu_entities=None):
attribute = None
if (nlu_entities is not None) and ("Status_Type" in nlu_entities):
attribute = nlu_entities['Status_Type'][0]['value']
self.__text_action(self.nlg.user_status(attribute=attribute))
def __user_name_action(self):
if self.nlg.user_name is None:
self.__text_action("I don't know your name. You can configure it in bot.py")
self.__text_action(self.nlg.user_name)
def __appearance_action(self):
requests.get("http://localhost:8080/face")
def __appreciation_action(self):
self.__text_action(self.nlg.appreciation())
def __acknowledge_action(self):
self.__text_action(self.nlg.acknowledge())
def __insult_action(self):
self.__text_action(self.nlg.insult())
def __personal_status_action(self):
self.__text_action(self.nlg.personal_status())
def __text_action(self, text=None):
if text is not None:
requests.get("http://localhost:8080/statement?text=%s" % text)
self.speech.synthesize_text(text)
def __news_action(self):
headlines = self.knowledge.get_news()
if headlines:
requests.post("http://localhost:8080/news", data=json.dumps({"articles":headlines}))
self.speech.synthesize_text(self.nlg.news("past"))
interest = self.nlg.article_interest(headlines)
if interest is not None:
self.speech.synthesize_text(interest)
else:
self.__text_action("I had some trouble finding news for you")
def __weather_action(self, nlu_entities=None):
current_dtime = datetime.datetime.now()
skip_weather = False # used if we decide that current weather is not important
weather_obj = self.knowledge.find_weather()
temperature = weather_obj['temperature']
icon = weather_obj['icon']
wind_speed = weather_obj['windSpeed']
weather_speech = self.nlg.weather(temperature, current_dtime, "present")
forecast_speech = None
if nlu_entities is not None:
if 'datetime' in nlu_entities:
if 'grain' in nlu_entities['datetime'][0] and nlu_entities['datetime'][0]['grain'] == 'day':
dtime_str = nlu_entities['datetime'][0]['value'] # 2016-09-26T00:00:00.000-07:00
dtime = dateutil.parser.parse(dtime_str)
if current_dtime.date() == dtime.date(): # hourly weather
forecast_obj = {'forecast_type': 'hourly', 'forecast': weather_obj['daily_forecast']}
forecast_speech = self.nlg.forecast(forecast_obj)
elif current_dtime.date() < dtime.date(): # sometime in the future ... get the weekly forecast/ handle specific days
forecast_obj = {'forecast_type': 'daily', 'forecast': weather_obj['weekly_forecast']}
forecast_speech = self.nlg.forecast(forecast_obj)
skip_weather = True
if 'Weather_Type' in nlu_entities:
weather_type = nlu_entities['Weather_Type'][0]['value']
print weather_type
if weather_type == "current":
forecast_obj = {'forecast_type': 'current', 'forecast': weather_obj['current_forecast']}
forecast_speech = self.nlg.forecast(forecast_obj)
elif weather_type == 'today':
forecast_obj = {'forecast_type': 'hourly', 'forecast': weather_obj['daily_forecast']}
forecast_speech = self.nlg.forecast(forecast_obj)
elif weather_type == 'tomorrow' or weather_type == '3 day' or weather_type == '7 day':
forecast_obj = {'forecast_type': 'daily', 'forecast': weather_obj['weekly_forecast']}
forecast_speech = self.nlg.forecast(forecast_obj)
skip_weather = True
weather_data = {"temperature": temperature, "icon": icon, 'windSpeed': wind_speed, "hour": datetime.datetime.now().hour}
requests.post("http://localhost:8080/weather", data=json.dumps(weather_data))
if not skip_weather:
self.speech.synthesize_text(weather_speech)
if forecast_speech is not None:
self.speech.synthesize_text(forecast_speech)
def __maps_action(self, nlu_entities=None):
location = None
map_type = None
if nlu_entities is not None:
if 'location' in nlu_entities:
location = nlu_entities['location'][0]["value"]
if "Map_Type" in nlu_entities:
map_type = nlu_entities['Map_Type'][0]["value"]
if location is not None:
maps_url = self.knowledge.get_map_url(location, map_type)
maps_action = "Sure. Here's a map of %s." % location
body = {'url': maps_url}
requests.post("http://localhost:8080/image", data=json.dumps(body))
self.speech.synthesize_text(maps_action)
else:
self.__text_action("I'm sorry, I couldn't understand what location you wanted.")
def __holidays_action(self):
holidays = self.knowledge.get_holidays()
next_holiday = self.__find_next_holiday(holidays)
requests.post("http://localhost:8080/holidays", json.dumps({"holiday": next_holiday}))
self.speech.synthesize_text(self.nlg.holiday(next_holiday['localName']))
def __find_next_holiday(self, holidays):
today = datetime.datetime.now()
for holiday in holidays:
date = holiday['date']
if (date['day'] > today.day) and (date['month'] > today.month):
return holiday
# next year
return holidays[0]
if __name__ == "__main__":
bot = Bot()
bot.start()
# speech.py
# speechrecognition, pyaudio, brew install portaudio
import speech_recognition as sr
import os
import requests
from gtts import gTTS
from pydub import AudioSegment
from pydub.playback import play
class Speech(object):
def __init__(self, launch_phrase="mirror mirror", debugger_enabled=False):
self.launch_phrase = launch_phrase
self.debugger_enabled = debugger_enabled
self.__debugger_microphone(enable=False)
def google_speech_recognition(self, recognizer, audio):
speech = None
try:
speech = recognizer.recognize_google(audio)
print("Google Speech Recognition thinks you said " + speech)
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))
return speech
def listen_for_audio(self):
# obtain audio from the microphone
r = sr.Recognizer()
m = sr.Microphone()
with m as source:
r.adjust_for_ambient_noise(source)
self.__debugger_microphone(enable=True)
print "I'm listening"
audio = r.listen(source)
self.__debugger_microphone(enable=False)
print "Found audio"
return r, audio
def is_call_to_action(self, recognizer, audio):
speech = self.google_speech_recognition(recognizer, audio)
if speech is not None and self.launch_phrase in speech.lower():
return True
return False
def synthesize_text(self, text):
tts = gTTS(text=text, lang='en')
tts.save("tmp.mp3")
song = AudioSegment.from_mp3("tmp.mp3")
play(song)
os.remove("tmp.mp3")
def __debugger_microphone(self, enable=True):
if self.debugger_enabled:
try:
r = requests.get("http://localhost:8080/microphone?enabled=%s" % str(enable))
if r.status_code != 200:
print("Used wrong endpoint for microphone debugging")
except Exception as e:
print(e)
最佳答案
如果您通过 Traceback 错误回读,基本上它是说在第 13 行,您成功从 speech 导入了 Speech,但在该文件内部它试图导入一个名为 speech_recognition 的模块。显然,由于我不知道的原因,它找不到该文件。
一些潜在的修复
鉴于我以前从未使用过这种模块,其他人可能会就修复提供一些更好的建议,但这是我最好的选择。
抱歉没能提供更多帮助!快乐编码。
关于python - 语音识别错误 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42328169/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!