AI_Assistant

  Python Voice Assistant – Project Overview

🚀 Introduction

In today’s digital world, voice assistants like Alexa, Siri, and Google Assistant have become part of our daily life. They help us search information, open apps, tell the time, and even crack jokes!
In this project, I created a custom voice assistant using Python. The assistant listens to your commands, processes them, and responds back with speech.

I named my assistant Igris 🖤 – and it’s my personal AI helper.


⚙️ Features

Greeting System – Wishes good morning, afternoon, or evening.
Voice Recognition – Listens to user voice commands using speech_recognition.
Text-to-Speech (TTS) – Responds with natural speech using pyttsx3.
Wikipedia Search – Fetches quick answers from Wikipedia.


Time Teller – Tells the current time.
Website Opener – Opens YouTube, Google, StackOverflow, or any search query.
Fallback Mode – If voice input fails, you can type your command.
Simple Chat – Responds to greetings, name questions, and even jokes!


🛠️ Tech Stack

  • Python (Core Language)

  • speech_recognition (Voice input)

  • pyttsx3 (Text-to-Speech output)

  • wikipedia API (Knowledge source)

  • webbrowser (For opening sites)

  • datetime (Time features)


🎯 How It Works

  1. The program starts and greets the user.

  2. It listens for your voice command.

  3. Recognizes speech → Converts it to text.

  4. Matches the command (Wikipedia, time, jokes, or website).

  5. Responds back via voice + text.

  6. Keeps running until you say "stop" or "exit".


💡 Example Commands

  • What is Python in Wikipedia?” → Reads out a short answer.

  • What time is it?” → Tells the current time.

  • Open YouTube” → Launches YouTube in browser.

  • Tell me a joke” → Cracks a coding joke.





🎉 Conclusion

This project is a beginner-friendly AI assistant that introduces you to speech recognition, text-to-speech, API usage, and automation.
I plan to upgrade Igris step by step — adding levels, smarter conversations, and maybe even AI integration in the future! 🚀


Complete Source Code:

import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import sys
import time

# ----------------- Setup TTS engine -----------------
engine = pyttsx3.init()
engine.setProperty("rate", 165)    # speaking rate
voices = engine.getProperty("voices")
# choose a voice index if you want (0 or 1 usually)
if voices:
    engine.setProperty("voice", voices[0].id)

def speak(text: str):
    """Speak the given text and also print it."""
    print("Assistant:", text)
    engine.say(text)
    engine.runAndWait()

# ----------------- Greetings -----------------
def wish_me():
    hour = datetime.datetime.now().hour
    if 0 <= hour < 12:
        speak("Good morning!")
    elif 12 <= hour < 18:
        speak("Good afternoon!")
    else:
        speak("Good evening!")
    speak("I am your assistant. How can I help you today? You can say 'stop' to exit.")

# ----------------- Listening / Text fallback -----------------
def take_command(timeout=5, phrase_time_limit=6):
    """
    Listen from microphone and return recognized text (lowercased).
    If recognition fails, returns 'None'. Caller can fallback to text input.
    """
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 0.7
        r.energy_threshold = 300  # may need tuning per environment
        try:
            audio = r.listen(source, timeout=timeout, phrase_time_limit=phrase_time_limit)
        except sr.WaitTimeoutError:
            print("No speech detected (timeout).")
            return "None"
    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language="en-in")
        print(f"You said: {query}")
        return query.lower()
    except sr.UnknownValueError:
        print("Could not understand audio.")
        return "None"
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))
        return "None"

# ----------------- Utilities -----------------
def tell_time():
    str_time = datetime.datetime.now().strftime("%I:%M %p")
    speak(f"The current time is {str_time}")

def search_wikipedia(query: str, sentences=2):
    try:
        speak("Searching Wikipedia...")
        result = wikipedia.summary(query, sentences=sentences)
        speak("According to Wikipedia,")
        speak(result)
    except wikipedia.DisambiguationError as e:
        speak("There are multiple results for that. Please be more specific.")
        print(e.options[:10])
    except Exception as e:
        speak("Sorry, I couldn't fetch from Wikipedia.")
        print("Wikipedia error:", e)

def open_website(url):
    speak(f"Opening {url}")
    webbrowser.open(url)

# ----------------- Main loop -----------------
def main():
    wish_me()
    while True:
        query = take_command()

        # Fallback to text input when voice recognition fails
        if query == "None":
            speak("I didn't catch that. You can type your command or say 'stop' to exit.")
            try:
                query = input("Type command (or 'stop' to exit): ").strip().lower()
            except (KeyboardInterrupt, EOFError):
                speak("Exiting. Goodbye!")
                break

        if not query:
            continue

        # Exit conditions
        if any(term in query for term in ["exit", "quit", "stop", "goodbye", "bye"]):
            speak("Okay. Goodbye. Have a nice day!")
            break

        # Wikipedia search
        if "wikipedia" in query:
            # remove the word 'wikipedia' and search the rest
            q = query.replace("wikipedia", "").strip()
            if not q:
                speak("What should I search on Wikipedia?")
                q = input("Search Wikipedia for: ").strip()
            if q:
                search_wikipedia(q)
            continue

        # Tell time
        if "time" in query:
            tell_time()
            continue

        # Open websites
        if "open youtube" in query or "youtube" in query:
            open_website("https://www.youtube.com")
            continue
        if "open google" in query or "google" in query:
            open_website("https://www.google.com")
            continue
        if "open stackoverflow" in query or "stack overflow" in query:
            open_website("https://stackoverflow.com")
            continue

        # Simple conversation
        if any(greet in query for greet in ["hello", "hi", "hey"]):
            speak("Hello! How can I help you?")
            continue
        if "your name" in query or "who are you" in query:
            speak("I am Igris your assistant!")
            continue
        if "your level"in query:
            speak("My Current Level is 1... for feature My Boss Maharaja Updated me...")
        if "joke" in query:
            speak("Why did the programmer quit his job? Because he didn't get arrays.")
            continue

        # Web search: open google with query
        if query.startswith("search ") or query.startswith("google "):
            # remove leading keyword
            q = query.split(" ", 1)[1] if " " in query else ""
            if q:
                url = f"https://www.google.com/search?q={q.replace(' ', '+')}"
                open_website(url)
                continue

        # If not recognized command
        speak("Sorry, I don't know that command yet. You can ask me to search Wikipedia, tell time, open websites, or say 'stop' to exit.")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        speak("Interrupted by user. Shutting down.")
        try:
            sys.exit(0)
        except SystemExit:
            pass







Post a Comment

0 Comments