Skip to content

AI-powered Personal Assistant

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

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of automation and voice recognition
  • Required libraries: speechrecognitionspeechrecognition, pyttsx3pyttsx3, datetimedatetime, osos

Before you Start

Install Python and the required libraries:

Install dependencies
pip install SpeechRecognition pyttsx3
Install dependencies
pip install SpeechRecognition pyttsx3

Getting Started

Create a Project

  1. Create a folder named ai-powered-personal-assistantai-powered-personal-assistant.
  2. Open the folder in your code editor or IDE.
  3. Create a file named ai_powered_personal_assistant.pyai_powered_personal_assistant.py.
  4. Copy the code below into your file.

Write the Code

⚙️ AI-powered Personal Assistant
AI-powered Personal Assistant
"""
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)
 
AI-powered Personal Assistant
"""
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

Run personal assistant
python ai_powered_personal_assistant.py
Run personal assistant
python ai_powered_personal_assistant.py

Explanation

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

  1. Import Libraries and Setup Assistant
ai_powered_personal_assistant.py
import speech_recognition as sr
import pyttsx3
import datetime
import os
ai_powered_personal_assistant.py
import speech_recognition as sr
import pyttsx3
import datetime
import os
  1. Voice Command Recognition
ai_powered_personal_assistant.py
def listen_command():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = recognizer.listen(source)
    try:
        return recognizer.recognize_google(audio)
    except Exception as e:
        return f"Error: {e}"
ai_powered_personal_assistant.py
def listen_command():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = recognizer.listen(source)
    try:
        return recognizer.recognize_google(audio)
    except Exception as e:
        return f"Error: {e}"
  1. Task Automation Logic
ai_powered_personal_assistant.py
def perform_task(command):
    if 'time' in command:
        now = datetime.datetime.now().strftime('%H:%M:%S')
        return f"Current time is {now}"
    elif 'open' in command:
        app = command.split('open ')[-1]
        os.system(app)
        return f"Opened {app}"
    else:
        return "Task not recognized."
ai_powered_personal_assistant.py
def perform_task(command):
    if 'time' in command:
        now = datetime.datetime.now().strftime('%H:%M:%S')
        return f"Current time is {now}"
    elif 'open' in command:
        app = command.split('open ')[-1]
        os.system(app)
        return f"Opened {app}"
    else:
        return "Task not recognized."
  1. CLI Interface and Error Handling
ai_powered_personal_assistant.py
def main():
    print("AI-powered Personal Assistant")
    while True:
        cmd = input('> ')
        if cmd == 'listen':
            command = listen_command()
            result = perform_task(command)
            print(result)
        elif cmd == 'exit':
            break
        else:
            print("Unknown command. Type 'listen' or 'exit'.")
 
if __name__ == "__main__":
    main()
ai_powered_personal_assistant.py
def main():
    print("AI-powered Personal Assistant")
    while True:
        cmd = input('> ')
        if cmd == 'listen':
            command = listen_command()
            result = perform_task(command)
            print(result)
        elif cmd == 'exit':
            break
        else:
            print("Unknown command. Type 'listen' or 'exit'.")
 
if __name__ == "__main__":
    main()

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

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

This project teaches:

  • Assistant Design: Task automation and voice recognition
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • Personal Productivity Tools
  • Smart Home Assistants
  • Educational Tools

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.

Was this page helpful?

Let us know how we did