-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
187 lines (160 loc) · 5.98 KB
/
main.py
File metadata and controls
187 lines (160 loc) · 5.98 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"""
JARVIS - Virtual Assistant
==========================
A sophisticated voice-activated AI assistant
Features:
- OpenAI GPT integration for intelligent responses
- Wake word detection ("Jarvis")
- Voice synthesis with multiple TTS options
- Web browsing automation
- Music library integration
- News API integration
- Advanced speech recognition
"""
import speech_recognition as sr
import webbrowser
import pyttsx3
import musicLibrary
import requests
from openai import OpenAI
from gtts import gTTS
import pygame
import os
# Configuration - Replace with your actual API keys
OPENAI_API_KEY = "<Your OpenAI Key Here>"
NEWS_API_KEY = "<Your News API Key Here>"
# Initialize components
recognizer = sr.Recognizer()
engine = pyttsx3.init()
def speak_old(text):
"""Traditional TTS using pyttsx3"""
engine.say(text)
engine.runAndWait()
def speak(text):
"""Enhanced TTS using Google Text-to-Speech with pygame playback"""
try:
tts = gTTS(text)
tts.save('temp.mp3')
# Initialize Pygame mixer
pygame.mixer.init()
# Load and play the MP3 file
pygame.mixer.music.load('temp.mp3')
pygame.mixer.music.play()
# Keep the program running until the music stops playing
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
pygame.mixer.music.unload()
os.remove("temp.mp3")
except Exception as e:
print(f"TTS Error: {e}")
# Fallback to traditional TTS
speak_old(text)
def aiProcess(command):
"""Process commands using OpenAI GPT"""
try:
client = OpenAI(api_key=OPENAI_API_KEY)
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a virtual assistant named Jarvis skilled in general tasks like Alexa and Google Cloud. Give short responses please"},
{"role": "user", "content": command}
]
)
return completion.choices[0].message.content
except Exception as e:
return f"Sorry, I'm having trouble processing that request. Error: {str(e)}"
def processCommand(c):
"""Process voice commands and execute appropriate actions"""
command = c.lower()
# Web browsing commands
if "open google" in command:
webbrowser.open("https://google.com")
speak("Opening Google")
elif "open facebook" in command:
webbrowser.open("https://facebook.com")
speak("Opening Facebook")
elif "open youtube" in command:
webbrowser.open("https://youtube.com")
speak("Opening YouTube")
elif "open linkedin" in command:
webbrowser.open("https://linkedin.com")
speak("Opening LinkedIn")
# Music commands
elif command.startswith("play"):
try:
song = command.split(" ")[1]
link = musicLibrary.music[song]
webbrowser.open(link)
speak(f"Playing {song}")
except (IndexError, KeyError):
speak("Sorry, I couldn't find that song or you didn't specify a song name")
# News commands
elif "news" in command:
try:
r = requests.get(f"https://newsapi.org/v2/top-headlines?country=in&apiKey={NEWS_API_KEY}")
if r.status_code == 200:
data = r.json()
articles = data.get('articles', [])
speak("Here are the top headlines")
for i, article in enumerate(articles[:5]): # Limit to 5 headlines
speak(f"Headline {i+1}: {article['title']}")
else:
speak("Sorry, I couldn't fetch the news right now")
except Exception as e:
speak("There was an error getting the news")
print(f"News Error: {e}")
# AI-powered responses for everything else
else:
output = aiProcess(c)
speak(output)
def main():
"""Main function"""
speak("Initializing Jarvis....")
print("🤖 JARVIS Virtual Assistant")
print("Say 'Jarvis' to wake me up, then give your command")
print("=" * 50)
while True:
# Listen for the wake word "Jarvis"
r = sr.Recognizer()
print("Recognizing...")
try:
with sr.Microphone() as source:
print("Listening for wake word...")
audio = r.listen(source, timeout=2, phrase_time_limit=1)
word = r.recognize_google(audio)
if word.lower() == "jarvis":
speak("Yes?")
# Listen for command
with sr.Microphone() as source:
print("Jarvis Active... Listening for command...")
audio = r.listen(source)
command = r.recognize_google(audio)
print(f"Command: {command}")
processCommand(command)
except sr.UnknownValueError:
# Didn't recognize speech, continue listening
pass
except sr.RequestError as e:
print(f"Could not request results; {e}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
# Check if required files exist
try:
import musicLibrary
main()
except ImportError:
print("⚠️ musicLibrary.py not found! Creating it now...")
# Create musicLibrary.py if it doesn't exist
with open("musicLibrary.py", "w") as f:
f.write('''# Music Library - Add your favorite songs here
music = {
"stealth": "https://www.youtube.com/watch?v=U47Tr9BB_wE",
"march": "https://www.youtube.com/watch?v=Xqeq4b5u_Xw",
"skyfall": "https://www.youtube.com/watch?v=DeumyOzKqgI&pp=ygUHc2t5ZmFsbA%3D%3D",
"wolf": "https://www.youtube.com/watch?v=ThCH0U6aJpU&list=PLnrGi_-oOR6wm0Vi-1OsiLiV5ePSPs9oF&index=21"
}
''')
print("✅ musicLibrary.py created! You can now run the assistant.")
import musicLibrary
main()