-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJarvis.py
123 lines (114 loc) · 4 KB
/
Jarvis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import speech_recognition as sr
import webbrowser
import pyttsx3
import pygame
import requests
import os
from gtts import gTTS
from openai import OpenAI
# Initialize components
recognizer = sr.Recognizer()
engine = pyttsx3.init()
news_api_key = "YOUR_NEWS_API_KEY" # Replace with your actual key
openai_api_key = "YOUR_OPENAI_API_KEY" # Replace with your actual key
# Command mappings
commands = {
"open google": lambda: webbrowser.open("https://www.google.com"),
"open facebook": lambda: webbrowser.open("https://www.facebook.com"),
"open youtube": lambda: webbrowser.open("https://www.youtube.com"),
"open linkedin": lambda: webbrowser.open("https://www.linkedin.com"),
}
music_library = {
"song1": "https://example.com/song1",
"song2": "https://example.com/song2",
# Add more songs here
}
# Speak using Google Text-to-Speech
def speak(text):
tts = gTTS(text)
tts.save("temp.mp3")
pygame.mixer.init()
pygame.mixer.music.load("temp.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
pygame.mixer.music.unload()
os.remove("temp.mp3")
# Fetch and read top news
def fetch_news():
try:
url = f"https://newsapi.org/v2/top-headlines?country=sa&apiKey={news_api_key}"
response = requests.get(url)
if response.status_code == 200:
articles = response.json().get("articles", [])[:5] # Limit to top 5 headlines
for article in articles:
speak(article["title"])
else:
speak("Unable to fetch news at the moment.")
except Exception as e:
print(f"Error fetching news: {e}")
speak("An error occurred while fetching news.")
# Handle OpenAI processing
def ai_process(command):
try:
client = OpenAI(api_key=openai_api_key)
completion = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a virtual assistant named Jarvis."},
{"role": "user", "content": command},
],
)
response = completion["choices"][0]["message"]["content"]
return response
except Exception as e:
print(f"Error with OpenAI API: {e}")
return "I'm sorry, I encountered an error with OpenAI."
# Process the user command
def process_command(command):
command = command.lower()
if command in commands:
commands[command]() # Execute mapped command
elif command.startswith("play"):
song = command.split(" ", 1)[-1]
if song in music_library:
webbrowser.open(music_library[song])
speak(f"Playing {song}.")
else:
speak("Sorry, I couldn't find that song.")
elif "news" in command:
fetch_news()
else:
response = ai_process(command)
speak(response)
# Listen for commands
def listen_for_command():
try:
with sr.Microphone() as source:
recognizer.adjust_for_ambient_noise(source) # Handle background noise
print("Listening...")
audio = recognizer.listen(source, timeout=5)
command = recognizer.recognize_google(audio)
return command
except sr.UnknownValueError:
speak("Sorry, I didn't catch that.")
except sr.WaitTimeoutError:
print("Listening timed out.")
return None
# Main loop
if __name__ == "__main__":
speak("Initializing Jarvis...")
while True:
try:
print("Say 'Jarvis' to activate.")
with sr.Microphone() as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source, timeout=5)
wake_word = recognizer.recognize_google(audio).lower()
if wake_word == "jarvis":
speak("Yes?")
command = listen_for_command()
if command:
process_command(command)
except Exception as e:
print(f"An error occurred: {e}")