使用 PyAudio、语音识别、pyttsx3 和 SerpApi 构建简单的基于 CLI 的语音助手

德米特里·祖布☀️

一、介绍

        正如您从标题中看到的,这是一个演示项目,显示了一个非常基本的语音助手脚本,可以根据 Google 搜索结果在终端中回答您的问题。

        您可以在 GitHub 存储库中找到完整代码:dimitryzub/serpapi-demo-projects/speech-recognition/cli-based/

        后续博客文章将涉及:

  • 使用Flask、一些 HTML、CSS 和 Javascript 的基于 Web 的解决方案。
  • 使用Flutter和Dart的基于 Android 和 Windows 的解决方案。

二、我们将在这篇博文中构建什么

2.1 环境准备

        首先,让我们确保我们处于不同的环境中,并正确安装项目所需的库。最难(可能)是 安装 .pyaudio,关于此种困难可以参看下文克服:

   [解决]修复 win 32/64 位操作系统上的 PyAudio pip 安装错误 

2.2 虚拟环境和库安装

        在开始安装库之前,我们需要为此项目创建并激活一个新环境:

# if you're on Linux based systems
$ python -m venv env && source env/bin/activate
$ (env) <path># if you're on Windows and using Bash terminal
$ python -m venv env && source env/Scripts/activate
$ (env) <path># if you're on Windows and using CMD
python -m venv env && .\env\Scripts\activate
$ (env) <path>

        解释python -m venv env告诉 Python 运行 module( -m)venv并创建一个名为 的文件夹env&&代表“与”。source <venv_name>/bin/activate将激活您的环境,并且您将只能在该环境中安装库。

        现在安装所有需要的库:

pip install rich pyttsx3 SpeechRecognition google-search-results

        现在到pyaudio. 请记住,pyaudio安装时可能会引发错误。您可能需要进行额外的研究。

        如果您使用的是 Linux,我们需要安装一些开发依赖项才能使用pyaudio

$ sudo apt-get install -y libasound-dev portaudio19-dev
$ pip install pyaudio

如果您使用的是 Windows,则更简单(使用 CMD 和 Git Bash 进行测试):

pip install pyaudio

三、完整代码

import os
import speech_recognition
import pyttsx3
from serpapi import GoogleSearch
from rich.console import Console
from dotenv import load_dotenvload_dotenv('.env')
console = Console()def main():console.rule('[bold yellow]SerpApi Voice Assistant Demo Project')recognizer = speech_recognition.Recognizer()while True:with console.status(status='Listening you...', spinner='point') as progress_bar:try:with speech_recognition.Microphone() as mic:recognizer.adjust_for_ambient_noise(mic, duration=0.1)audio = recognizer.listen(mic)text = recognizer.recognize_google(audio_data=audio).lower()console.print(f'[bold]Recognized text[/bold]: {text}')progress_bar.update(status='Looking for answers...', spinner='line')params = {'api_key': os.getenv('API_KEY'),'device': 'desktop','engine': 'google','q': text,'google_domain': 'google.com','gl': 'us','hl': 'en'}search = GoogleSearch(params)results = search.get_dict()try:if 'answer_box' in results:try:primary_answer = results['answer_box']['answer']except:primary_answer = results['answer_box']['result']console.print(f'[bold]The answer is[/bold]: {primary_answer}')elif 'knowledge_graph' in results:secondary_answer = results['knowledge_graph']['description']console.print(f'[bold]The answer is[/bold]: {secondary_answer}')else:tertiary_answer = results['answer_box']['list']console.print(f'[bold]The answer is[/bold]: {tertiary_answer}')progress_bar.stop() # if answered is success -> stop progress bar.user_promnt_to_contiune_if_answer_is_success = input('Would you like to to search for something again? (y/n) ')if user_promnt_to_contiune_if_answer_is_success == 'y':recognizer = speech_recognition.Recognizer()continue # run speech recognizion again until `user_promt` == 'n'else:console.rule('[bold yellow]Thank you for cheking SerpApi Voice Assistant Demo Project')breakexcept KeyError:progress_bar.stop()error_user_promt = input("Sorry, didn't found the answer. Would you like to rephrase it? (y/n) ")if error_user_promt == 'y':recognizer = speech_recognition.Recognizer()continue # run speech recognizion again until `user_promt` == 'n'else:console.rule('[bold yellow]Thank you for cheking SerpApi Voice Assistant Demo Project')breakexcept speech_recognition.UnknownValueError:progress_bar.stop()user_promt_to_continue = input('Sorry, not quite understood you. Could say it again? (y/n) ')if user_promt_to_continue == 'y':recognizer = speech_recognition.Recognizer()continue # run speech recognizion again until `user_promt` == 'n'else:progress_bar.stop()console.rule('[bold yellow]Thank you for cheking SerpApi Voice Assistant Demo Project')breakif __name__ == '__main__':main()

四、代码说明

导入库:

