import speech_recognition as sr
import pyttsx3
import google.generativeai as genai
import wikipedia
import webbrowser
import time
import re
import math
from pygame import mixer
# 🔹 Configure Google Gemini API
GEMINI_API_KEY = "AIzaSyAaqNVkIQTJ9x3Pqr8euu1-jXP8LeGwLkM"
genai.configure(api_key=GEMINI_API_KEY)
# 🔹 Initialize text-to-speech engine
engine = pyttsx3.init()
engine.setProperty('rate', 180)
# 🔹 Initialize pygame mixer for music playback
mixer.init()
# 🔹 Speak Function
def speak(text):
"""Convert text to speech."""
print(f"🤖 Assistant: {text}")
engine.say(text)
engine.runAndWait()
# 🔹 Recognize Speech
def listen():
"""Recognize user speech and return text."""
recognizer = sr.Recognizer()
with sr.Microphone() as source:
recognizer.adjust_for_ambient_noise(source)
print("🎤 Listening...")
try:
audio = recognizer.listen(source, timeout=6)
user_input = recognizer.recognize_google(audio).lower()
print(f" You: {user_input}") # Display user input in
terminal
return user_input
except sr.UnknownValueError:
print("Sorry, I didn't understand.")
return ""
except sr.RequestError:
print("Could not request results, check your internet
connection.")
return ""
# 🔹 Get Gemini AI Response
def get_gemini_response(prompt):
"""Fetch a response from Google Gemini AI."""
try:
model = genai.GenerativeModel("gemini-1.5-pro")
response = model.generate_content(prompt)
return response.text if hasattr(response, 'text') else "Sorry,
I couldn't generate a response."
except Exception as e:
return f"Error communicating with Gemini API: {str(e)}"
# 🔹 Wikipedia Search
def search_wikipedia(topic):
"""Search Wikipedia for a topic."""
try:
summary = wikipedia.summary(topic, sentences=2)
return summary
except wikipedia.exceptions.DisambiguationError as e:
return f"Multiple results found: {e.options[:3]}"
except wikipedia.exceptions.PageError:
return "Sorry, I couldn't find anything on Wikipedia."
# 🔹 Online Search
def search_online(query):
"""Perform a Google search and return the top results."""
url = f"https://www.google.com/search?q={query.replace(' ', '+')}"
webbrowser.open(url)
return "Here are some results I found."
# 🔹 Handle Mathematical Expressions
def handle_math_expression(expression):
"""Evaluate a mathematical expression."""
try:
# Remove any non-math characters
expression = re.sub(r'[^0-9+\-*/() .]', '', expression)
result = eval(expression)
return f"The result is {result}."
except Exception as e:
return f"Sorry, I couldn't evaluate the expression: {str(e)}"
# 🔹 Play Music
def play_music(file_path):
"""Play a music file."""
try:
mixer.music.load(file_path)
mixer.music.play()
return "Playing music."
except Exception as e:
return f"Sorry, I couldn't play the music: {str(e)}"
# 🔹 Handle Commands
def handle_command(command):
"""Process user commands and perform actions."""
if "time" in command:
speak("The current time is " + time.strftime("%I:%M %p"))
elif "open youtube" in command:
webbrowser.open("https://www.youtube.com")
speak("Opening YouTube.")
elif "open google" in command:
webbrowser.open("https://www.google.com")
speak("Opening Google.")
elif "open wikipedia" in command:
webbrowser.open("https://www.wikipedia.org")
speak("Opening Wikipedia.")
elif "search wikipedia for" in command:
topic = command.replace("search wikipedia for", "").strip()
if topic:
speak("Searching Wikipedia...")
result = search_wikipedia(topic)
speak(result)
else:
speak("Please specify a topic.")
elif "search online for" in command:
query = command.replace("search online for", "").strip()
if query:
speak("Searching online...")
search_online(query)
else:
speak("Please specify a search query.")
elif "tell me about" in command:
query = command.replace("tell me about", "").strip()
if query:
speak("Let me check...")
response = get_gemini_response(query)
speak(response)
else:
speak("Please specify a topic.")
elif "what is" in command and ("+" in command or "-" in command or
"*" in command or "/" in command):
expression = command.replace("what is", "").strip()
result = handle_math_expression(expression)
speak(result)
elif "play music" in command:
speak("Playing music.")
play_music("path_to_music_file.mp3") # Replace with the actual
path to your music file
elif "exit" in command or "goodbye" in command or "stop" in
command:
speak("Goodbye! Have a great day!")
return False # Stops the loop
else:
speak("I'm not sure how to respond to that.")
return True # Continue running
# 🔹 Main Assistant Loop
def main():
"""Main function to run the voice assistant."""
speak("Hey! I'm your voice assistant. Say 'Hey Assistant' to
activate me.")
while True:
command = listen()
if "hey assistant" in command:
speak("Yes, how can I help?")
while True:
command = listen()
if command:
if "stop" in command: # Check for "stop" command
speak("Let me know if you want anything. Have a
great day!")
return # Exit the assistant
if not handle_command(command):
return # Properly exit when "exit" or
"goodbye" is spoken
else:
speak("I didn't catch that. Try again.")
# 🔹 Run the Assistant
if __name__ == "__main__":
main()