create me an AI that can interact with users by voice and has the ability to understand…
- User
create me an AI that can interact with users by voice and has the ability to understand on window using python
Assistant
create me an AI that can interact with users by voice and has the ability to understand on window using python
I'll help you create a voice-interactive AI assistant for Windows using Python. This will include speech recognition, text-to-speech, and basic AI capabilities.
Here's a complete implementation:
import speech_recognition as sr
import pyttsx3
import datetime
import webbrowser
import os
import subprocess
import json
from threading import Thread
import queue
import time
class VoiceAssistant:
def __init__(self):
# Initialize speech recognition
self.recognizer = sr.Recognizer()
self.microphone = sr.Microphone()
# Initialize text-to-speech
self.engine = pyttsx3.init('sapi5') # Windows Speech API
self.voices = self.engine.getProperty('voices')
self.engine.setProperty('voice', self.voices[0].id) # 0 for male, 1 for female
self.engine.setProperty('rate', 180) # Speech rate
# Queue for handling speech output
self.speech_queue = queue.Queue()
self.is_speaking = False
# Start speech thread
self.speech_thread = Thread(target=self._speech_worker, daemon=True)
self.speech_thread.start()
def _speech_worker(self):
"""Worker thread for handling speech output"""
while True:
text = self.speech_queue.get()
if text is None:
break
self.is_speaking = True
self.engine.say(text)
self.engine.runAndWait()
self.is_speaking = False
self.speech_queue.task_done()
def speak(self, text):
"""Convert text to speech"""
print(f"Assistant: {text}")
self.speech_queue.put(text)
def listen(self):
"""Listen for voice input"""
with self.microphone as source:
print("Listening...")
self.recognizer.adjust_for_ambient_noise(source, duration=0.5)
try:
audio = self.recognizer.listen(source, timeout=5, phrase_time_limit=10)
print("Processing...")
# Use Google's speech recognition
text = self.recognizer.recognize_google(audio)
print(f"You said: {text}")
return text.lower()
except sr.WaitTimeoutError:
return None
except sr.UnknownValueError:
print("Could not understand audio")
return None
except sr.RequestError as e:
print(f"Error with speech recognition: {e}")
return None
def process_command(self, command):
"""Process user commands"""
if command is None:
return
# Greetings
if any(word in command for word in ['hello', 'hi', 'hey']):
self.speak("Hello! How can I help you today?")
# Time and date
elif 'time' in command:
current_time = datetime.datetime.now().strftime("%I:%M %p")
self.speak(f"The current time is {current_time}")
elif 'date' in command:
current_date = datetime.datetime.now().strftime("%B %d, %Y")
self.speak(f"Today's date is {current_date}")
# Open applications
elif 'open notepad' in command:
self.speak("Opening Notepad")
subprocess.Popen(['notepad.exe'])
elif 'open calculator' in command:
self.speak("Opening Calculator")
subprocess.Popen(['calc.exe'])
elif 'open browser' in command or 'open chrome' in command:
self.speak("Opening web browser")
webbrowser.open('https://www.google.com')
# Web searches
elif 'search' in command:
search_query = command.replace('search', '').strip()
if search_query:
self.speak(f"Searching for {search_query}")
webbrowser.open(f"https://www.google.com/search?q={search_query}")
else:
self.speak("What would you like me to search for?")
# System commands
elif 'shutdown' in command:
self.speak("Are you sure you want to shutdown the computer?")
confirmation = self.listen()
if confirmation and 'yes' in confirmation:
self.speak("Shutting down the system")
os.system("shutdown /s /t 5")
elif 'restart' in command:
self.speak("Are you sure you want to restart the computer?")
confirmation = self.listen()
if confirmation and 'yes' in confirmation:
self.speak("Restarting the system")
os.system("shutdown /r /t 5")
# File operations
elif 'create file' in command:
self.speak("What should I name the file?")
filename = self.listen()
if filename:
try:
with open(f"{filename}.txt", 'w') as f:
f.write("")
self.speak(f"Created file {filename}.txt")
except Exception as e:
self.speak("Sorry, I couldn't create the file")
# Exit
elif any(word in command for word in ['exit', 'quit', 'goodbye', 'bye']):
self.speak("Goodbye! Have a great day!")
return False
# Help
elif 'help' in command or 'what can you do' in command:
help_text = """I can help you with:
- Telling time and date
- Opening applications like Notepad and Calculator
- Web searches
- Creating text files
- System commands like shutdown and restart
- And more! Just ask me."""
self.speak(help_text)
else:
self.speak("I'm not sure how to help with that. Can you please rephrase?")
return True
def run(self):
"""Main loop"""
self.speak("Hello! I'm your voice assistant. How can I help you?")
while True:
# Wait a bit if still speaking
while self.is_speaking:
time.sleep(0.1)
command = self.listen()
if command:
should_continue = self.process_command(command)
if not should_continue:
break
# Cleanup
self.speech_queue.put(None)
self.speech_thread.join()
# Enhanced version with more AI capabilities
class AdvancedVoiceAssistant(VoiceAssistant):
def __init__(self):
super().__init__()
self.conversation_history = []
self.user_preferences = {}
def remember_preference(self, key, value):
"""Store user preferences"""
self.user_preferences[key] = value
with open('preferences.json', 'w') as f:
json.dump(self.user_preferences, f)
def load_preferences(self):
"""Load saved preferences"""
try:
with open('preferences.json', 'r') as f:
self.user_preferences = json.load(f)
except FileNotFoundError:
self.user_preferences = {}
def process_command(self, command):
"""Enhanced command processing with context awareness"""
if command is None:
return True
# Add to conversation history
self.conversation_history.append(command)
# Check for name setting
if 'my name is' in command:
name = command.split('my name is')[-1].strip()
self.remember_preference('user_name', name)
self.speak(f"Nice to meet you, {name}!")
return True
# Greet by name if known
if any(word in command for word in ['hello', 'hi', 'hey']):
name = self.user_preferences.get('user_name', '')
greeting = f"Hello{', ' + name if name else ''}! How can I help you today?"
self.speak(greeting)
return True
# Weather (placeholder - would need API integration)
if 'weather' in command:
self.speak("I would need to connect to a weather API to provide current weather information.")
return True
# Note taking
if 'take note' in command or 'make note' in command:
self.speak("What would you like me to note down?")
note = self.listen()
if note:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open('notes.txt', 'a') as f:
f.write(f"\n[{timestamp}] {note}")
self.speak("I've saved your note")
return True
# Read notes
if 'read notes' in command:
try:
with open('notes.txt', 'r') as f:
notes = f.read()
if notes:
self.speak("Here are your notes:")
self.speak(notes)
else:
self.speak("You don't have any notes yet")
except FileNotFoundError:
self.speak("You don't have any notes yet")
return True
# Default to parent class processing
return super().process_command(command)
def main():
"""Main function to run the assistant"""
print("Voice Assistant Starting...")
print("Please make sure your microphone is connected and working.")
print("-" * 50)
# Use the advanced version
assistant = AdvancedVoiceAssistant()
assistant.load_preferences()
try:
assistant.run()
except KeyboardInterrupt:
print("\nAssistant stopped by user")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
To use this voice assistant, you'll need to install the required packages:
pip install speechrecognition pyttsx3 pyaudio
Note for Windows users: If you encounter issues installing pyaudio, you can download the appropriate wheel file from here and install it using:
pip install PyAudio‑0.2.11‑cp39‑cp39‑win_amd64.whl
Features of this AI assistant:
To extend this assistant, you could add:
The assistant is designed to be modular and extensible. You can easily add new commands by extending the process_command method or creating new methods for specific functionalities.