-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
321 lines (268 loc) · 11.1 KB
/
main.py
File metadata and controls
321 lines (268 loc) · 11.1 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"""
AURA Main Controller (V22.0 - GROQ AI INTEGRATED)
Features: Groq Llama 3 brain, Vosk wake word, gesture control, multiprocessing
"""
import sys
import os
import time
import signal
from multiprocessing import Process, Value, Queue, Array, freeze_support
from ctypes import c_char
# Ensure proper imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
from src.config import validate_config, print_config_summary, get_system_info
from src.voice_service import voice_process_loop
print("[Aura] ✓ Core modules loaded")
except Exception as e:
print(f"[Aura] ✗ Import error: {e}")
sys.exit(1)
# Try to import vision service (optional)
VISION_AVAILABLE = False
try:
from src.vision_service import vision_process_loop
VISION_AVAILABLE = True
print("[Aura] ✓ Vision module loaded")
except ImportError as e:
print(f"[Aura] ⚠ Vision not available: {e}")
except Exception as e:
print(f"[Aura] ⚠ Vision import error: {e}")
class SharedState:
"""Thread-safe shared state between processes"""
def __init__(self):
self.system_active = Value('b', True)
self.voice_enabled = Value('b', True)
self.vision_enabled = Value('b', True)
# Communication
self.command_queue = Queue()
# Shared buffers
self.last_app = Array(c_char, 100)
self.mode = Array(c_char, 20)
self.context = Array(c_char, 200)
# Initialize
self.set_last_app("")
self.set_mode("desktop")
self.set_context("")
def set_last_app(self, app_name: str):
"""Thread-safe setter"""
encoded = app_name.encode('utf-8')[:99]
with self.last_app.get_lock():
self.last_app.value = encoded
def get_last_app(self) -> str:
"""Thread-safe getter"""
with self.last_app.get_lock():
return self.last_app.value.decode('utf-8', errors='ignore').strip()
def set_mode(self, mode: str):
"""Thread-safe setter"""
encoded = mode.encode('utf-8')[:19]
with self.mode.get_lock():
self.mode.value = encoded
def get_mode(self) -> str:
"""Thread-safe getter"""
with self.mode.get_lock():
return self.mode.value.decode('utf-8', errors='ignore').strip()
def set_context(self, context: str):
"""Thread-safe setter"""
encoded = context.encode('utf-8')[:199]
with self.context.get_lock():
self.context.value = encoded
def get_context(self) -> str:
"""Thread-safe getter"""
with self.context.get_lock():
return self.context.value.decode('utf-8', errors='ignore').strip()
class AuraSystem:
"""Main system controller"""
def __init__(self):
self.shared_state = SharedState()
self.voice_process = None
self.vision_process = None
self.running = False
# Signal handlers
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
def _signal_handler(self, signum, frame):
"""Handle shutdown signals"""
print("\n[System] Shutdown signal received...")
self.shutdown()
sys.exit(0)
def startup(self, enable_vision=True):
"""Start all system components"""
print("\n" + "="*60)
print(" A U R A I N T E R F A C E V 2 2 . 0")
print(" Groq AI Brain + Gesture Control")
print("="*60)
# Validate configuration
if not validate_config():
print("\n[FATAL] Configuration validation failed!")
print("[FATAL] Please fix the errors above and restart.")
return False
# Print configuration summary
print_config_summary()
# Get system info
sys_info = get_system_info()
print("[System] Configuration validated.")
# Display feature status
print("\n[Features]")
print(f" • Wake Word Detection: {'✓ Enabled' if sys_info['vosk_model'] else '✗ Disabled'}")
print(f" • AI Brain (Groq): {'✓ Enabled' if sys_info['ai_mode'] else '✗ Disabled'}")
print(f" • Gesture Control: ✓ Enabled")
print(f" • Vision System: {'✓ Available' if VISION_AVAILABLE else '✗ Disabled'}")
# Start Voice Process
print("\n[System] Starting Voice Recognition...")
try:
self.voice_process = Process(
target=voice_process_loop,
args=(self.shared_state,),
name="Aura_Voice",
daemon=False
)
self.voice_process.start()
time.sleep(2.0) # Wait for initialization (AI brain needs more time)
if not self.voice_process.is_alive():
print("[Error] Voice process failed to start!")
return False
print("[System] ✓ Voice recognition online")
except Exception as e:
print(f"[Error] Failed to start voice: {e}")
import traceback
traceback.print_exc()
return False
# Start Vision Process (optional)
if enable_vision and VISION_AVAILABLE:
print("[System] Starting Vision System...")
try:
self.vision_process = Process(
target=vision_process_loop,
args=(self.shared_state,),
name="Aura_Vision",
daemon=False
)
self.vision_process.start()
time.sleep(0.5)
if self.vision_process.is_alive():
print("[System] ✓ Vision system online")
else:
print("[Warning] Vision process failed to start")
self.vision_process = None
except Exception as e:
print(f"[Warning] Vision not available: {e}")
self.vision_process = None
self.running = True
# Print usage instructions
self._print_instructions(sys_info)
return True
def _print_instructions(self, sys_info: dict):
"""Print usage instructions"""
print("\n" + "="*60)
print(">> SYSTEM ONLINE")
print("="*60)
if sys_info['vosk_model']:
print(f">> Wake Word: '{sys_info['wake_word']}'")
print(">>")
if sys_info['ai_mode']:
print(">> AI QUERIES (Groq Llama 3):")
print(" • 'Jarvis, what is quantum computing?'")
print(" • 'Jarvis, explain machine learning'")
print(" • 'Jarvis, tell me about black holes'")
print(" • 'Jarvis, how to learn Python?'")
print(">>")
print(">> GESTURE COMMANDS:")
print(" • 'Jarvis, open notepad'")
print(" • 'Jarvis, close spotify'")
print(" • 'Jarvis, play weekend on spotify'")
print(" • 'Jarvis, play Starboy on youtube'")
print(" • 'Jarvis, search Python tutorial'")
print(" • 'Jarvis, type hello world'")
print(" • 'Jarvis, close this tab'")
else:
print(">> Wake word detection disabled (Vosk model not found)")
print(">> System running in limited mode")
print(">>")
print(">> Press Ctrl+C to exit")
print("="*60 + "\n")
def monitor(self):
"""Monitor process health"""
try:
while self.running and self.shared_state.system_active.value:
# Check voice process
if self.voice_process and not self.voice_process.is_alive():
print("[Error] Voice process died. Restarting...")
try:
self.voice_process = Process(
target=voice_process_loop,
args=(self.shared_state,),
name="Aura_Voice",
daemon=False
)
self.voice_process.start()
time.sleep(2.0)
except Exception as e:
print(f"[Error] Failed to restart voice: {e}")
# Check vision process
if self.vision_process and not self.vision_process.is_alive():
print("[Warning] Vision process died")
self.vision_process = None
time.sleep(1.0)
except KeyboardInterrupt:
print("\n[System] Keyboard interrupt received")
except Exception as e:
print(f"[Error] Monitor error: {e}")
finally:
self.shutdown()
def shutdown(self):
"""Clean shutdown"""
if not self.running:
return
self.running = False
self.shared_state.system_active.value = False
print("\n[System] Shutting down...")
# Stop voice process
if self.voice_process:
print("[System] Stopping voice recognition...")
try:
self.voice_process.terminate()
self.voice_process.join(timeout=3)
if self.voice_process.is_alive():
print("[System] Force killing voice process")
self.voice_process.kill()
self.voice_process.join(timeout=1)
except Exception as e:
print(f"[Warning] Voice shutdown error: {e}")
# Stop vision process
if self.vision_process:
print("[System] Stopping vision system...")
try:
self.vision_process.terminate()
self.vision_process.join(timeout=3)
if self.vision_process.is_alive():
print("[System] Force killing vision process")
self.vision_process.kill()
self.vision_process.join(timeout=1)
except Exception as e:
print(f"[Warning] Vision shutdown error: {e}")
print("[System] Goodbye!\n")
def main():
"""Main entry point"""
freeze_support()
# Parse arguments
enable_vision = "--no-vision" not in sys.argv
# Create and start system
system = AuraSystem()
if system.startup(enable_vision=enable_vision):
try:
system.monitor()
except Exception as e:
print(f"[Fatal] System error: {e}")
import traceback
traceback.print_exc()
finally:
system.shutdown()
else:
print("\n[Fatal] System startup failed")
print("[Info] Check the errors above and:")
print(" 1. Ensure Vosk model is downloaded and extracted")
print(" 2. Set GROQ_API_KEY environment variable for AI features")
print(" 3. Run: python -m src.setup_check (if available)")
sys.exit(1)
if __name__ == "__main__":
main()