-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
243 lines (187 loc) · 7.61 KB
/
main.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
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
236
237
238
239
240
241
242
243
# Imports
import os
import sys
import json
import importlib
from importlib.machinery import SourceFileLoader
import utils.voice_recognizer as voice_recognizer
import utils.on_command as command
from colorama import Fore, init
import semantic_version
import requests
import keyboard
import time
import threading
commands = {} # ALL COMMANDS TO BE USED BY OPERATOR
wakewords = []
version_url = 'https://raw.githubusercontent.com/mattordev/coda/main/version.json'
manual_assisstant_input = False
if __name__ == "__main__":
if "-m" in sys.argv:
manual_assisstant_input = True
else:
manual_assisstant_input = False
def setup_commands():
command_file_location = os.getcwd() + "\commands\\"
sys.path.append(command_file_location)
# Clear the existing commands dictionary
commands.clear()
for cmdFile in os.listdir(command_file_location):
name = os.fsdecode(cmdFile)
if name.endswith(".py"):
command_path = os.path.join(command_file_location, cmdFile)
module = SourceFileLoader(name.split(
".py")[0].lower(), command_path).load_module()
commands[name.split(".py")[0].lower()] = module
# Save the commands to a JSON file after the setup is complete
print("Saving commands...")
save_commands()
def save_commands():
print("----------------------------------------", flush=True)
print("PRINTING FOUND COMMANDS:")
print(commands)
print("----------------------------------------")
serialized_commands = {}
for cmd_name, cmd_module in commands.items():
serialized_commands[cmd_name] = {
'module': cmd_module.__file__,
# Add any other relevant information from the module if needed
}
with open("commands.json", "w") as outfile:
json.dump(serialized_commands, outfile)
def load_commands():
commands = {}
serialized_commands = {} # Initialize to an empty dictionary
try:
# Add the directory to the module search path, without this, the commands won't load - need to make this universal across different machines.
sys.path.append('G:\\GitRepos\\coda\\commands')
with open("commands.json", "r") as infile:
try:
serialized_commands = json.load(infile)
except json.JSONDecodeError as e:
print(
"Error loading commands from JSON. Attempting to re-setup the commands...")
setup_commands()
# These commands won't load even though the commands.json file is present
commands = load_commands()
for cmd_name, cmd_data in serialized_commands.items():
module_path = cmd_data["module"]
# Add any other relevant information from the JSON if needed
# Get the module name from the file path
module_name = module_path.split("\\")[-1].split(".")[0]
# Load the module using spec_from_file_location
spec = importlib.util.spec_from_file_location(
module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Add the command to the dictionary
commands[cmd_name] = module
print("Commands loaded successfully.")
except FileNotFoundError as e:
raise e
return commands
def save_wakewords(wakewords):
print("Saving wakewords...")
jsonWakewords = json.dumps(wakewords)
jsonWakewordsFile = open("wakewords.json", "w")
jsonWakewordsFile.write(jsonWakewords)
jsonWakewordsFile.close()
print("Wakewords saved!")
def load_wakewords():
wakewords = ()
try:
with open("wakewords.json", "r") as infile:
# Store the loaded wakewords for string manipulation
serialized_wakewords = json.load(infile)
wakewords = json_dict_to_string_array(serialized_wakewords)
# print(wakewords)
except FileNotFoundError as e:
raise e
return wakewords
def check_update_available(version_url):
try:
with open("version.json", "r") as json_file:
json_data = json.load(json_file)
saved_version = semantic_version.Version(json_data['version'])
version_response = requests.get(version_url)
if version_response.status_code == 200:
response_json = version_response.json()
latest_version = response_json['version']
latest_semantic_version = semantic_version.Version(latest_version)
if latest_semantic_version > saved_version:
prompt = input(
"An update is available. Would you like to update? (y/n): ")
if prompt.lower() == "y":
# Update the program using the update_manager
import utils.update_manager as update_manager
update_manager.main()
return True # Updated successfully
else:
init(autoreset=True)
print(
Fore.RED + "Update aborted. Continuing with current version..")
return False # User chose not to update
except (IOError, KeyError, requests.RequestException, ValueError):
pass
return False
def start_voice_recognition():
voice_recognizer.run(wakewords, commands, type='normal')
def run_first_time_setup():
print("Commands file not found. Assuming first time setup...")
setup_commands()
save_wakewords(wakewords)
### UTIL FUNCTIONS ##
# These should probably be moved to a seperate .py file
def json_dict_to_string_array(jsonData):
string_array = []
for item in jsonData:
# Assuming the strings are at the top level of the json structure
if isinstance(item, str):
string_array.append(item)
return string_array
def toggle_input():
global manual_assisstant_input
manual_assisstant_input = not manual_assisstant_input
print(
f"Manual input mode {'enabled' if manual_assisstant_input else 'disabled'}")
#####################
### MAIN ###
startTimer = time.perf_counter()
wakewords = ["coda", "kodak", "coder", "skoda",
"powder", "kodi", "system", "jeff"]
if check_update_available(version_url):
# if there's an update available, re-find the commands
setup_commands()
print("Setting up commands as a new version was found...")
else:
try:
# load the commands from JSON.
commands = load_commands()
wakewords = load_wakewords()
# print(commands)
except FileNotFoundError:
run_first_time_setup()
load_time = time.perf_counter()
print(f"C.O.D.A loaded in {round(load_time-startTimer, 2)} second(s)")
# Create thread variable for calling the voice recog
voice_thread = threading.Thread(target=start_voice_recognition)
# Start the voice recognition thread
if not manual_assisstant_input:
voice_thread.start()
# Main loop
while True:
if manual_assisstant_input:
print("MANUAL MODE ENABLED")
manual_message = input("Please enter a command: ")
# This needs to ignore the wakeword still
command.run(manual_message, commands)
# Check for keyboard input to toggle back to voice input mode
# if keyboard.is_pressed('ctrl+b'):
# manual_assisstant_input = False
# voice_thread.start() # Start voice recognition thread again
else:
if keyboard.is_pressed('ctrl+b'):
manual_assisstant_input = True
print("VOICE RECOGNITION STOPPED. MANUAL MODE ENABLED")
voice_thread.join(timeout=0.1)
# Stop voice recognition thread