如何使用 Python 构建您的个人 AI 助手

发布时间:2025-06-21 12:29

AI助手如语音助手成为个人助理 #生活知识# #生活感悟# #科技生活变迁# #科技进步与日常生活#

你还记得托尼·斯塔克的虚拟私人助理 J.A.R.V.I.S. 吗?我相信你会的!

你有没有想过创建自己的私人助理?是的?托尼·斯塔克可以帮助我们!哎呀,你忘了他不在了吗?可惜他再也救不了我们了。

但是,嘿,你最喜欢的语言 Python 可以帮助你。是的,你没听错。我们可以创建自己的 J.A.R.V.I.S.使用 Python。让我们滚动它!

在项目开发过程中,我们会遇到各种模块和外部库。让我们学习并安装它们。但在我们安装它们之前,让我们创建一个虚拟环境并激活它。

我们将使用virtualenv创建一个虚拟环境。 Python 现在附带一个预安装的virtualenv库。因此,要创建虚拟环境,您可以使用以下命令:

$ python -m venv env

上述命令将创建一个名为env的虚拟环境。现在,我们需要使用以下命令激活环境:

$ . env/Scripts/activate

要验证环境是否已激活,您可以在终端中查看(env)。现在,我们可以安装库了。

pyttsx3:pyttsx 是一个跨平台的文本到语音库,它是独立于平台的。使用这个库进行文本到语音转换的主要优点是它可以离线工作。要安装此模块,请在终端中键入以下命令。

$点安装pyttsx3 SpeechRecognition :它允许我们将音频转换为文本以进行进一步处理。要安装此模块,请在终端中键入以下命令。

$ pip install SpeechRecognition pywhatkit:这是一个易于使用的库,可以帮助我们非常轻松地与浏览器交互。要安装模块,请在终端中运行以下命令。

$点安装pywhatkit wikipedia:用于从维基百科网站获取各种信息。要安装此模块,请在终端中键入以下命令。

$ pip 安装维基百科 requests:它是一个优雅而简单的 Python HTTP 库,允许您非常轻松地发送 HTTP/1.1 请求。要安装模块,请在终端中运行以下命令:

$ pip 安装请求

.env 文件

我们需要这个文件来存储一些与项目相关的私有数据,例如 API Keys、Passwords 等。现在,让我们存储用户和机器人的名称。

创建一个名为.env的文件并在其中添加以下内容:

USER=Ashutosh BOTNAME=JARVIS

要使用.env文件中的内容,我们将安装另一个名为 python-decouple 的模块:

$ pip install python-decouple

在此处了解有关 Python中的环境变量的更多信息。

设置 JARVIS

在我们开始定义一些重要的功能之前,让我们先创建一个语音引擎。

import pyttsx3 from decouple import config USERNAME = config('USER') BOTNAME = config('BOTNAME') engine = pyttsx3.init('sapi5') engine.setProperty('rate', 190) engine.setProperty('volume', 1.0) voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id)

我们来分析一下上面的脚本。首先,我们使用_pyttsx3_模块初始化了一个engine。sapi5是一个帮助我们使用语音的 Microsoft Speech API。在此处了解更多信息。接下来,我们使用setProperty方法设置语音引擎的rate和volume属性。现在,我们可以使用getProperty方法从引擎中获取声音。voices将是我们系统中可用的声音列表。如果我们打印它,我们可以看到如下:

[<pyttsx3.voice.Voice object at 0x000001AB9FB834F0>, <pyttsx3.voice.Voice object at 0x000001AB9FB83490>]

第一个是男声,另一个是女声。 JARVIS 是电影中的男助理,但我选择使用setProperty方法在本教程中将voice属性设置为女性。

注意:如果您收到与 PyAudio 相关的错误,请从此处下载 PyAudio wheel并将其安装在虚拟环境中。

此外,使用 decouple 中的config方法,我们从环境变量中获取USER和BOTNAME的值。

1\。说话功能

Speak 函数将负责说出传递给它的任何文本。让我们看看代码:

# Text to Speech Conversion def speak(text): """Used to speak whatever text is passed to it""" engine.say(text) engine.runAndWait()

在speak()方法中,引擎会说出使用say()方法传递给它的任何文本。使用runAndWait()方法,它在事件循环期间阻塞并在命令队列被清除时返回。

每当程序运行时,此功能将用于问候用户。根据当前时间,向用户打招呼_早安_、下午好_或_晚安。

from datetime import datetime def greet_user(): """Greets the user according to the time""" hour = datetime.now().hour if (hour >= 6) and (hour < 12): speak(f"Good Morning {USERNAME}") elif (hour >= 12) and (hour < 16): speak(f"Good afternoon {USERNAME}") elif (hour >= 16) and (hour < 19): speak(f"Good Evening {USERNAME}") speak(f"I am {BOTNAME}. How may I assist you?")

首先,我们获取当前时间,即如果当前时间是上午 11:15,则该小时将是 11。如果小时的值在 6 到 12 之间,请向用户表示早安。如果值在 12 和 16 之间,祝下午好,同样,如果值在 16 和 19 之间,祝晚上好。我们正在使用 speak 方法来祝愿用户。

