AI-powered Personal Assistant
Abstract
Section titled “Abstract”AI-powered Personal Assistant is a Python project that uses AI to automate tasks and respond to voice commands. The application features task automation, voice recognition, and a CLI interface, demonstrating best practices in assistant design and automation.
Prerequisites
Section titled “Prerequisites”- Python 3.8 or above
- A code editor or IDE
- Basic understanding of automation and voice recognition
- Required libraries:
speechrecognition,pyttsx3,datetime,os
Before you Start
Section titled “Before you Start”Install Python and the required libraries:
pip install SpeechRecognition pyttsx3Getting Started
Section titled “Getting Started”Create a Project
Section titled “Create a Project”- Create a folder named
ai-powered-personal-assistant. - Open the folder in your code editor or IDE.
- Create a file named
ai_powered_personal_assistant.py. - Copy the code below into your file.
Write the Code
Section titled “Write the Code”AI-powered Personal Assistant
pch.viewSource"""
AI Powered Personal Assistant
Features:
- Scheduling
- Reminders
- Natural language interface
- Modular design
- CLI interface
- Error handling
"""
import sys
import datetime
import threading
import time
import re
from collections import defaultdict
try:
import nltk
from nltk.tokenize import word_tokenize
except ImportError:
nltk = None
word_tokenize = lambda x: x.split()
class Reminder:
def __init__(self, time, message):
self.time = time
self.message = message
self.triggered = False
class PersonalAssistant:
def __init__(self):
self.reminders = []
self.schedule = defaultdict(list)
self.running = True
self.thread = threading.Thread(target=self.check_reminders, daemon=True)
self.thread.start()
def add_reminder(self, time_str, message):
try:
t = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M')
self.reminders.append(Reminder(t, message))
print(f"Reminder set for {t}: {message}")
except Exception as e:
print(f"Error: {e}")
def add_schedule(self, date_str, event):
self.schedule[date_str].append(event)
print(f"Scheduled: {event} on {date_str}")
def show_schedule(self, date_str):
events = self.schedule.get(date_str, [])
print(f"Schedule for {date_str}:")
for e in events:
print(f"- {e}")
def check_reminders(self):
while self.running:
now = datetime.datetime.now()
for r in self.reminders:
if not r.triggered and now >= r.time:
print(f"REMINDER: {r.message}")
r.triggered = True
time.sleep(30)
def parse_command(self, cmd):
tokens = word_tokenize(cmd.lower())
if 'remind' in tokens:
m = re.search(r'remind me at (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) to (.+)', cmd)
if m:
self.add_reminder(m.group(1), m.group(2))
else:
print("Invalid reminder format.")
elif 'schedule' in tokens:
m = re.search(r'schedule (.+) on (\d{4}-\d{2}-\d{2})', cmd)
if m:
self.add_schedule(m.group(2), m.group(1))
else:
print("Invalid schedule format.")
elif 'show' in tokens and 'schedule' in tokens:
m = re.search(r'show schedule for (\d{4}-\d{2}-\d{2})', cmd)
if m:
self.show_schedule(m.group(1))
else:
print("Invalid show schedule format.")
elif cmd == 'exit':
self.running = False
print("Goodbye!")
sys.exit(0)
else:
print("Unknown command.")
class CLI:
@staticmethod
def run():
pa = PersonalAssistant()
print("AI Powered Personal Assistant")
print("Commands:")
print("- remind me at YYYY-MM-DD HH:MM to <message>")
print("- schedule <event> on YYYY-MM-DD")
print("- show schedule for YYYY-MM-DD")
print("- exit")
while pa.running:
cmd = input('> ')
pa.parse_command(cmd)
if __name__ == "__main__":
try:
CLI.run()
except Exception as e:
print(f"Error: {e}")
sys.exit(1) Example Usage
Section titled “Example Usage”python ai_powered_personal_assistant.pyHow it fits together
Section titled “How it fits together”Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.
flowchart TD RUN(["python ai_powered_personal_assistant.py"]) Reminder["Reminder
class"] PersonalAssistant["PersonalAssistant
class"] CLI["CLI
class"] RUN --> Reminder CLI --> PersonalAssistant PersonalAssistant --> Reminder
Explanation
Section titled “Explanation”Key Features
Section titled “Key Features”- Task Automation: Automates common tasks (e.g., reminders, opening apps).
- Voice Commands: Responds to spoken instructions.
- Error Handling: Validates inputs and manages exceptions.
- CLI Interface: Interactive command-line usage.
Code Breakdown
Section titled “Code Breakdown”- What it imports (lines 12–17)
import sys
import datetime
import threading
import time
import re
from collections import defaultdictReminder— the class (lines 25–29)
class Reminder:
def __init__(self, time, message):
self.time = time
self.message = message
self.triggered = FalsePersonalAssistant— the class (lines 31–91)
class PersonalAssistant:
def __init__(self):
self.reminders = []
self.schedule = defaultdict(list)
self.running = True
self.thread = threading.Thread(target=self.check_reminders, daemon=True)
self.thread.start()
def add_reminder(self, time_str, message):
try:
t = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M')
self.reminders.append(Reminder(t, message))
print(f"Reminder set for {t}: {message}")
except Exception as e:
print(f"Error: {e}")
def add_schedule(self, date_str, event):
self.schedule[date_str].append(event)
# ... 37 more lines in the file ...
elif cmd == 'exit':
self.running = False
print("Goodbye!")
sys.exit(0)
else:
print("Unknown command.")CLI— the class (lines 93–105)
class CLI:
@staticmethod
def run():
pa = PersonalAssistant()
print("AI Powered Personal Assistant")
print("Commands:")
print("- remind me at YYYY-MM-DD HH:MM to <message>")
print("- schedule <event> on YYYY-MM-DD")
print("- show schedule for YYYY-MM-DD")
print("- exit")
while pa.running:
cmd = input('> ')
pa.parse_command(cmd)The file defines 3 top-level symbols in all; the whole thing is above under Write the Code.
Features
Section titled “Features”- AI-Based Personal Assistant: Automates tasks and responds to voice commands
- Task Automation: Handles reminders, app launching, and more
- Error Handling: Manages invalid inputs and exceptions
- Production-Ready: Scalable and maintainable code
Next Steps
Section titled “Next Steps”Enhance the project by:
- Supporting more tasks and integrations
- Creating a GUI with Tkinter or a web app with Flask
- Adding natural language understanding
- Unit testing for reliability
Educational Value
Section titled “Educational Value”This project teaches:
- Assistant Design: Task automation and voice recognition
- Software Design: Modular, maintainable code
- Error Handling: Writing robust Python code
Real-World Applications
Section titled “Real-World Applications”- Personal Productivity Tools
- Smart Home Assistants
- Educational Tools
Conclusion
Section titled “Conclusion”AI-powered Personal Assistant demonstrates how to build a scalable and accurate assistant tool using Python. With modular design and extensibility, this project can be adapted for real-world applications in productivity, automation, and more. For more advanced projects, visit Python Central Hub.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading