voice_assistant_code
voice_assistant_code
import pyttsx3
import google.generativeai as genai
import wikipedia
import webbrowser
import time
import re
import math
from pygame import mixer
# 🔹 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."
# 🔹 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"))
else:
speak("I'm not sure how to respond to that.")
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.")