Repository navigation
Expand file tree
/
Copy pathactions.py
More file actions
235 lines (194 loc) · 9.03 KB
/
Copy pathactions.py
File metadata and controls
235 lines (194 loc) · 9.03 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""
Actions module for Stonic voice assistant
Contains functions for different actions (opening apps, websites, etc.)
"""
import os
import subprocess
import webbrowser
import datetime
import random
import logging
import time
import platform
import requests
import json
from typing import Optional, Dict, Any, List
from utils import (
APPLICATIONS,
WEBSITES,
USER_NAME,
extract_website_name,
extract_app_name,
get_time,
get_date,
log_command
)
logger = logging.getLogger("Stonic.Actions")
class ActionHandler:
"""Class to handle various actions based on commands"""
def __init__(self, speaker=None):
"""
Initialize the action handler
Args:
speaker: Speaker object for voice responses
"""
self.speaker = speaker
logger.info("ActionHandler initialized")
def process_command(self, command: str) -> bool:
"""
Process a voice command and execute the appropriate action
Args:
command (str): The voice command to process
Returns:
bool: True if a command was recognized and executed, False otherwise
"""
if not command:
return False
command = command.lower().strip()
logger.info(f"Processing command: '{command}'")
# Exit commands
if any(exit_cmd in command for exit_cmd in ["exit", "quit", "bye", "goodbye", "shutdown", "shut down"]):
self._execute_action(self._exit_stonic, "Exiting Stonic")
return True
# Time commands
if any(time_cmd in command for time_cmd in ["what time", "current time", "time now", "tell me the time"]):
self._execute_action(self._tell_time, "Telling the time")
return True
# Date commands
if any(date_cmd in command for date_cmd in ["what date", "current date", "date today", "tell me the date", "what day"]):
self._execute_action(self._tell_date, "Telling the date")
return True
# Open application commands
if "open" in command and any(app in command for app in APPLICATIONS.keys()):
app_name = extract_app_name(command)
if app_name:
self._execute_action(lambda: self._open_application(app_name), f"Opening {app_name}")
return True
# Open website commands
if any(web_cmd in command for web_cmd in ["open website", "go to", "visit", "browse"]):
website_name = extract_website_name(command)
if website_name:
self._execute_action(lambda: self._open_website(website_name), f"Opening {website_name}")
return True
# Special cases for common websites
if "youtube" in command:
self._execute_action(lambda: self._open_website("youtube"), "Opening YouTube")
return True
if "google" in command and "chrome" not in command:
self._execute_action(lambda: self._open_website("google"), "Opening Google")
return True
# Weather command (placeholder - would need API integration)
if any(weather_cmd in command for weather_cmd in ["weather", "temperature", "forecast"]):
self._execute_action(self._tell_weather, "Checking the weather")
return True
# Joke command
if any(joke_cmd in command for joke_cmd in ["joke", "funny", "make me laugh"]):
self._execute_action(self._tell_joke, "Telling a joke")
return True
# Help command
if any(help_cmd in command for help_cmd in ["help", "commands", "what can you do"]):
self._execute_action(self._tell_help, "Providing help information")
return True
# Who are you
if any(who_cmd in command for who_cmd in ["who are you", "your name", "introduce yourself"]):
self._execute_action(self._introduce_stonic, "Introducing myself")
return True
# No recognized command
logger.warning(f"Command not recognized: '{command}'")
if self.speaker:
self.speaker.command_not_recognized()
return False
def _execute_action(self, action_func, action_description):
"""
Execute an action and handle any errors
Args:
action_func: Function to execute
action_description: Description of the action for logging
"""
try:
logger.info(f"Executing action: {action_description}")
action_func()
log_command(action_description, successful=True)
except Exception as e:
logger.error(f"Error executing action '{action_description}': {e}")
log_command(action_description, successful=False)
if self.speaker:
self.speaker.unable_to_perform(action_description.lower())
def _open_application(self, app_name):
"""Open an application"""
if app_name in APPLICATIONS:
app_path = APPLICATIONS[app_name]
try:
# Different methods based on platform
if platform.system() == 'Windows':
os.startfile(app_path)
else:
subprocess.Popen([app_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if self.speaker:
self.speaker.confirm_action(f"opening {app_name}")
except Exception as e:
logger.error(f"Could not open application {app_name}: {e}")
if self.speaker:
self.speaker.unable_to_perform(f"open {app_name}")
else:
logger.warning(f"Application {app_name} not found in configured applications")
if self.speaker:
self.speaker.unable_to_perform(f"open {app_name}")
def _open_website(self, website_name):
"""Open a website"""
if website_name in WEBSITES:
url = WEBSITES[website_name]
try:
webbrowser.open(url)
if self.speaker:
self.speaker.confirm_action(f"opening {website_name}")
except Exception as e:
logger.error(f"Could not open website {website_name}: {e}")
if self.speaker:
self.speaker.unable_to_perform(f"open {website_name}")
else:
logger.warning(f"Website {website_name} not found in configured websites")
if self.speaker:
self.speaker.unable_to_perform(f"open {website_name}")
def _tell_time(self):
"""Tell the current time"""
current_time = get_time()
if self.speaker:
self.speaker.speak(current_time)
def _tell_date(self):
"""Tell the current date"""
current_date = get_date()
if self.speaker:
self.speaker.speak(current_date)
def _tell_weather(self):
"""Tell the current weather (placeholder)"""
# This would need API integration with a weather service
if self.speaker:
self.speaker.speak(f"I'm sorry, {USER_NAME}. Stonic doesn't have weather functionality implemented yet.")
def _tell_joke(self):
"""Tell a joke"""
jokes = [
f"Why don't scientists trust atoms? Because they make up everything, {USER_NAME}!",
f"Did you hear about the mathematician who's afraid of negative numbers? He'll stop at nothing to avoid them, {USER_NAME}!",
f"Why was the computer cold? It left its Windows open, {USER_NAME}!",
f"How many programmers does it take to change a light bulb? None, that's a hardware problem, {USER_NAME}!",
f"Why do programmers always mix up Halloween and Christmas? Because Oct 31 equals Dec 25, {USER_NAME}!"
]
if self.speaker:
joke = random.choice(jokes)
self.speaker.speak(joke)
def _tell_help(self):
"""Provide help information"""
help_text = f"Stonic can help you with various tasks, {USER_NAME}. You can ask me to open applications like Chrome or VS Code, open websites like YouTube or Google, tell you the time or date, tell a joke, or exit by saying goodbye."
if self.speaker:
self.speaker.speak(help_text)
def _introduce_stonic(self):
"""Introduce Stonic"""
intro_text = f"I am Stonic, your personal voice assistant, {USER_NAME}. I was designed to help you with everyday tasks through voice commands. I can open applications, browse websites, tell you the time, and more. Just ask if you need help."
if self.speaker:
self.speaker.speak(intro_text)
def _exit_stonic(self):
"""Exit Stonic"""
if self.speaker:
self.speaker.farewell()
# The actual exit occurs in the main loop