-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassistant.py
More file actions
170 lines (151 loc) · 5.83 KB
/
assistant.py
File metadata and controls
170 lines (151 loc) · 5.83 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
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import os
import sys
# Initialize speech engine
try:
engine = pyttsx3.init()
engine.setProperty('rate', 170) # Speed of speech
voices = engine.getProperty('voices')
# Try to set a female voice if available
try:
engine.setProperty('voice', voices[1].id) # Female voice
except:
try:
engine.setProperty('voice', voices[0].id) # Fallback to default voice
except:
pass
except Exception as e:
print(f"Error initializing text-to-speech engine: {e}")
print("Text-to-speech might not work properly.")
def talk(text):
print("🎙️ UDAY:", text)
try:
engine.say(text)
engine.runAndWait()
except Exception as e:
print(f"Error in speech synthesis: {e}")
def take_command():
listener = sr.Recognizer()
with sr.Microphone() as source:
print("🎧 Listening...")
talk("I'm listening, please speak...")
listener.pause_threshold = 1
listener.energy_threshold = 300
try:
audio = listener.listen(source, timeout=5, phrase_time_limit=5)
print("Processing your command...")
command = listener.recognize_google(audio, language='en-in')
command = command.lower()
print("🗣️ You said:", command)
return command
except sr.WaitTimeoutError:
print("No command detected.")
return ""
except sr.UnknownValueError:
talk("Sorry bro, I didn't catch that. Could you please repeat?")
return ""
except sr.RequestError as e:
talk("Could not request results; check your internet connection.")
print(f"Could not request results; {e}")
return ""
except Exception as e:
talk("Sorry, I encountered an error.")
print(f"Error: {e}")
return ""
def run_uday():
command = take_command().lower()
if not command:
return
elif "play" in command:
song = command.replace("play", "").replace("youtube", "").replace("on", "").strip()
if song:
talk(f"Playing {song} on YouTube for you 🎶")
try:
pywhatkit.playonyt(song)
except Exception as e:
print(f"Error playing video: {e}")
talk("Sorry, I couldn't play that on YouTube. Please check your internet connection.")
else:
talk("Please tell me what song or video you'd like me to play.")
elif any(phrase in command for phrase in ["what's the time", "what time is it", "tell me the time"]):
time = datetime.datetime.now().strftime('%I:%M %p')
talk(f"It's {time} ⏰")
elif any(phrase in command for phrase in ["who is uday codes", "who is uday_codes"]):
info = (
"Uday, known as uday_codes on Instagram, is a coding content creator. "
"He teaches Python projects in Telugu and runs udaycodes.in 💻"
)
talk(info)
elif command.startswith("who is "):
person = command.replace("who is ", "").strip()
if person:
try:
info = wikipedia.summary(person, sentences=2)
talk(f"Here's what I found about {person}:")
talk(info)
except Exception as e:
print(f"Error: {e}")
talk(f"Sorry, I couldn't find information about {person}.")
else:
talk("Could you please tell me who you want to know about?")
elif "joke" in command or "make me laugh" in command:
joke = pyjokes.get_joke()
talk("Here's a joke for you!")
print(f"🎭 Joke: {joke}")
talk(joke)
elif any(phrase in command for phrase in ["open chrome", "start chrome"]):
chrome_paths = [
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
]
for path in chrome_paths:
if os.path.exists(path):
talk("Opening Chrome 🚀")
os.startfile(path)
return
talk("I couldn't find Chrome on your system. Is it installed?")
elif any(phrase in command for phrase in ["open code", "open vs code", "open visual studio code"]):
try:
talk("Opening VS Code 💻")
os.system("code")
except Exception as e:
print(f"Error: {e}")
talk("I couldn't open VS Code. Is it installed and in your system path?")
elif any(phrase in command for phrase in ["exit", "stop", "goodbye", "bye", "quit"]):
talk("Okay, see you later! Have a great day! This is UDAY signing off. 👋")
cleanup()
sys.exit(0)
elif command:
talk("I'm not sure how to help with that. Could you try something else?")
def cleanup():
try:
if 'engine' in globals():
engine.stop()
except Exception as e:
print(f"Error during cleanup: {e}")
if __name__ == "__main__":
try:
# Register cleanup function
import atexit
atexit.register(cleanup)
# Start the assistant
talk("Hello! I'm UDAY – your personal voice assistant. How can I help you today? 💡")
while True:
run_uday()
except KeyboardInterrupt:
print("\nGoodbye! Thanks for using UDAY. 👋")
cleanup()
sys.exit(0)
except Exception as e:
print(f"\nAn error occurred: {e}")
try:
talk("Sorry, I encountered an error. Please restart me.")
except:
print("Could not speak the error message.")
cleanup()
sys.exit(1)