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
0 Comments