如今,听到某人与不在场的人交谈并不奇怪。我们向Alexa询问天气情况并将恒温器的温度降低。然后,我们问Siri我们当天的日程安排是什么,并打电话给人们。我们现在比以往任何时候都使用语音和语音接口技术。我无法想象再做手动了!这真的是未来。
- 福布斯
介绍
谁不想拥有一个总是倾听你的电话,预测你的每一个需要,并在必要时采取行动的助手?基于人工智能的语音助手,现在可以享受这种奢侈品。
语音助手有一些小包装,可以在听到您的命令后执行各种操作。他们可以打开灯,回答问题,播放音乐,下订单和做各种基于AI的东西。
语音助理不要与虚拟助手混淆,虚拟助手是远程工作的人,因此可以处理各种任务。相反,语音助理是基于技术的。随着语音助理变得更加强大,它们在个人和商业领域的实用性也将增长。

什么是语音助手?
一个语音助手或智能个人助理是可以基于通过解释人的讲话,并通过合成的声音做出反应,即口头命令的个人执行任务或服务的软件代理。用户可以通过语音询问助手的问题,控制家庭自动化设备和媒体播放,并通过口头命令管理其他基本任务,如电子邮件,待办事项列表,打开或关闭任何应用程序等。
让我举一个Braina(脑人工)的例子,这是一个智能个人助理,人类语言界面,自动化和Windows PC 语音识别软件。Braina是一款多功能人工智能软件,可让您使用世界上大多数语言的语音命令与计算机进行交互。Braina还允许您准确地将语音转换为世界上100多种不同语言的文本。
最近,在Apple整合了最令人惊讶的虚拟助手 - Siri后,语音助手获得了主要平台,Siri正式成为Apple Inc.的一部分。但最大的演变时间表始于1962年西雅图世界博览会上的IBM展示独特的设备称为Shoebox。它是鞋盒的实际尺寸,可以执行科学功能,可以感知16个单词,并且可以用人类可识别的声音说出0到9个数字。
在20世纪70年代期间,宾夕法尼亚州匹兹堡的卡内基梅隆大学的研究人员在美国国防部及其国防高级研究计划局(DARPA)的大力帮助下制造了哈比。它可以理解近1000个单词,这大约是一个三岁孩子的词汇。
像苹果公司和IBM这样的大型组织在90年代早些时候开始制造利用语音确认的东西。1993年,Macintosh开始使用带 有PlainTalk的Macintosh PC构建语音识别。
1997年4月,Dragon NaturallySpeaking是第一个可以理解大约100个单词并将其转换为可读内容的不断听写产品。
话虽如此,建立一个简单的基于语音的桌面/笔记本电脑助手有多么酷,有能力:
- 在浏览器中打开subreddit。
- 在浏览器中打开任何网站。
- 发送电子邮件给您的联系人。
- 启动任何系统应用程序。
- 告诉你几乎所有城市的当前天气和温度
- 告诉你当前时间。
- 问候
- 在VLC媒体播放器上播放一首歌(当然,您需要在笔记本电脑/台式机中安装VLC媒体播放器)
- 更改桌面墙纸。
- 告诉你最新消息。
- 告诉你几乎所有你问的事。
因此,在本文中,我们将构建一个基于语音的应用程序,它能够完成上述所有任务。但首先,看看下面我在与桌面语音助手交互时制作的视频,我称她为索菲亚。
我希望你们喜欢上面与索菲亚互动的视频。现在让我们开始构建这个很酷的东西……
依赖性和要求:
系统要求:Python 2.7,Spyder IDE,MacOS Mojave(版本10.14)
安装所有这些python库:
pip install SpeechRecognition
pip install beautifulsoup4
pip install vlc
pip install youtube-dl
pip install pyowm
pip install wikipedia
让我们开始使用python构建我们的桌面语音助手
首先导入所有必需的库:
import speech_recognition as srimport osimport sysimport reimport webbrowserimport smtplibimport requestsimportsubprocess from pyowm import OWMimport youtube_dlimport vlcimport urllibimport urllib2import jsonfrom bs4 import BeautifulSoup as soupfrom urllib2 import urlopenimport wikipediaimport randomfrom time import strftime
为了让我们的语音助手能够执行上述所有功能,我们必须在一种方法中对每种功能的逻辑进行编码。
所以我们的第一步是创建解释用户语音响应的方法。
def myCommand():r = sr.Recognizer()with sr.Microphone() as source:print('Say something...')r.pause_threshold = 1r.adjust_for_ambient_noise(source, duration=1)audio = r.listen(source)try:command = r.recognize_google(audio).lower()print('You said: ' + command + '\n')#loop back to continue to listen for commands if unrecognizable speech is receivedexcept sr.UnknownValueError:print('....')command = myCommand();return command
接下来,创建一个将文本转换为语音的方法。
def sofiaResponse(audio):print(audio)for line in audio.splitlines():os.system("say " + audio)
现在创建一个循环以继续执行多个命令。方法assistant()内部传递用户命令(myCommand())作为参数。
while True:assistant(myCommand())
我们的下一步是创建与每个功能相对应的多个if语句。那么让我们看看如何在每个命令的if语句中创建这些小模块。
- 在浏览器中打开subreddit Reddit 。
用户将给出任何命令来打开Reddit中的任何subreddit,命令应为“Hey Sofia!你能打开Reddit subreddit_name “ 吗?只应使用斜体粗体短语。您可以使用任何类型的前缀,只需处理斜体粗体短语。
工作原理:如果您在命令中说了> open reddit,那么它将使用re.search()在user命令中搜索subreddit名称。该版(Subreddit)将使用搜索> www.reddit.com和使用蟒蛇的Webbrowser module.The浏览器将得到打开> 的Webbrowser模块提供了一个高层次的接口,以允许显示基于Web的文档给用户。
if 'open reddit' in command:reg_ex = re.search('open reddit (.*)', command)url = 'https://www.reddit.com/'if reg_ex:subreddit = reg_ex.group(1)url = url + 'r/' + subredditwebbrowser.open(url)sofiaResponse('The Reddit content has been opened for you Sir.')
因此,上面的代码将在您的默认浏览器中打开您想要的Reddit。
2.在浏览器中打开任何网站。
你可以打开任何网站只是说“打开website.com”或“打开website.org”。
例如:“请打开facebook.com”或“嘿,你能打开linkedin.com”这样你可以要求索菲亚为你打开任何网站。
工作原理:如果你在命令中说了> open这个词,那么它将使用re.search()在user命令中搜索网站名称。接下来,它会将网站名称附加到> https:// www。并使用> webbrowser模块在浏览器中打开完整的URL。
elif 'open' in command:reg_ex = re.search('open (.+)', command)if reg_ex:domain = reg_ex.group(1)print(domain)url = 'https://www.' + domainwebbrowser.open(url)sofiaResponse('The website you have requested has been opened for you Sir.')else:pass
3.发送电子邮件。
您也可以要求桌面助理发送电子邮件。
工作原理:如果你在命令中说过> 电子邮件,那么机器人会要求收据,如果我的响应是rajat,机器人将使用pthons smtplib库。该> 的smtplib模块> 定义了可用于发送邮件到任何互联网设备使用SMTP或ESMTP监听守护SMTP客户端会话对象。使用SMTP服务器使用Python的smtplib发送邮件。首先,它将使用> smtplib.SMTP()初始化gmail SMTP ,然后使用> ehlo()函数识别服务器,然后加密会话> starttls(),然后使用> login()登录到您的邮箱,然后使用> sendmail()发送邮件> 。
elif 'email' in command:sofiaResponse('Who is the recipient?')recipient = myCommand()if 'rajat' in recipient:sofiaResponse('What should I say to him?')content = myCommand()mail = smtplib.SMTP('smtp.gmail.com', 587)mail.ehlo()mail.starttls()mail.login('your_email_address', 'your_password')mail.sendmail('sender_email', 'receiver_email', content)mail.close()sofiaResponse('Email has been sent successfuly. You can check your inbox.')else:sofiaResponse('I don\'t know what you mean!')
4.启动任何系统应用程序。
说“启动日历”或“你能发动skype”或“索菲亚发射查找器”等,索菲亚将为您推出该系统应用程序。
工作原理:如果您在命令中说了“ > 启动 ”一词,那么它将使用re.search()在用户命令中搜索应用程序名称(如果它存在于您的系统中)。然后它会将后缀“.app”附加到应用程序名称。现在您的应用程序名称例如是calender.app(在macOS中,可执行文件以扩展名.app结尾,与Windows不同,以.exe结尾)。因此,可执行的应用程序名称将使用python subprocess的Popen()函数启动。该> 子模块,您可以开始从你的Python程序的新应用。
elif 'launch' in command:reg_ex = re.search('launch (.*)', command)if reg_ex:appname = reg_ex.group(1)appname1 = appname+".app"subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)sofiaResponse('I have launched the desired application')
5.告诉你几乎任何城市的当前天气和温度。
索菲亚还可以告诉您世界上任何城市的天气,最高和最低温度。用户只需说出“伦敦目前的天气是什么”或“告诉我德里当前的天气”。
工作原理:如果您在命令中说过> 当前天气,那么它将使用re.search()搜索城市名称。我用> pythons pyowm库来获取任何城市的天气。get_status()会告诉你天气状况,如阴霾,阴天,下雨等,get_temperature()会告诉你城市的最高和最低温度。
elif 'current weather' in command:reg_ex = re.search('current weather in (.*)', command)if reg_ex:city = reg_ex.group(1)owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')obs = owm.weather_at_place(city)w = obs.get_weather()k = w.get_status()x = w.get_temperature(unit='celsius')sofiaResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))
6.告诉你当前的时间。
“索菲亚你能告诉我当前的时间吗?”或“现在几点了?”索菲亚会告诉你当前的时区。
它是如何工作的:非常简单
elif 'time' in command:import datetimenow = datetime.datetime.now()sofiaResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))
7.问候/请假
说“你好索菲亚”来迎接你的语音助手,或者当你希望程序终止时,请说“关闭索菲亚”或“索菲亚请关机”等。
它是如何工作的:如果你在命令中说了> hello这个词,那么根据一天的时间,机器人会问候用户。如果时间超过中午12点,机器人将回复“你好先生。下午好,“同样如果时间超过6 ck pm,机器人将回应”你好先生。晚上好”。当你将命令作为shutdown时,将调用> sys.exit()来终止程序。
#Greet Sofiaelif 'hello' in command:day_time = int(strftime('%H'))if day_time < 12:sofiaResponse('Hello Sir. Good morning')elif 12 <= day_time < 18:sofiaResponse('Hello Sir. Good afternoon')else:sofiaResponse('Hello Sir. Good evening')#to terminate the programelif 'shutdown' in command:sofiaResponse('Bye bye Sir. Have a nice day')sys.exit()
8.在VLC媒体播放器上播放一首歌
此功能允许您的语音机器人在VLC媒体播放器中播放您想要的歌曲。用户会说“索菲亚给我播放一首歌”,机器人会问“我应该唱什么歌?”?只需说出歌曲的名称,索菲亚就会从你本地驱动器中的YouTube下载歌曲,在VLC媒体播放器上播放该歌曲,如果再次播放歌曲,之前下载的歌曲将自动删除。
它是如何工作的:如果你说这个短语在你的命令中> 播放一首歌,那么它会问你要播放什么视频歌。您将要求的歌曲将在youtube.com中搜索,如果找到,将使用pythons youtube_dl库将歌曲下载到您的本地目录中。在> YouTube的-DL是一个命令行程序,从YouTube.com和一些更多的网站下载视频。现在,这首歌将在使用蟒蛇> VLC库下载后播放,播放(path_to__videosong)模块实际播放该歌曲。
现在,如果您下次要求任何其他歌曲,则将刷新本地目录并在该目录中下载新歌曲。
elif 'play me a song' in command:path = '/Users/nageshsinghchauhan/Documents/videos/'folder = pathfor the_file in os.listdir(folder):file_path = os.path.join(folder, the_file)try:if os.path.isfile(file_path):os.unlink(file_path)except Exception as e:print(e)sofiaResponse('What song shall I play Sir?')mysong = myCommand()if mysong:flag = 0url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+')response = urllib2.urlopen(url)html = response.read()soup1 = soup(html,"lxml")url_list = []for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}):if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):flag = 1final_url = 'https://www.youtube.com' + vid['href']url_list.append(final_url)url = url_list[0]ydl_opts = {}os.chdir(path)with youtube_dl.YoutubeDL(ydl_opts) as ydl:ydl.download([url])vlc.play(path)if flag == 0:sofiaResponse('I have not found anything in Youtube ')
9.更改桌面壁纸。
你们也可以使用此功能更改桌面壁纸。当您说“更换壁纸”或“索菲亚请更换壁纸”之类的机器人时,机器人将从unsplash.com下载随机壁纸并将其设置为您的桌面背景。
工作原理:如果您在命令中说过> 更改壁纸这一短语,程序将从unsplash.com下载随机壁纸,将其存储在本地目录中,并使用subprocess.call()将其设置为桌面壁纸。我使用了unsplash API来访问其内容。
现在,如果下次再次要求更改壁纸时,将刷新本地目录,并在该目录中下载新壁纸。
elif 'change wallpaper' in command:folder = '/Users/nageshsinghchauhan/Documents/wallpaper/'for the_file in os.listdir(folder):file_path = os.path.join(folder, the_file)try:if os.path.isfile(file_path):os.unlink(file_path)except Exception as e:print(e)api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.comf = urllib2.urlopen(url)json_string = f.read()f.close()parsed_json = json.loads(json_string)photo = parsed_json['urls']['full']urllib.urlretrieve(photo, "/Users/nageshsinghchauhan/Documents/wallpaper/a") # Location where we download the image to.subprocess.call(["killall Dock"], shell=True)sofiaResponse('wallpaper changed successfully')
10.告诉你最新消息。
索菲亚还可以告诉您最新的新闻更新。用户只需说“索菲亚今天的头条新闻是什么?”或“告诉我今天的新闻”。
工作原理:如果您在命令中说过> 今天的短语> ,那么它将使用Google News RSS()中的> Beautiful Soup来抓取数据并为您阅读。因为我已将新闻限制数限制为15。
elif 'news for today' in command:try:news_url="https://news.google.com/news/rss"Client=urlopen(news_url)xml_page=Client.read()Client.close()soup_page=soup(xml_page,"xml")news_list=soup_page.findAll("item")for news in news_list[:15]:sofiaResponse(news.title.text.encode('utf-8'))except Exception as e:print(e)
11.告诉你几乎所有你问的事。
你的机器人可以获取你问她几乎任何事情的细节。比如“Sofia告诉我有关Google的信息”或“请告诉我有关超级计算机的信息”或“请告诉我有关互联网的信息”。所以你可以看到你可以询问几乎任何事情。
工作原理:如果你在命令中> 告诉我这个短语,那么它将使用re.search()在user命令中搜索关键字。使用pythons维基百科库,它将搜索该主题并提取前500个字符(如果你没有指定限制,机器人将为你读取整个页面)。> Wikipedia是一个Python库,可以轻松访问和解析来自维基百科的数据。
elif 'tell me about' in command:reg_ex = re.search('tell me about (.*)', command)try:if reg_ex:topic = reg_ex.group(1)ny = wikipedia.page(topic)sofiaResponse(ny.content[:500].encode('utf-8'))except Exception as e:sofiaResponse(e)
让我们把所有东西放在一起
import speech_recognition as srimport osimport sysimport reimport webbrowserimport smtplibimport requestsimport subprocessfrom pyowm import OWMimport youtube_dlimport vlcimport urllibimport urllib2import jsonfrom bs4 import BeautifulSoup as soupfrom urllib2 import urlopenimport wikipediaimport randomfrom time import strftimedef sofiaResponse(audio):"speaks audio passed as argument"print(audio)for line in audio.splitlines():os.system("say " + audio)def myCommand():"listens for commands"r = sr.Recognizer()with sr.Microphone() as source:print('Say something...')r.pause_threshold = 1r.adjust_for_ambient_noise(source, duration=1)audio = r.listen(source)try:command = r.recognize_google(audio).lower()print('You said: ' + command + '\n')#loop back to continue to listen for commands if unrecognizable speech is receivedexcept sr.UnknownValueError:print('....')command = myCommand();return commanddef assistant(command):"if statements for executing commands"#open subreddit Redditif 'open reddit' in command:reg_ex = re.search('open reddit (.*)', command)url = 'https://www.reddit.com/'if reg_ex:subreddit = reg_ex.group(1)url = url + 'r/' + subredditwebbrowser.open(url)sofiaResponse('The Reddit content has been opened for you Sir.')elif 'shutdown' in command:sofiaResponse('Bye bye Sir. Have a nice day')sys.exit()#open websiteelif 'open' in command:reg_ex = re.search('open (.+)', command)if reg_ex:domain = reg_ex.group(1)print(domain)url = 'https://www.' + domainwebbrowser.open(url)sofiaResponse('The website you have requested has been opened for you Sir.')else:pass#greetingselif 'hello' in command:day_time = int(strftime('%H'))if day_time < 12:sofiaResponse('Hello Sir. Good morning')elif 12 <= day_time < 18:sofiaResponse('Hello Sir. Good afternoon')else:sofiaResponse('Hello Sir. Good evening')elif 'help me' in command:sofiaResponse("""You can use these commands and I'll help you out:1. Open reddit subreddit : Opens the subreddit in default browser.2. Open xyz.com : replace xyz with any website name3. Send email/email : Follow up questions such as recipient name, content will be asked in order.4. Current weather in {cityname} : Tells you the current condition and temperture5. Hello6. play me a video : Plays song in your VLC media player7. change wallpaper : Change desktop wallpaper8. news for today : reads top news of today9. time : Current system time10. top stories from google news (RSS feeds)11. tell me about xyz : tells you about xyz""")#jokeelif 'joke' in command:res = requests.get('https://icanhazdadjoke.com/',headers={"Accept":"application/json"})if res.status_code == requests.codes.ok:sofiaResponse(str(res.json()['joke']))else:sofiaResponse('oops!I ran out of jokes')#top stories from google newselif 'news for today' in command:try:news_url="https://news.google.com/news/rss"Client=urlopen(news_url)xml_page=Client.read()Client.close()soup_page=soup(xml_page,"xml")news_list=soup_page.findAll("item")for news in news_list[:15]:sofiaResponse(news.title.text.encode('utf-8'))except Exception as e:print(e)#current weatherelif 'current weather' in command:reg_ex = re.search('current weather in (.*)', command)if reg_ex:city = reg_ex.group(1)owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')obs = owm.weather_at_place(city)w = obs.get_weather()k = w.get_status()x = w.get_temperature(unit='celsius')sofiaResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))#timeelif 'time' in command:import datetimenow = datetime.datetime.now()sofiaResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))elif 'email' in command:sofiaResponse('Who is the recipient?')recipient = myCommand()if 'rajat' in recipient:sofiaResponse('What should I say to him?')content = myCommand()mail = smtplib.SMTP('smtp.gmail.com', 587)mail.ehlo()mail.starttls()mail.login('your_email_address', 'your_password')mail.sendmail('sender_email', 'receiver_email', content)mail.close()sofiaResponse('Email has been sent successfuly. You can check your inbox.')else:sofiaResponse('I don\'t know what you mean!')#launch any applicationelif 'launch' in command:reg_ex = re.search('launch (.*)', command)if reg_ex:appname = reg_ex.group(1)appname1 = appname+".app"subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)sofiaResponse('I have launched the desired application')#play youtube songelif 'play me a song' in command:path = '/Users/nageshsinghchauhan/Documents/videos/'folder = pathfor the_file in os.listdir(folder):file_path = os.path.join(folder, the_file)try:if os.path.isfile(file_path):os.unlink(file_path)except Exception as e:print(e)sofiaResponse('What song shall I play Sir?')mysong = myCommand()if mysong:flag = 0url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+')response = urllib2.urlopen(url)html = response.read()soup1 = soup(html,"lxml")url_list = []for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}):if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):flag = 1final_url = 'https://www.youtube.com' + vid['href']url_list.append(final_url)url = url_list[0]ydl_opts = {}os.chdir(path)with youtube_dl.YoutubeDL(ydl_opts) as ydl:ydl.download([url])vlc.play(path)if flag == 0:sofiaResponse('I have not found anything in Youtube ')#change wallpaperelif 'change wallpaper' in command:folder = '/Users/nageshsinghchauhan/Documents/wallpaper/'for the_file in os.listdir(folder):file_path = os.path.join(folder, the_file)try:if os.path.isfile(file_path):os.unlink(file_path)except Exception as e:print(e)api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.comf = urllib2.urlopen(url)json_string = f.read()f.close()parsed_json = json.loads(json_string)photo = parsed_json['urls']['full']urllib.urlretrieve(photo, "/Users/nageshsinghchauhan/Documents/wallpaper/a") # Location where we download the image to.subprocess.call(["killall Dock"], shell=True)sofiaResponse('wallpaper changed successfully')#askme anythingelif 'tell me about' in command:reg_ex = re.search('tell me about (.*)', command)try:if reg_ex:topic = reg_ex.group(1)ny = wikipedia.page(topic)sofiaResponse(ny.content[:500].encode('utf-8'))except Exception as e:print(e)sofiaResponse(e)sofiaResponse('Hi User, I am Sofia and I am your personal voice assistant, Please give a command or say "help me" and I will tell you what all I can do for you.')#loop to continue executing multiple commandswhile True:assistant(myCommand())
所以你已经看到了通过编写简单的python代码行,我们可以创建一个非常酷的基于语音的桌面/笔记本电脑助手。除了这些功能外,您还可以在语音助手中添加许多不同的功能。
请注意,一旦开始执行程序,在与语音助手交互时要大声清晰,因为如果您的语音不清楚,您的语音助手可能无法正确解释您。
结论:未来是什么
在整个计算历史中,用户界面已变得越来越自然。屏幕和键盘是朝着这个方向迈出的一步。鼠标和图形用户界面是另一个。触摸屏是最新的发展。下一步很可能包括增强现实,手势和语音命令的混合。毕竟,提问或谈话通常比输入内容或在在线表单中输入多个详细信息更容易。
一个人与语音激活设备交互的次数越多,系统根据收到的信息识别的趋势和模式就越多。然后,该数据可用于确定用户偏好和品味,这是使家庭更聪明的长期卖点。谷歌和亚马逊正在寻求整合能够分析和响应人类情感的语音人工智能。
我希望你们喜欢阅读这篇文章。在评论部分分享您的想法/意见/疑问。你可以通过LinkedIn与我联系。
