-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhal_voice_assistant.py.my_broken_version
More file actions
1248 lines (1018 loc) Β· 44 KB
/
hal_voice_assistant.py.my_broken_version
File metadata and controls
1248 lines (1018 loc) Β· 44 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
HAL Voice Assistant with Eel GUI
Combines Voice Pipeline V2 + MCP Tools + LLM
"""
import eel
import asyncio
import logging
import sys
import threading
import json
from pathlib import Path
import pyttsx3
# Add parent directory to path for HAL imports
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import get_config
from voice_pipeline_v2 import VoicePipelineV2
# Import HAL MCP components
from hal_mcp_manager import HALMCPManager
from hal_intent_matcher import HALIntentMatcher
import ollama
# Setup logging - configure root logger to catch all subsystem logs
log_file = Path(__file__).parent / 'hal_voice_assistant.log'
logging.basicConfig(
level=logging.DEBUG, # Capture all log levels
format='%(asctime)s - [%(levelname)s] - %(name)s - %(message)s',
datefmt='%H:%M:%S',
handlers=[
logging.StreamHandler(sys.stderr), # Write to stderr
logging.FileHandler(log_file, mode='w') # Also write to file
],
force=True # Force reconfiguration even if already configured
)
logger = logging.getLogger(__name__)
logger.info(f"Logging to: {log_file}")
# Set specific log levels for noisy libraries
logging.getLogger('eel').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.getLogger('mcp').setLevel(logging.INFO)
# Initialize Eel
eel.init('web')
# Global state
app_state = {
'listening': False,
'speaking_enabled': True, # Can toggle TTS on/off
'status': 'initializing',
'wake_word': 'hal',
'language': 'en',
'current_page': 'home',
'navigation_stack': [],
'movie_playing': {
'active': False,
'title': '',
'duration': 0,
'saved_listening': False,
'saved_speaking': False,
'timer': None
}
}
# Components
voice_pipeline = None
mcp_manager = None
intent_matcher = None
ollama_client = None
config = None
voice_loop_thread = None
voice_loop_event_loop = None
mcp_thread = None # Thread running MCP event loop
mcp_event_loop = None # Event loop where MCP manager lives
tts_engine = None # TTS engine
def run_mcp_thread():
"""Run MCP manager in its own thread with persistent event loop"""
global mcp_event_loop, mcp_manager, config
# Create new event loop for this thread
mcp_event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(mcp_event_loop)
logger.info("MCP thread started")
async def init_mcp():
global mcp_manager
# Initialize MCP Manager
logger.info("π Initializing MCP tools...")
mcp_manager = HALMCPManager()
# Load MCP servers
import json
mcp_config_path = config.MCP_SERVERS_CONFIG if hasattr(config, 'MCP_SERVERS_CONFIG') else '../mcp-servers.json'
with open(mcp_config_path, 'r') as f:
mcp_config = json.load(f)
servers_config = mcp_config.get("mcpServers", mcp_config)
await mcp_manager.connect_servers(servers_config)
logger.info(f"β
Connected to {len(mcp_manager.sessions)} MCP servers")
# Keep event loop running
while True:
await asyncio.sleep(1)
try:
mcp_event_loop.run_until_complete(init_mcp())
except Exception as e:
logger.error(f"MCP thread error: {e}", exc_info=True)
finally:
mcp_event_loop.close()
logger.info("MCP thread stopped")
def initialize_tts():
"""Initialize Text-to-Speech engine"""
global tts_engine, config
try:
logger.info("Initializing TTS engine...")
tts_engine = pyttsx3.init()
# Configure from settings
tts_engine.setProperty('rate', config.TTS_RATE)
tts_engine.setProperty('volume', config.TTS_VOLUME)
# Set voice if specified
if config.TTS_VOICE:
voices = tts_engine.getProperty('voices')
for voice in voices:
if config.TTS_VOICE in voice.id:
tts_engine.setProperty('voice', voice.id)
logger.info(f"TTS voice set to: {voice.id}")
break
logger.info("β
TTS engine initialized")
return True
except Exception as e:
logger.error(f"TTS initialization failed: {e}")
return False
def speak(text):
"""Speak text using TTS (non-blocking)"""
global tts_engine, app_state
# Check if speaking is enabled
if not app_state.get('speaking_enabled', True):
logger.info(f"π Speaking disabled, skipping: {text[:100]}...")
return
if not tts_engine:
logger.warning("TTS not initialized, skipping speak")
return
try:
logger.info(f"π Speaking: {text[:100]}...")
tts_engine.say(text)
tts_engine.runAndWait()
except Exception as e:
logger.error(f"TTS speak error: {e}")
async def initialize_system():
"""Initialize all systems"""
global voice_pipeline, intent_matcher, ollama_client, config, mcp_thread
try:
eel_log("π Initializing HAL Voice Assistant...")
# Load config
config = get_config()
app_state['wake_word'] = config.WAKE_WORD
# Initialize Voice Pipeline
eel_log("π€ Initializing voice pipeline...")
voice_pipeline = VoicePipelineV2(config)
if not await voice_pipeline.initialize():
raise Exception("Voice pipeline initialization failed")
eel_log("β
Voice pipeline ready")
# Initialize TTS
eel_log("π Initializing text-to-speech...")
if initialize_tts():
eel_log("β
TTS ready")
else:
eel_log("β οΈ TTS initialization failed (will continue without speech)")
# Start MCP manager in its own thread
eel_log("π Starting MCP manager thread...")
mcp_thread = threading.Thread(target=run_mcp_thread, daemon=True)
mcp_thread.start()
# Wait for MCP manager to be initialized
timeout = 10
for i in range(timeout * 10):
await asyncio.sleep(0.1)
if mcp_manager is not None:
eel_log(f"β
MCP manager ready")
break
else:
raise Exception("MCP manager initialization timeout")
# Initialize Intent Matcher
intent_mapping_path = config.INTENT_MAPPING if hasattr(config, 'INTENT_MAPPING') else '../intent-mapping.json'
intent_matcher = HALIntentMatcher(mapping_file=intent_mapping_path)
eel_log(f"β
Loaded {len(intent_matcher.intents)} intents")
# Initialize Ollama client
ollama_url = config.OLLAMA_URL if hasattr(config, 'OLLAMA_URL') else "http://localhost:11434"
ollama_client = ollama.Client(host=ollama_url)
eel_log(f"β
Ollama client ready ({ollama_url})")
app_state['status'] = 'ready'
eel_update_status('ready', 'Ready - Say "{}" to activate'.format(app_state['wake_word']))
return True
except Exception as e:
logger.error(f"Initialization failed: {e}", exc_info=True)
eel_log(f"β Initialization failed: {e}")
app_state['status'] = 'error'
return False
async def voice_loop():
"""Main voice interaction loop"""
global voice_pipeline, app_state
logger.info("π€ Voice loop started!")
eel_log("π€ Voice loop started!")
while app_state['listening']:
try:
# Update UI
logger.info(f"π Listening for wake word: {app_state['wake_word']}")
eel_update_status('listening', f'Listening for "{app_state["wake_word"]}"...')
# Wait for wake word and get transcription
logger.info("Calling listen_and_transcribe()...")
text = await voice_pipeline.listen_and_transcribe()
if not text:
logger.info("No text received, continuing...")
continue
logger.info("="*80)
logger.info(f"π TRANSCRIPTION: '{text}'")
logger.info("="*80)
# Filter out TTS feedback (when microphone picks up the speaker output)
# Common phrases from agent responses that shouldn't be processed as commands
tts_feedback_phrases = [
"completed successfully",
"operations completed",
"task completed",
"request completed",
"all done",
"finished successfully"
]
text_lower = text.lower()
if any(phrase in text_lower for phrase in tts_feedback_phrases):
logger.warning(f"β οΈ Ignoring TTS feedback: '{text}'")
eel_log(f"β οΈ Filtered TTS echo")
continue
# Update UI with transcription
eel_update_transcript(text)
eel_update_status('processing', 'Processing your request...')
# Process the command
response = await process_command(text)
# Update UI with response
eel_update_response(response)
eel_update_status('speaking', 'Speaking response...')
# Speak response using TTS
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, speak, response)
# Wait longer to ensure TTS audio has finished and microphone buffer is clear
# This prevents the microphone from picking up the TTS output as a new command
await asyncio.sleep(3.0) # Increased from 0.5s to prevent audio feedback loop
except Exception as e:
logger.error(f"Voice loop error: {e}", exc_info=True)
eel_log(f"β Error: {e}")
await asyncio.sleep(2)
logger.info("π Voice loop stopped")
eel_log("π Voice loop stopped")
async def resolve_movie_filename(partial_name: str) -> str:
"""
Resolve a partial movie name to a full filename by fuzzy matching against available movies
Args:
partial_name: Partial movie name (e.g., "superman")
Returns:
Full filename (e.g., "Superman.mp4") or original if no match found
"""
try:
# Call list_movies to get available movies
logger.debug(f"Resolving movie filename for: {partial_name}")
# Call MCP tool on MCP event loop
future = asyncio.run_coroutine_threadsafe(
mcp_manager.call_tool("media-server", "list_movies", {}),
mcp_event_loop
)
result = future.result(timeout=10)
# Parse the result - it's in text format with numbered list
# Format: "1. Filename.mp4\n Path: ...\n Size: ...\n Type: ...\n"
import re
movie_names = []
# Extract movie filenames from numbered list (e.g., "1. Superman.mp4")
for line in result.split('\n'):
# Match lines like "1. Superman.mp4" or "5. Superman.mp4"
match = re.match(r'^\d+\.\s+(.+\.(mp4|mkv|avi|mov))\s*$', line.strip())
if match:
movie_names.append(match.group(1))
if not movie_names:
logger.warning(f"No movie files found in list_movies result")
logger.debug(f"Result: {result[:500]}")
return partial_name
logger.debug(f"Found {len(movie_names)} movies: {movie_names}")
# Fuzzy match the partial name against movie filenames
partial_lower = partial_name.lower()
best_match = None
best_score = 0
for movie_name in movie_names:
movie_name_lower = movie_name.lower()
# Remove extension for comparison
movie_base = movie_name_lower.rsplit('.', 1)[0] if '.' in movie_name_lower else movie_name_lower
# Simple fuzzy matching - check if partial name is in movie name
if partial_lower in movie_base:
# Score by length difference (prefer closer matches)
score = 100 - abs(len(movie_base) - len(partial_lower))
if score > best_score:
best_score = score
best_match = movie_name
# Exact match
elif partial_lower == movie_base:
best_match = movie_name
break
if best_match:
logger.info(f"Matched '{partial_name}' to '{best_match}'")
return best_match
else:
logger.warning(f"No movie match found for '{partial_name}'")
return partial_name
except Exception as e:
logger.error(f"Error resolving movie filename: {e}", exc_info=True)
return partial_name
async def use_llm_agent(user_text: str) -> str:
"""
Use LLM agent with tool calling to handle complex requests
Args:
user_text: User's request
Returns:
Agent's response after tool execution
"""
try:
# Get list of available MCP tools
all_tools = mcp_manager.get_all_tools()
# Build tools description for prompt
tools_desc = []
for tool_info in all_tools:
server = tool_info.get("server", "")
tool_name = tool_info.get("tool", "")
description = tool_info.get("description", "")
tools_desc.append(f"- {server}.{tool_name}: {description}")
tools_prompt = "\n".join(tools_desc)
# System prompt for agent
system_prompt = f"""You are an expert at breaking down complex user requests into function calls.
Available functions:
{tools_prompt}
Respond with JSON only:
{{"function":"function_name","describe":"brief intent","parameter":"value_or_json"}}
IMPORTANT RULES:
1. You must actually CALL the functions, not just describe what you would do
2. Only call "finished" AFTER you have called all necessary functions
3. For media-server.play_movie, use ONLY the filename (e.g. "nonexistantmovie.mp4"), NOT the full path
4. When list_movies shows "1. nonexistantmovie.mp4", use "nonexistantmovie.mp4" as the filename parameter
5. For movie selection: First call list_movies, then call "select_movie" to let the system pick the best match from available movies"""
# Run agent loop
logger.info("="*80)
logger.info(f"π€ STARTING LLM AGENT")
logger.info(f" User query: {user_text}")
logger.info("="*80)
conversation = [{"role": "user", "content": user_text}]
max_iterations = 5
for iteration in range(max_iterations):
logger.info("-"*80)
logger.info(f"π AGENT ITERATION {iteration + 1}/{max_iterations}")
logger.info("-"*80)
# Get LLM response with structured output
model = config.OLLAMA_AGENT_MODEL if hasattr(config, 'OLLAMA_AGENT_MODEL') else 'qwen2.5:3b'
logger.info(f"π¬ LLM CALL")
logger.info(f" Model: {model}")
logger.info(f" System prompt:")
logger.info("-"*80)
logger.info(system_prompt)
logger.info("-"*80)
logger.info(f" Conversation messages:")
for i, msg in enumerate(conversation):
logger.info(f" Message {i+1} ({msg['role']}): {msg['content'][:500]}")
logger.info("-"*80)
response = ollama_client.chat(
model=model,
messages=[{"role": "system", "content": system_prompt}] + conversation,
format={
"type": "object",
"properties": {
"function": {"type": "string"},
"describe": {"type": "string"},
"parameter": {"type": "string"}
},
"required": ["function", "describe", "parameter"]
}
)
tool_call = response['message']['content']
logger.info(f"π¬ LLM RESPONSE: {tool_call}")
# Parse tool call
import json
try:
call_data = json.loads(tool_call)
function_name = call_data.get("function", "")
describe = call_data.get("describe", "")
parameter_str = call_data.get("parameter", "{}")
logger.info(f"Agent calling: {function_name} - {describe}")
eel_log(f"π€ {describe}")
# Check if finished
if function_name == "finished":
return describe
# Handle special "select_movie" function (with or without server prefix)
if function_name == "select_movie" or function_name.endswith(".select_movie"):
# Extract movie list from conversation history
movie_list = []
for msg in reversed(conversation):
if msg['role'] == 'user' and 'Tool result:' in msg['content']:
# Parse movie list from previous list_movies result
result_text = msg['content']
if 'Available movies:' in result_text or '.mp4' in result_text or '.mkv' in result_text:
# Extract movie filenames
import re
matches = re.findall(r'\d+\.\s+([^\n]+)', result_text)
if matches:
movie_list = matches
break
if movie_list:
# Ask LLM to select best match
logger.info("="*80)
logger.info(f"π¬ EXPLICIT MOVIE SELECTION")
logger.info(f" User wants: {user_text}")
logger.info(f" Available movies: {movie_list}")
logger.info("="*80)
# Create simple movie list without numbering
movie_titles = ', '.join([f'"{m}"' for m in movie_list])
selection_prompt = f"""Of the movies {movie_titles}, which one best matches: {user_text}
Respond with only the filename from the list above, nothing else."""
logger.info(f"π SELECTION PROMPT:")
logger.info("-"*80)
logger.info(selection_prompt)
logger.info("-"*80)
selection_response = ollama_client.chat(
model=model,
messages=[{"role": "user", "content": selection_prompt}]
)
selected_movie = selection_response['message']['content'].strip()
logger.info(f"π¬ LLM SELECTED: {selected_movie}")
logger.info(f" Model used: {model}")
logger.info(f" Full LLM response: {selection_response['message']['content']}")
logger.info("="*80)
# Add to conversation
conversation.append({"role": "assistant", "content": tool_call})
conversation.append({
"role": "user",
"content": f"Selected movie: {selected_movie}\n\nNow play this movie using media-server.play_movie"
})
continue
else:
logger.warning("No movie list found in conversation history")
conversation.append({"role": "assistant", "content": tool_call})
conversation.append({
"role": "user",
"content": "Error: No movie list available. Please call list_movies first."
})
continue
# Parse function name (format: server.tool)
if "." in function_name:
server_name, tool_name = function_name.split(".", 1)
else:
logger.warning(f"Invalid function format: {function_name}")
continue
# Parse parameters
try:
params = json.loads(parameter_str) if parameter_str else {}
except json.JSONDecodeError:
params = {"filename": parameter_str} if parameter_str else {}
# Execute MCP tool on MCP thread
logger.info("="*80)
logger.info(f"π§ MCP CALL (from agent)")
logger.info(f" Server: {server_name}")
logger.info(f" Tool: {tool_name}")
logger.info(f" Parameters: {params}")
logger.info(f" Call point: hal_voice_assistant.py:use_llm_agent")
logger.info("="*80)
future = asyncio.run_coroutine_threadsafe(
mcp_manager.call_tool(server_name, tool_name, params),
mcp_event_loop
)
tool_result = future.result(timeout=30)
logger.info("="*80)
logger.info(f"β
MCP RESULT: {tool_result[:500] if len(tool_result) > 500 else tool_result}")
logger.info("="*80)
# Add to conversation
conversation.append({"role": "assistant", "content": tool_call})
conversation.append({
"role": "user",
"content": f"Tool result: {tool_result}\n\nContinue if needed, or call 'finished' if done."
})
except json.JSONDecodeError as e:
logger.error(f"Failed to parse agent response: {e}")
return "Sorry, I had trouble understanding how to help with that."
return "Task completed"
except Exception as e:
logger.error(f"LLM agent error: {e}", exc_info=True)
return f"Sorry, I encountered an error: {str(e)}"
async def process_command(user_text: str) -> str:
"""
Process user command through MCP tools or LLM
Args:
user_text: Transcribed user speech
Returns:
Response text
"""
logger.info(f"π€ User: {user_text}")
eel_log(f"π€ User: {user_text}")
try:
# Try to match to MCP tool
match = intent_matcher.match(user_text)
if match:
intent_name, intent_data = match
logger.info(f"π― Matched intent: {intent_name}")
eel_log(f"π― Using MCP tool: {intent_name}")
# Extract parameters
params = intent_matcher.extract_params(user_text, intent_data)
server_name, tool_name = intent_matcher.get_tool_info(intent_data)
# Special handling for play_movie - convert partial name to full filename
if tool_name == "play_movie" and "filename" in params:
filename = params["filename"]
# If filename contains words like "about", "with", this is a description, use smart selection
if any(word in filename.lower() for word in ["about", "with", "featuring", "starring"]):
logger.info(f"Filename '{filename}' is a description, using smart movie selection")
eel_log(f"π€ Analyzing your request...")
# Get list of available movies
future = asyncio.run_coroutine_threadsafe(
mcp_manager.call_tool("media-server", "list_movies", {}),
mcp_event_loop
)
movies_result = future.result(timeout=30)
# Extract movie filenames from result
import re
movie_list = re.findall(r'\d+\.\s+([^\n]+\.mp4)', movies_result)
if movie_list:
logger.info("="*80)
logger.info(f"π¬ SMART MOVIE SELECTION")
logger.info(f" User query: {user_text}")
logger.info(f" Available movies: {movie_list}")
logger.info("="*80)
# Create simple selection prompt
movie_titles = ', '.join([f'"{m}"' for m in movie_list])
selection_prompt = f"""Of the movies {movie_titles}, which one best matches: {user_text}
Respond with only the filename from the list above, nothing else."""
logger.info(f"π SELECTION PROMPT:")
logger.info("-"*80)
logger.info(selection_prompt)
logger.info("-"*80)
# Ask LLM to select
model = config.OLLAMA_AGENT_MODEL if hasattr(config, 'OLLAMA_AGENT_MODEL') else 'qwen2.5:7b'
selection_response = ollama_client.chat(
model=model,
messages=[{"role": "user", "content": selection_prompt}]
)
selected_movie = selection_response['message']['content'].strip()
# Clean up response (remove quotes, extra text)
for movie in movie_list:
if movie.lower() in selected_movie.lower():
selected_movie = movie
break
logger.info(f"π¬ LLM SELECTED: {selected_movie}")
logger.info(f" Model used: {model}")
logger.info(f" Full LLM response: {selection_response['message']['content']}")
logger.info("="*80)
params["filename"] = selected_movie
eel_log(f"π¬ Selected: {selected_movie}")
else:
logger.warning("Could not extract movie list, falling back to agent")
agent_result = await use_llm_agent(user_text)
return agent_result
else:
params["filename"] = await resolve_movie_filename(filename)
logger.info(f"Resolved movie filename: {params['filename']}")
# Execute MCP tool - must run on MCP event loop since MCP sessions were created there
logger.info("="*80)
logger.info(f"π§ MCP CALL")
logger.info(f" Server: {server_name}")
logger.info(f" Tool: {tool_name}")
logger.info(f" Parameters: {params}")
logger.info(f" Call point: hal_voice_assistant.py:process_command")
logger.info("="*80)
# Check if we're already in the MCP event loop
try:
current_loop = asyncio.get_running_loop()
if current_loop == mcp_event_loop:
# Already in MCP loop, can call directly
result = await mcp_manager.call_tool(server_name, tool_name, params)
else:
# Different loop, use run_coroutine_threadsafe
future = asyncio.run_coroutine_threadsafe(
mcp_manager.call_tool(server_name, tool_name, params),
mcp_event_loop
)
result = future.result(timeout=30) # 30 second timeout
except RuntimeError:
# No running loop, use run_coroutine_threadsafe
future = asyncio.run_coroutine_threadsafe(
mcp_manager.call_tool(server_name, tool_name, params),
mcp_event_loop
)
result = future.result(timeout=30) # 30 second timeout
logger.info("="*80)
logger.info(f"β
MCP RESULT: {result[:500] if len(result) > 500 else result}")
logger.info("="*80)
# Check if MCP call failed or returned error
if result and ("error" in result.lower() or "not found" in result.lower() or "failed" in result.lower()):
logger.warning(f"MCP tool returned error, trying LLM agent...")
eel_log(f"β οΈ Tool failed, using LLM agent...")
# Use LLM agent to interpret and retry
agent_result = await use_llm_agent(user_text)
return agent_result
# If movie was successfully started, enter movie playback mode
if tool_name == "play_movie" and "error" not in result.lower() and "not found" not in result.lower():
movie_title = params.get("filename", "Unknown Movie")
# Remove extension from title
if '.' in movie_title:
movie_title = movie_title.rsplit('.', 1)[0]
# Start movie playback mode (default 2 hour duration)
await start_movie_playback(movie_title, duration_minutes=120)
return result
else:
# No tool match - use LLM agent
logger.info(f"π No tool match, using LLM agent...")
eel_log("π Using LLM agent...")
agent_result = await use_llm_agent(user_text)
return agent_result
except Exception as e:
logger.error(f"Command processing error: {e}", exc_info=True)
return f"Sorry, I encountered an error: {str(e)}"
# Navigation Stack Functions
def navigate_to(page_name):
"""Navigate to a new page, pushing current page to stack"""
global app_state
# Push current page to stack if not already there
if app_state['current_page'] != page_name:
app_state['navigation_stack'].append(app_state['current_page'])
app_state['current_page'] = page_name
logger.info(f"π Navigated to: {page_name}, stack: {app_state['navigation_stack']}")
eel_update_page(page_name)
def navigate_back():
"""Navigate back to previous page"""
global app_state
if app_state['navigation_stack']:
previous_page = app_state['navigation_stack'].pop()
app_state['current_page'] = previous_page
logger.info(f"π Navigated back to: {previous_page}, stack: {app_state['navigation_stack']}")
eel_update_page(previous_page)
else:
# At home, refresh instead
logger.info(f"π Already at home, refreshing page")
eel_refresh_page()
# Movie State Management Functions
async def start_movie_playback(movie_title, duration_minutes=120):
"""
Start movie playback mode
- Save current listen/speak state
- Disable both
- Set timer to restore state after movie ends
"""
global app_state
logger.info(f"π¬ Starting movie playback: {movie_title} ({duration_minutes} min)")
# Save current state
app_state['movie_playing']['saved_listening'] = app_state['listening']
app_state['movie_playing']['saved_speaking'] = app_state['speaking_enabled']
# Disable listening and speaking during movie
if app_state['listening']:
app_state['listening'] = False
logger.info("π Paused listening during movie")
app_state['speaking_enabled'] = False
logger.info("π Disabled speaking during movie")
# Set movie state
app_state['movie_playing']['active'] = True
app_state['movie_playing']['title'] = movie_title
app_state['movie_playing']['duration'] = duration_minutes
# Navigate to movie playing page
navigate_to('movie_playing')
# Start timer to restore state after movie
import threading
def restore_after_movie():
asyncio.run(end_movie_playback())
timer = threading.Timer(duration_minutes * 60, restore_after_movie)
timer.daemon = True
timer.start()
app_state['movie_playing']['timer'] = timer
logger.info(f"β²οΈ Set timer for {duration_minutes} minutes")
async def end_movie_playback():
"""
End movie playback mode
- Restore previous listen/speak state
- Return to home
"""
global app_state
if not app_state['movie_playing']['active']:
return
logger.info("π¬ Ending movie playback")
# Cancel timer if exists
if app_state['movie_playing']['timer']:
app_state['movie_playing']['timer'].cancel()
# Restore previous state
app_state['listening'] = app_state['movie_playing']['saved_listening']
app_state['speaking_enabled'] = app_state['movie_playing']['saved_speaking']
logger.info(f"π Restored listening={app_state['listening']}, speaking={app_state['speaking_enabled']}")
# Clear movie state
app_state['movie_playing']['active'] = False
app_state['movie_playing']['title'] = ''
app_state['movie_playing']['duration'] = 0
app_state['movie_playing']['timer'] = None
# Return to home
app_state['navigation_stack'] = []
app_state['current_page'] = 'home'
eel_update_page('home')
@eel.expose
def load_ui_config():
"""Load UI configuration from JSON file"""
config_file = Path(__file__).parent / 'ui-config.json'
try:
with open(config_file, 'r') as f:
ui_config = json.load(f)
logger.info(f"β
Loaded UI config: {len(ui_config.get('screens', {}))} screens")
return ui_config
except Exception as e:
logger.error(f"β Error loading UI config: {e}")
return {
"version": "1.0",
"initial_screen": "home",
"screens": {
"home": {
"title": "HAL Voice Assistant",
"components": [
{
"type": "text",
"content": "Voice assistant ready. Say the wake word to begin.",
"style": {"fontSize": "1.5rem", "textAlign": "center", "marginTop": "50px"}
}
]
}
}
}
@eel.expose
def call_mcp(server, tool, params):
"""Call MCP tool through the manager"""
global mcp_manager, mcp_event_loop
logger.info(f"π§ MCP Call: {server}.{tool} with params: {params}")
try:
if not mcp_manager or not mcp_event_loop:
return "Error: MCP not initialized"
future = asyncio.run_coroutine_threadsafe(
mcp_manager.call_tool(server, tool, params),
mcp_event_loop
)
result = future.result(timeout=30)
logger.info(f"β
MCP Result: {result[:100]}...")
return result
except Exception as e:
error_msg = f"MCP Error: {e}"
logger.error(f"β {error_msg}")
return error_msg
# Eel exposed functions
@eel.expose
def get_status():
"""Get current system status"""
return app_state
def run_voice_loop_in_thread():
"""Run voice loop in a separate thread with its own asyncio event loop"""
global voice_loop_event_loop
# Create new event loop for this thread
voice_loop_event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(voice_loop_event_loop)
logger.info("Voice loop thread started")
try:
# Run the voice loop
voice_loop_event_loop.run_until_complete(voice_loop())
except Exception as e:
logger.error(f"Voice loop thread error: {e}", exc_info=True)
finally:
voice_loop_event_loop.close()
logger.info("Voice loop thread stopped")
@eel.expose
def toggle_listening():
"""Toggle listening on/off"""
global voice_loop_thread
app_state['listening'] = not app_state['listening']
logger.info(f"Toggle listening: {app_state['listening']}")
if app_state['listening']:
# Start voice loop in background thread
logger.info("Starting voice loop thread...")
voice_loop_thread = threading.Thread(target=run_voice_loop_in_thread, daemon=True)
voice_loop_thread.start()
logger.info("Voice loop thread started")
return True
else:
logger.info("Stopping voice loop...")
# The loop will stop when app_state['listening'] becomes False
return False
@eel.expose
def update_wake_word(new_wake_word):
"""Update wake word"""
try:
app_state['wake_word'] = new_wake_word
if voice_pipeline:
voice_pipeline.change_wake_word(new_wake_word)
eel_log(f"β
Wake word changed to: {new_wake_word}")
return True
except Exception as e:
eel_log(f"β Failed to change wake word: {e}")
return False
@eel.expose
def update_language(language):
"""Update transcription language"""
try:
app_state['language'] = language
if voice_pipeline:
voice_pipeline.change_language(language)
eel_log(f"β
Language changed to: {language}")
return True
except Exception as e:
eel_log(f"β Failed to change language: {e}")
return False
@eel.expose
def toggle_speaking():
"""Toggle speaking on/off"""
global app_state
app_state['speaking_enabled'] = not app_state['speaking_enabled']
logger.info(f"π Speaking toggled: {app_state['speaking_enabled']}")
return app_state['speaking_enabled']
@eel.expose
def go_back():
"""Navigate back"""
navigate_back()
return True
@eel.expose
def pause_movie():
"""Pause the currently playing movie"""
try:
logger.info("βΈοΈ Pausing movie...")
# Call MCP tool to pause
future = asyncio.run_coroutine_threadsafe(
mcp_manager.call_tool("media-server", "pause_movie", {}),
mcp_event_loop