该功能用于获取用户的命令并使用speech_recognition模块识别命令。

import speech_recognition as sr from random import choice from utils import opening_text def take_user_input(): """Takes user input, recognizes it using Speech Recognition module and converts it into text""" r = sr.Recognizer() with sr.Microphone() as source: print('Listening....') r.pause_threshold = 1 audio = r.listen(source) try: print('Recognizing...') query = r.recognize_google(audio, language='en-in') if not 'exit' in query or 'stop' in query: speak(choice(opening_text)) else: hour = datetime.now().hour if hour >= 21 and hour < 6: speak("Good night sir, take care!") else: speak('Have a good day sir!') exit() except Exception: speak('Sorry, I could not understand. Could you please say that again?') query = 'None' return query

我们已将speech_recognition模块导入为sr。speech_recognition模块中的_Recognizer_ 类帮助我们识别音频。同一个模块有一个 Microphone 类,可以让我们访问设备的麦克风。所以以麦克风为source,我们尝试使用_Recognizer_类中的listen()方法来收听音频。我们也将pause_threshold设置为1,即说话时停顿一秒也不会抱怨。

接下来,使用 Recognizer 类中的recognize_google()方法,我们尝试识别音频。recognize_google()方法使用 Google Speech Recognition API 对传递给它的音频执行语音识别。我们已将语言设置为en-in,即英语印度。它返回音频的转录本,它只是一个字符串。我们将它存储在一个名为query的变量中。

如果查询中有 exitstop 字样,这意味着我们要求助手立即停止。因此,在停止之前,我们按照当前时间再次向用户打招呼。如果时间在 21 点到 6 点之间,则向用户祝福 Good Night,否则,一些其他消息。我们创建一个utils.py文件,其中只有一个列表,其中包含一些语句:

opening_text = [ "Cool, I'm on it sir.", "Okay sir, I'm working on it.", "Just a second sir.", ]

如果查询没有这两个词(退出或停止),我们会说一些话来告诉用户我们已经听到了您的声音。为此,我们将使用随机模块中的选择方法从opening_text列表中随机选择任何语句。说完,我们退出程序。

在整个过程中,如果遇到异常,我们向用户道歉,并将query设置为None。最后,我们返回query。

为了运行项目,我们使用 main 方法。

if __name__ == ' __main__': greet_user() while True: query = take_user_input().lower() print(query)

众所周知,我们需要做的第一件事是使用greet_user()函数问候用户。接下来,我们运行一个 while 循环,使用take_user_input()函数不断地从用户那里获取输入。现在,我们只是打印query。

目前,main.py中的完整代码如下所示:

import pyttsx3 import speech_recognition as sr from decouple import config from datetime import datetime from random import choice from utils import opening_text USERNAME = config('USER') BOTNAME = config('BOTNAME') engine = pyttsx3.init('sapi5') engine.setProperty('rate', 190) engine.setProperty('volume', 1.0) voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) def speak(text): """Used to speak whatever text is passed to it""" engine.say(text) engine.runAndWait() def greet_user(): """Greets the user according to the time""" hour = datetime.now().hour if (hour >= 6) and (hour < 12): speak(f"Good Morning {USERNAME}") elif (hour >= 12) and (hour < 16): speak(f"Good afternoon {USERNAME}") elif (hour >= 16) and (hour < 19): speak(f"Good Evening {USERNAME}") speak(f"I am {BOTNAME}. How may I assist you?") def take_user_input(): """Takes user input, recognizes it using Speech Recognition module and converts it into text""" r = sr.Recognizer() with sr.Microphone() as source: print('Listening....') r.pause_threshold = 1 audio = r.listen(source) try: print('Recognizing...') query = r.recognize_google(audio, language='en-in') if not 'exit' in query or 'stop' in query: speak(choice(opening_text)) else: hour = datetime.now().hour if hour >= 21 and hour < 6: speak("Good night sir, take care!") else: speak('Have a good day sir!') exit() except Exception: speak('Sorry, I could not understand. Could you please say that again?') query = 'None' return query if __name__ == ' __main__': greet_user() while True: query = take_user_input().lower() print(query)

您现在可以运行和测试应用程序。

$ python main.py

结论

在这一部分中,我们已经完成了虚拟个人助理的设置。我们尚未为其添加任何功能。我们将在博客的下一部分中研究这些功能。敬请关注!

网址:如何使用 Python 构建您的个人 AI 助手 https://www.yuejiaxmz.com/news/view/1071073

相关内容

使用Python构建虚拟个人助手教程
如何利用Python构建智能虚拟助手
推荐使用:Python驱动的个人助手
使用 ChatGPT 构建虚拟个人助理
AI自动化工作流:如何构建你的智能助手?
Deep Seek:普通人的高效AI助手,如何打破使用壁垒?
使用Python+JarvisAI实现AI虚拟助手
构建您的私人语音助手:在本地运行的Whisper + Ollama + Bark之旅
Python实现简单的智能助手
小白如何做一个Python人工智能语音助手

随便看看