Make your own AI assistant by python

 hey there, here's the code for your AI assistant :

libraries: pip install speech_recognition pyttsx3 pyaudio

Source code:

import SpeechRecognition as sr
import pyttsx3
import nltk
from nltk.chat.util import Chat, reflections

# Initialize text-to-speech engine
engine = pyttsx3.init()

def speak(text):
    engine.say(text)
    engine.runAndWait()

# Define pairs of patterns and responses
pairs = [
    (r'hi|hello|hey', ['Hello!', 'Hey there!', 'Hi!']),
    (r'how are you?', ['I am good, thank you.', 'Doing well, thanks.']),
    (r'what can you do?', ['I can answer questions and provide information.']),
    (r'quit', ['Goodbye!', 'Bye!']),
]

# Create a chatbot using NLTK's Chat class
chatbot = Chat(pairs, reflections)

# Speech recognition setup
recognizer = sr.Recognizer()

def recognize_speech():
    with sr.Microphone() as source:
        print("Listening...")
        audio = recognizer.listen(source)

        try:
            # Recognize speech using Google's speech recognition
            text = recognizer.recognize_google(audio)
            print(f"You said: {text}")
            return text.lower()
        except sr.UnknownValueError:
            print("Sorry, I didn't catch that.")
            return None
        except sr.RequestError:
            print("Sorry, I'm having trouble connecting.")
            return None

# Main loop for the AI assistant
def assistant():
    speak("Hello, I'm your assistant. How can I help you?")
    while True:
        query = recognize_speech()
        if query:
            response = chatbot.respond(query)
            if response:
                print(response)
                speak(response)
            if 'quit' in query:
                speak("Goodbye!")
                break

if __name__ == "__main__":
    assistant()

Comments