import os
import speech_recognition
import pyttsx3
from serpapi import GoogleSearch
from rich.console import Console
from dotenv import load_dotenv
  • rich用于在终端中进行漂亮格式化的 Python 库。
  • pyttsx3Python 的文本到语音转换器可离线工作。
  • SpeechRecognition用于将语音转换为文本的 Python 库。
  • google-search-resultsSerpApi 的 Python API 包装器,可解析来自 15 个以上搜索引擎的数据。
  • os读取秘密环境变量。在本例中,它是 SerpApi API 密钥。
  • dotenv从文件加载环境变量(SerpApi API 密钥).env.env文件可以重命名为任何文件:(.napoleon .点)代表环境变量文件。

定义rich Console(). 它将用于美化终端输出(动画等):

console = Console()

定义main所有发生的函数:

def main():console.rule('[bold yellow]SerpApi Voice Assistant Demo Project')recognizer = speech_recognition.Recognizer()

在函数的开头,我们定义speech_recognition.Recognizer()并将console.rule创建以下输出:

───────────────────────────────────── SerpApi Voice Assistant Demo Project ─────────────────────────────────────

下一步是创建一个 while 循环,该循环将不断监听麦克风输入以识别语音:

while True:with console.status(status='Listening you...', spinner='point') as progress_bar:try:with speech_recognition.Microphone() as mic:recognizer.adjust_for_ambient_noise(mic, duration=0.1)audio = recognizer.listen(mic)text = recognizer.recognize_google(audio_data=audio).lower()console.print(f'[bold]Recognized text[/bold]: {text}')
  • console.status-rich进度条,仅用于装饰目的。
  • speech_recognition.Microphone()开始从麦克风拾取输入。
  • recognizer.adjust_for_ambient_noise旨在根据环境能量水平校准能量阈值。
  • recognizer.listen监听实际的用户文本。
  • recognizer.recognize_google使用 Google Speech Recongition API 执行语音识别。lower()是降低识别文本。
  • console.print允许使用文本修改的语句rich print,例如添加粗体斜体等。

spinner='point'将产生以下输出(使用python -m rich.spinner查看列表spinners):

之后,我们需要初始化 SerpApi 搜索参数以进行搜索:

progress_bar.update(status='Looking for answers...', spinner='line') 
params = {'api_key': os.getenv('API_KEY'),  # serpapi api key   'device': 'desktop',              # device used for 'engine': 'google',               # serpapi parsing engine: https://serpapi.com/status'q': text,                        # search query 'google_domain': 'google.com',    # google domain:          https://serpapi.com/google-domains'gl': 'us',                       # country of the search:  https://serpapi.com/google-countries'hl': 'en'                        # language of the search: https://serpapi.com/google-languages# other parameters such as locations: https://serpapi.com/locations-api
}
search = GoogleSearch(params)         # where data extraction happens on the SerpApi backend
results = search.get_dict()           # JSON -> Python dict

progress_bar.update将会progress_bar用新的status(控制台中打印的文本)进行更新,spinner='line'并将产生以下动画:

之后,使用 SerpApi 的Google 搜索引擎 API从 Google 搜索中提取数据。

代码的以下部分将执行以下操作:

try:if 'answer_box' in results:try:primary_answer = results['answer_box']['answer']except:primary_answer = results['answer_box']['result']console.print(f'[bold]The answer is[/bold]: {primary_answer}')elif 'knowledge_graph' in results:secondary_answer = results['knowledge_graph']['description']console.print(f'[bold]The answer is[/bold]: {secondary_answer}')else:tertiary_answer = results['answer_box']['list']console.print(f'[bold]The answer is[/bold]: {tertiary_answer}')progress_bar.stop()  # if answered is success -> stop progress baruser_promnt_to_contiune_if_answer_is_success = input('Would you like to to search for something again? (y/n) ')if user_promnt_to_contiune_if_answer_is_success == 'y':recognizer = speech_recognition.Recognizer()continue         # run speech recognizion again until `user_promt` == 'n'else:console.rule('[bold yellow]Thank you for cheking SerpApi Voice Assistant Demo Project')breakexcept KeyError:progress_bar.stop()  # if didn't found the answer -> stop progress barerror_user_promt = input("Sorry, didn't found the answer. Would you like to rephrase it? (y/n) ")if error_user_promt == 'y':recognizer = speech_recognition.Recognizer()continue         # run speech recognizion again until `user_promt` == 'n'else:console.rule('[bold yellow]Thank you for cheking SerpApi Voice Assistant Demo Project')break

最后一步是处理麦克风没有拾取声音时的错误:

# while True:
#     with console.status(status='Listening you...', spinner='point') as progress_bar:
#         try:# speech recognition code# data extraction codeexcept speech_recognition.UnknownValueError:progress_bar.stop()         # if didn't heard the speech -> stop progress baruser_promt_to_continue = input('Sorry, not quite understood you. Could say it again? (y/n) ')if user_promt_to_continue == 'y':recognizer = speech_recognition.Recognizer()continue               # run speech recognizion again until `user_promt` == 'n'else:progress_bar.stop()    # if want to quit -> stop progress barconsole.rule('[bold yellow]Thank you for cheking SerpApi Voice Assistant Demo Project')break

console.rule()将提供以下输出:

