# Import necessary libraries
import os
import speech_recognition as sr # For voice recognition
import pyttsx3 # For text-to-speech
import datetime # For time-related tasks
import webbrowser # For opening websites
from dotenv import load_dotenv # For managing environment variables
# Load environment variables (for API keys, etc.)
load_dotenv()
# Define the Jarvis class
class Jarvis:
def __init__(self):
# Initialize text-to-speech engine
self.engine = pyttsx3.init()
self.recognizer = sr.Recognizer() # Initialize voice recognizer
self.voices = self.engine.getProperty('voices')
self.engine.setProperty('voice', self.voices[1].id) # Set voice (0 for male, 1 for female)
self.engine.setProperty('rate', 150) # Set speech speed
# Function to make Jarvis speak
def speak(self, text):
print(f"JARVIS: {text}") # Print text in the console
self.engine.say(text) # Convert text to speech
self.engine.runAndWait() # Wait for speech to finish
# Function to listen to user commands
def listen(self):
with sr.Microphone() as source: # Use microphone as audio source
print("Listening...")
audio = self.recognizer.listen(source) # Listen to the user's voice
try:
# Convert speech to text using Google's speech recognition
command = self.recognizer.recognize_google(audio)
print(f"YOU: {command}") # Print the user's command
return command.lower() # Return the command in lowercase
except Exception as e:
self.speak("Sorry, I didn't catch that") # Handle errors
return ""
# Function to greet the user based on the time of day
def greet(self):
hour = datetime.datetime.now().hour # Get the current hour
if 5 <= hour < 12:
self.speak("Good morning!")
elif 12 <= hour < 18:
self.speak("Good afternoon!")
else:
self.speak("Good evening!")
# Function to execute user commands
def execute_command(self, command):
if 'time' in command: # Tell the current time
current_time = datetime.datetime.now().strftime("%I:%M %p")
self.speak(f"The current time is {current_time}")
elif 'open youtube' in command: # Open YouTube
self.speak("Opening YouTube")
webbrowser.open("https://youtube.com")
elif 'search web' in command: # Search the web
query = command.replace("search web", "")
webbrowser.open(f"https://google.com/search?q={query}")
elif 'exit' in command or 'bye' in command: # Exit the program
self.speak("Goodbye!")
exit()
# Main program
if __name__ == "__main__":
jarvis = Jarvis() # Create an instance of Jarvis
jarvis.greet() # Greet the user
jarvis.speak("How can I assist you today?") # Ask for commands
# Continuously listen for commands
while True:
command = jarvis.listen() # Listen to the user
if command:
jarvis.execute_command(command) # Execute the command
AtmosPro - Premium Weather Intelligence AtmosPro Premium Atmospheric Intelligence Suite Analyze New York City, US 22 °C Humidity 65% Wind 5.2 m/s Visibility 10 km Feels Like 24°C Advanced Metrics ...
Comments