───────────────────── Thank you for cheking SerpApi Voice Assistant Demo Project ──────────────────────

添加if __name__ == '__main__'惯用语,以防止用户在无意时意外调用某些脚本,并调用main将运行整个脚本的函数:

if __name__ == '__main__':main()

五、链接

  • rich
  • pyttsx3
  • SpeechRecognition
  • google-search-results
  • os
  • dotenv

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/145273.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Python爬虫】安装requests库解决报错问题

requests 确保pip的安装命令行下安装出现的问题以及解决办法换镜像源安装验证安装为什么使用requests库呢 废话不多说了&#xff0c;直接进入正题 确保pip的安装 首先要想安装requests库&#xff0c;第一点就是要确保pip已经安装。这个pip在Python高级版本中已经默认安装了。…

如何实现前端实时通信(WebSocket、Socket.io等)?

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…

空中计算(Over-the-Air Computation)学习笔记

文章目录 写在前面 写在前面 本文是论文A Survey on Over-the-Air Computation的阅读笔记&#xff1a; 通信和计算通常被视为独立的任务。 从工程的角度来看&#xff0c;这种方法是非常有效的&#xff0c;因为可以执行孤立的优化。 然而&#xff0c;对于许多面向计算的应用程序…

python如何创建自己的对冲交易算法

在这篇文章中&#xff0c;我解释了如何创建一个人工智能来每天为我进行自动交易。 随着机器学习的现代进步和在线数据的轻松访问&#xff0c;参与量化交易变得前所未有的容易。为了让事情变得更好&#xff0c;AWS 等云工具可以轻松地将交易想法转化为真正的、功能齐全的交易机器…

浅析PID

当涉及到控制系统中的精确调节和稳定性&#xff0c;PID&#xff08;比例-积分-微分&#xff09;控制算法是一种不可或缺的工具。本文将简单介绍PID控制算法&#xff0c;从基本概念到具体实现&#xff0c;一起了解如何使用PID控制算法来优化控制系统。 引言 PID&#xff08;比…

Python数据挖掘 | 升级版自动查核酸

&#x1f4d5;作者简介&#xff1a;热爱跑步的恒川&#xff0c;致力于C/C、Java、Python等多编程语言&#xff0c;热爱跑步&#xff0c;喜爱音乐的一位博主。 &#x1f4d7;本文收录于恒川的日常汇报系列&#xff0c;大家有兴趣的可以看一看 &#x1f4d8;相关专栏C语言初阶、C…

汽车屏类产品(一):流媒体后视镜Camera Monitoring System (CMS)

前言: CMS,有叫电子侧视镜,虚拟倒车镜,电子倒车镜, 电子取代镜等,ISO 国际标准组织称其为摄像头监控系统。电子后视镜由“摄像头+屏幕”组成,汽车外后视镜经历了光学镜面从平面镜到曲面镜的迭代进步,CMS也实现从商用车到乘用车的过渡。显示模式为外部摄像头采集图像,…

MAC如何在根目录创建文件

在这之前先明确一下啥是根目录。 打开终端&#xff0c;输入cd /&#xff0c;然后输入 ls 查看根目录下有哪些文件 可以看到 usr、etc、opt 这些文件的地方才叫根目录&#xff0c;而不是以用户命名&#xff0c;可以看到音乐、应用程序、影片、桌面的地方哈 介绍一种叫做软连接…

CleanMyMac X免费macOS清理系统管家

近些年伴随着苹果生态的蓬勃发展&#xff0c;越来越多的用户开始尝试接触Mac电脑。然而很多人上手Mac后会发现&#xff0c;它的使用逻辑与Windows存在很多不同&#xff0c;而且随着使用时间的增加&#xff0c;一些奇奇怪怪的文件也会占据有限的磁盘空间&#xff0c;进而影响使用…

鸿蒙原生应用,对开发者意味着什么?

华为925秋季全场景新品发布会上&#xff0c;有一个消息&#xff0c;官宣只用了大约一分钟的时间&#xff0c;在我们看来&#xff0c;却可能是这场发布会最重要的一分钟&#xff0c;也是最大的“彩蛋”。 发布会接近结束时&#xff0c;余承东突然宣布&#xff1a;鸿蒙原生应用全…

3ds Max2023安装教程(最新最详细)

目录 一.简介 二.安装步骤 软件&#xff1a;3ds Max版本&#xff1a;2023语言&#xff1a;简体中文大小&#xff1a;6.85G安装环境&#xff1a;Win11/Win10/Win8/Win7硬件要求&#xff1a;CPU3GHz 内存16G(或更高&#xff09;下载通道①百度网盘丨64位下载链接&#xff1a; …

使用Gitlab构建简单流水线CI/CD

什么是Gitlab Gitlab实质上是一套DevOps工具 目前看起来&#xff0c;Gitlab属于是内嵌了一套CI/CD的框架&#xff0c;并且可以提供软件开发中的版本管理、项目管理等等其他功能。 这里需要辨别一下Gitlab和Github Gitee的区别。 GIthub大家都很熟悉了&#xff0c;一般大家都会…