-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedical_assistant.py
More file actions
2919 lines (2610 loc) · 111 KB
/
Copy pathmedical_assistant.py
File metadata and controls
2919 lines (2610 loc) · 111 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 python
# -*- coding: utf-8 -*-
print("Starting medical_assistant.py...")
# Suppress warnings - these NumPy warnings on Windows are harmless
import os
import sys
import warnings
from datetime import datetime, timezone
import hashlib
print("Imported os, sys, warnings")
# Set environment variable to suppress warnings
os.environ['PYTHONWARNINGS'] = 'ignore'
# Suppress all warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
print("Loading dependencies...")
try:
import time
import asyncio
import threading
import json
import base64
import queue
import websockets
import re
import ast
import webbrowser
import subprocess
import importlib.util
import pathlib
import urllib.request
print(" [OK] time, asyncio, threading, json, queue, websockets, re, ast, webbrowser")
except ImportError as e:
print(f" [FAIL] websockets: {e}")
print(" Install with: pip install websockets")
sys.exit(1)
except Exception as e:
print(f" [FAIL] Standard libs: {e}")
sys.exit(1)
try:
from langdetect import detect, LangDetectException
print(" [OK] langdetect")
except Exception as e:
print(f" [FAIL] langdetect: {e}")
print(" Install with: pip install langdetect")
sys.exit(1)
print(" Attempting to import qdrant_client...")
sys.stdout.flush() # Force output
try:
from qdrant_client import QdrantClient
print(" [OK] qdrant_client")
sys.stdout.flush()
except ImportError as e:
print(f" [FAIL] qdrant_client ImportError: {e}")
print(" Install with: pip install qdrant-client")
import traceback
traceback.print_exc()
sys.exit(1)
except Exception as e:
print(f" [FAIL] qdrant_client Exception: {type(e).__name__}: {e}")
print(" This might be a dependency issue.")
import traceback
print("\nFull traceback:")
traceback.print_exc()
sys.exit(1)
except BaseException as e:
print(f" [FAIL] qdrant_client BaseException: {type(e).__name__}: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
try:
from sentence_transformers import SentenceTransformer
print(" [OK] sentence_transformers")
except Exception as e:
print(f" [WARN] sentence_transformers unavailable: {e}")
print(" RAG retrieval will be disabled; core voice/orchestrator still works.")
print(" To re-enable retrieval later: pip install tf-keras sentence-transformers")
SentenceTransformer = None
try:
import google.generativeai as genai
from google.api_core import exceptions as google_exceptions
print(" [OK] google-generativeai")
except Exception as e:
print(f" [FAIL] google-generativeai: {e}")
print(" Install with: pip install google-generativeai")
sys.exit(1)
try:
from dotenv import load_dotenv
print(" [OK] dotenv")
except Exception as e:
print(f" [FAIL] dotenv: {e}")
print(" Install with: pip install python-dotenv")
sys.exit(1)
try:
from groq import Groq
print(" [OK] groq")
except ImportError as e:
print(f" [FAIL] groq: {e}")
print(" Install with: pip install groq")
sys.exit(1)
try:
import speech_recognition as sr
import io
print(" [OK] speech_recognition")
except ImportError as e:
print(f" [FAIL] speech_recognition: {e}")
print(" Install with: pip install SpeechRecognition pyaudio")
# Don't exit, just disable voice
sr = None
try:
from elevenlabs.client import ElevenLabs
from elevenlabs.play import play
print(" [OK] elevenlabs")
except ImportError as e:
print(f" [FAIL] elevenlabs: {e}")
print(" Install with: pip install elevenlabs")
print(f" [FAIL] elevenlabs: {e}")
print(" Install with: pip install elevenlabs")
ElevenLabs = None
try:
import pyaudio
print(" [OK] pyaudio")
except ImportError as e:
print(f" [FAIL] pyaudio: {e}")
print(" Install with: pip install pyaudio")
pyaudio = None
try:
import pygame
print(" [OK] pygame")
except ImportError as e:
print(f" [FAIL] pygame: {e}")
print(" Install with: pip install pygame")
pygame = None
try:
from twilio.rest import Client
print(" [OK] twilio")
except ImportError as e:
print(f" [FAIL] twilio: {e}")
# print(" Install with: pip install twilio")
Client = None
try:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import uvicorn
print(" [OK] fastapi/uvicorn")
except ImportError as e:
print(f" [WARN] fastapi/uvicorn not installed: {e}")
FastAPI = None
CORSMiddleware = None
BaseModel = None
Field = None
uvicorn = None
from intersense_orchestrator import evaluate_simulation_state
try:
from Elysa.wakeword_service import (
pause_wakeword_mic,
resume_wakeword_mic,
schedule_wakeword_resume_after_voice_session,
start_elysa_wakeword_listener,
)
except ImportError:
def pause_wakeword_mic():
pass
def resume_wakeword_mic():
pass
def schedule_wakeword_resume_after_voice_session():
pass
def start_elysa_wakeword_listener(*args, **kwargs):
return False
# ----------------------------
# Agent Actions & Tools (Inlined)
# ----------------------------
def play_alert_sound(**kwargs):
"""Play a sound effect using Pygame."""
# Flexible argument handling
level = kwargs.get("level") or kwargs.get("alert_type") or kwargs.get("type") or "high"
print(f"🔊 [ACTION] Playing {level} alert sound")
# Check pygame mixer
if pygame:
if not pygame.mixer.get_init():
try:
pygame.mixer.init()
print(" [Init] Pygame Mixer Initialized for Action")
except Exception as e:
print(f"⚠️ Mixer Init Failed: {e}")
return {"status": "failed", "error": "Mixer init failed"}
# Try to find a sound file
sound_path = os.path.join("frontend", "assets", "alert.mp3")
if os.path.exists(sound_path):
try:
# Use Sound object for SFX so it doesn't conflict with music (TTS)
effect = pygame.mixer.Sound(sound_path)
effect.set_volume(0.5) # Sentient volume
effect.play()
except Exception as e:
print(f"⚠️ Sound Error: {e}")
else:
print(f"⚠️ Sound file missing: {sound_path}")
# Fallback beep
print("\a") # System bell
else:
print("⚠️ Pygame mixer not initialized")
return {"status": "played", "level": level}
def send_whatsapp_alert(message_text="EMERGENCY: The user needs help!", **kwargs):
"""Send a WhatsApp alert to the family."""
print(f"📱 [ACTION] Sending WhatsApp alert: {message_text}")
if not Client:
print("⚠️ Twilio library not installed.")
return {"status": "failed", "error": "Twilio not installed"}
account_sid = os.getenv("TWILIO_ACCOUNT_SID")
auth_token = os.getenv("TWILIO_AUTH_TOKEN")
from_number = os.getenv("TWILIO_FROM_NUMBER")
to_number = os.getenv("TWILIO_TO_NUMBER")
if not all([account_sid, auth_token, from_number, to_number]):
print("⚠️ Twilio credentials missing in .env")
return {"status": "failed", "error": "Twilio credentials missing"}
try:
client = Client(account_sid, auth_token)
# Use simple free-form text instead of content templates for flexibility
message = client.messages.create(
from_=from_number,
body=message_text,
to=to_number
)
print(f"✅ WhatsApp Message sent! SID: {message.sid}")
return {"status": "sent", "sid": message.sid}
except Exception as e:
print(f"⚠️ Twilio Error: {e}")
return {"status": "failed", "error": str(e)}
# Register Actions
ACTIONS = {
"send_whatsapp_alert": send_whatsapp_alert
}
# Tool Definitions for LLM
TOOLS = [
{
"name": "send_whatsapp_alert",
"description": "Send a WhatsApp alert to family members. You MUST provide a 'message_text' describing the situation (e.g., 'User is feeling faint').",
"parameters": {
"type": "object",
"properties": {
"message_text": {
"type": "string",
"description": "The specific message to send to the family."
}
},
"required": ["message_text"]
}
},
]
def execute_action(action_name, args):
"""Execute a registered action."""
if action_name in ACTIONS:
try:
return ACTIONS[action_name](**args)
except Exception as e:
return {"status": "failed", "error": str(e)}
return {"status": "failed", "error": "Unknown action"}
def handle_agent_response(response):
"""Normalize agent response."""
if isinstance(response, dict) and response.get("type") == "action":
return {"type": "action", "name": response.get("name"), "args": response.get("args", {})}
return {"type": "speech", "text": response.get("text", str(response))}
def parse_agent_json(raw_reply):
"""Parse raw LLM output as action/speech JSON."""
parsed_response = None
def try_parse(text):
try:
return json.loads(text)
except Exception:
pass
text_py = text.replace("false", "False").replace("true", "True").replace("null", "None")
try:
val = ast.literal_eval(text_py)
if isinstance(val, dict):
return val
except Exception:
pass
return None
parsed_response = try_parse(raw_reply)
if not parsed_response:
match = re.search(r"\{.*\}", raw_reply, re.DOTALL)
if match:
parsed_response = try_parse(match.group(0))
if not parsed_response:
return {"type": "speech", "text": raw_reply}
return parsed_response
print("Loading environment variables...")
load_dotenv()
print("[OK] Environment loaded")
# ----------------------------
# Setup
# ----------------------------
# Qdrant configuration - can use local or cloud
QDRANT_HOST = os.getenv("QDRANT_HOST", "http://localhost:6333") # Local default
QDRANT_API_KEY = os.getenv("QDRANT_API_KEY", None) # Optional for local
COLLECTION_NAME = "hannibal_kb"
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
ELEVENLABS_VOICE_ID = os.getenv("ELEVENLABS_VOICE_ID", "Xb7hH8MSUJpSbSDYk0k2")
# ----------------------------
# WebSocket Server & Input Handling
# ----------------------------
CONNECTED_CLIENTS = set()
WS_PORT = 8765
INPUT_QUEUE = queue.Queue()
ORCHESTRATOR_QUEUE = queue.Queue()
WS_LOOP = None
# Last UI-selected voice language (WebSocket); used for "Elysa" wake → \voice
_VOICE_CLIENT_LANG = ["en"]
_VOICE_CLIENT_LANG_LOCK = threading.Lock()
def get_client_voice_language():
with _VOICE_CLIENT_LANG_LOCK:
return _VOICE_CLIENT_LANG[0]
def broadcast_state(state, audio_level=0.0):
"""Send state update to all connected clients in a thread-safe way."""
if not CONNECTED_CLIENTS or WS_LOOP is None:
return
message = json.dumps({
"state": state,
"audioData": audio_level
})
async def _send():
websockets.broadcast(CONNECTED_CLIENTS, message)
try:
# Schedule the broadcast on the WebSocket thread's event loop
asyncio.run_coroutine_threadsafe(_send(), WS_LOOP)
except Exception as e:
print(f"⚠️ Broadcast Error: {e}")
async def ws_handler(websocket):
print(f" [WS] Client connected")
CONNECTED_CLIENTS.add(websocket)
try:
async for message in websocket:
try:
data = json.loads(message)
msg_type = data.get("type")
lang = data.get("language")
if isinstance(lang, str) and lang.strip():
with _VOICE_CLIENT_LANG_LOCK:
_VOICE_CLIENT_LANG[0] = lang.strip().lower()[:16]
if msg_type == "language":
continue
if msg_type == "command":
cmd = data.get("content")
language = data.get("language", "en") # Default to english
print(f" [WS] Remote command received: {cmd} (lang: {language})")
INPUT_QUEUE.put({"text": cmd, "language": language})
except json.JSONDecodeError:
pass
except Exception as e:
print(f" [WS] Error parsing: {e}")
except Exception as e:
print(f" [WS] Connection closed: {e}")
finally:
CONNECTED_CLIENTS.discard(websocket)
print(f" [WS] Client disconnected")
async def run_ws_server():
print(f" [WS] Starting WebSocket server on port {WS_PORT}...")
async with websockets.serve(ws_handler, "127.0.0.1", WS_PORT):
await asyncio.Future() # run forever
def start_websocket_server():
"""Start WS server in a daemon thread."""
def thread_run():
global WS_LOOP
# Create a new event loop for this thread
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
WS_LOOP = loop
loop.run_until_complete(run_ws_server())
t = threading.Thread(target=thread_run, daemon=True)
t.start()
time.sleep(1) # Give it a sec to start
if not GEMINI_API_KEY:
print("[ERROR] GEMINI_API_KEY not found!")
print(" Please set it in .env file: GEMINI_API_KEY=your_key_here")
# sys.exit(1) # Don't exit yet to allow import, but will fail on query
# Initialize Qdrant client with error handling
try:
print("[INFO] Connecting to Qdrant...")
if QDRANT_API_KEY:
client = QdrantClient(url=QDRANT_HOST, api_key=QDRANT_API_KEY)
else:
client = QdrantClient(url=QDRANT_HOST)
# Test connection
collections = client.get_collections()
print(f"[OK] Connected to Qdrant at {QDRANT_HOST}\n")
except Exception as e:
print(f"[ERROR] Cannot connect to Qdrant at {QDRANT_HOST}")
print(f" Error: {e}")
print("\n[INFO] Solutions:")
print(" 1. Check internet connection")
print(" 2. Verify QDRANT_HOST in .env includes port (e.g. :6333)")
print(" 3. Verify API key")
sys.exit(1)
# ----------------------------
# Embedding Model (Local, Free)
# ----------------------------
model = None
if SentenceTransformer is not None:
try:
print("[INFO] Loading embedding model...")
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
print("[OK] Embedding model loaded.\n")
except Exception as e:
print(f"[WARN] Embedding model unavailable: {e}")
print(" Retrieval disabled; assistant will continue without RAG context.\n")
model = None
else:
print("[WARN] Embedding model skipped (sentence_transformers unavailable).")
print(" Retrieval disabled; assistant will continue without RAG context.\n")
def get_embedding(text):
"""Generate embedding using local SentenceTransformer model."""
if model is None:
return None
return model.encode(text).tolist()
# ----------------------------
# LLM Setup (Gemini)
# ----------------------------
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
def query_gemini(messages, voice_wav_bytes=None, voice_language=None):
"""Query Gemini API."""
if not GEMINI_API_KEY:
return "Error: GEMINI_API_KEY not configured."
# Extract system message
system_msg = next((m["content"] for m in messages if m["role"] == "system"), None)
# Filter for chat messages
chat_messages = [m for m in messages if m["role"] != "system"]
if not chat_messages:
return "Error: No user message found."
# Configure model with system instruction
# Using gemini-2.5-flash for speed/cost efficiency
model = genai.GenerativeModel('gemini-2.5-flash', system_instruction=system_msg)
# Split into history and last message
last_msg = chat_messages[-1]
history_msgs = chat_messages[:-1]
# Build Gemini history format
gemini_history = []
for m in history_msgs:
role = "user" if m["role"] == "user" else "model"
gemini_history.append({"role": role, "parts": [m["content"]]})
try:
chat = model.start_chat(history=gemini_history)
if voice_wav_bytes:
# Give Gemini the transcript + original WAV so it can correct STT mistakes.
language_hint = voice_language or "auto"
text_part = (
f"Voice language hint: {language_hint}\n"
"User transcript (may contain STT mistakes):\n"
f"{last_msg['content']}\n\n"
"Please use the attached WAV audio as primary evidence when unclear."
)
audio_part = {
"inline_data": {
"mime_type": "audio/wav",
"data": base64.b64encode(voice_wav_bytes).decode("utf-8"),
}
}
response = chat.send_message([text_part, audio_part])
else:
response = chat.send_message(last_msg["content"])
text = response.text.strip()
# Clean up markdown code blocks if present
if text.startswith("```json"):
text = text[7:]
if text.startswith("```python"):
text = text[9:]
if text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
return text.strip()
except google_exceptions.InvalidArgument as e:
return f"Gemini Error (Invalid Argument): {e}"
except Exception as e:
return f"Gemini Error: {e}"
# ----------------------------
# Retriever
# ----------------------------
def retrieve_docs(user_query, k=3):
"""Retrieve relevant documents from Qdrant vector database."""
query_vec = get_embedding(user_query)
if query_vec is None:
return []
try:
# Check if collection exists
collections = [c.name for c in client.get_collections().collections]
if COLLECTION_NAME not in collections:
print(f"⚠️ Collection '{COLLECTION_NAME}' not found!")
print(f" Available collections: {collections}")
print(f" Please run: python farm_index_data.py")
return []
results = client.query_points(
collection_name=COLLECTION_NAME,
query=query_vec,
limit=k
).points
return [r.payload["content"] for r in results]
except Exception as e:
print(f"⚠️ Error retrieving documents: {e}")
return []
return []
# ----------------------------
# Voice Transcription (Groq)
# ----------------------------
def listen_and_transcribe(return_audio=False):
"""Listen to microphone and transcribe using Groq Whisper."""
if not sr:
print("❌ SpeechRecognition not installed.")
return None
if not GROQ_API_KEY:
print("❌ GROQ_API_KEY not found in .env.")
return None
r = sr.Recognizer()
# Balance speed + sentence completeness (avoid mid-sentence cutoffs)
r.energy_threshold = 300 # Default 300, can adjust dynamic
r.pause_threshold = 1.0 # Allow longer short pauses while speaking
r.non_speaking_duration = 0.7 # Keep stream open a bit longer before endpointing
r.dynamic_energy_threshold = True
try:
groq_client = Groq(api_key=GROQ_API_KEY)
with sr.Microphone() as source:
broadcast_state("listening")
print("\n🎤 Listening... (Speak now!)")
# Slightly longer calibration improves stability in noisy rooms
r.adjust_for_ambient_noise(source, duration=0.3)
# Listen (stops when silence is detected)
try:
# Reduced phrase_time_limit to avoid broken open mics
audio_data = r.listen(source, timeout=10, phrase_time_limit=15)
# Immediately switch to thinking state to show user we heard them
broadcast_state("thinking")
except sr.WaitTimeoutError:
broadcast_state("neutral") # Reset if they didn't speak
return None
print("⏳ Transcribing...")
# Convert to WAV in memory
wav_data = audio_data.get_wav_data()
audio_stream = io.BytesIO(wav_data)
audio_stream.name = "audio.wav" # Groq needs a filename
transcription = groq_client.audio.transcriptions.create(
file=("audio.wav", audio_stream),
model="whisper-large-v3",
temperature=0,
response_format="verbose_json",
)
transcript_text = transcription.text.strip()
if return_audio:
return transcript_text, wav_data
return transcript_text
except sr.RequestError as e:
print(f"❌ Microphone error: {e}")
broadcast_state("neutral")
return None
except Exception as e:
print(f"❌ Transcription error: {e}")
broadcast_state("neutral")
return None
# ----------------------------
# Text-to-Speech (ElevenLabs)
# ----------------------------
def speak_response(text):
"""Convert text to speech and play it using Pygame (MP3) in chunks."""
if not ElevenLabs or not ELEVENLABS_API_KEY:
return
if not pygame:
print("⚠️ Pygame not available for playback.")
return
# Initialize Pygame Mixer if needed
if not pygame.mixer.get_init():
# Lower buffer size for lower latency (default is 4096)
pygame.mixer.init(buffer=512)
import re
# Split text into sentences to play immediately (Time-to-first-byte reduction)
# This regex splits by . ! ? but keeps the punctuation
sentences = re.split(r'(?<=[.!?])\s+', text)
sentences = [s.strip() for s in sentences if s.strip()]
if not sentences:
return
client = ElevenLabs(api_key=ELEVENLABS_API_KEY)
try:
for sentence in sentences:
# Skip very short fragments that might just be noise
if len(sentence) < 2:
continue
# Generate audio for this sentence
# We fetch while the previous one might still be playing (overlapping IO/Playback)
try:
audio_generator = client.text_to_speech.convert(
text=sentence,
voice_id=ELEVENLABS_VOICE_ID,
model_id="eleven_multilingual_v2",
output_format="mp3_44100_128",
)
audio_data = b"".join([chunk for chunk in audio_generator if chunk])
audio_io = io.BytesIO(audio_data)
# Wait for previous playback to finish before starting new one
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10) # Check every 10ms for faster response
# Play current content
broadcast_state("speaking", audio_level=0.8) # Simulate level
pygame.mixer.music.load(audio_io)
pygame.mixer.music.play()
except Exception as e:
print(f"⚠️ TTS Error on sentence '{sentence[:10]}...': {e}")
continue
# Wait for the final sentence to finish
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
except Exception as e:
print(f"⚠️ TTS General Error: {e}")
finally:
broadcast_state("neutral") # Always reset to neutral
# Cached wake greeting (generate once: python Elysa/download_greeting_audio.py)
ELYSA_WAKE_GREETING_MP3 = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "Elysa", "elysa_greeting.mp3"
)
WHATSAPP_ALERT_SENT_MP3 = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "Elysa", "whatsapp_alert_sent.mp3"
)
CRITICAL_FAINTING_ESCALATION_MP3 = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "Elysa", "critical_fainting_escalation.mp3"
)
_ELYSA_DIR = os.path.dirname(ELYSA_WAKE_GREETING_MP3)
# Single English cached thanks reply (any-language thanks from user → English audio).
THANKS_REPLY_MP3 = os.path.join(_ELYSA_DIR, "thanks_reply_en.mp3")
THANKS_HISTORY_TEXT = "You're welcome. I'm here if you need anything else."
_GRATITUDE_BAD_SUBSTRINGS = (
"dizzy", "faint", "pain", "hurt", "nausea", "chest", "breath", "bleed",
"emergency", "help me", "not ok", "not okay", "feel bad", "symptom",
"دوار", "وجع", "غمى", "إغماء",
)
_GRATITUDE_TOKEN_REQUIRED = frozenset(
{
"thank", "thanks", "thx", "ty", "merci", "gracias", "gracia",
"shukran", "choukran", "شكرا", "شكرًا", "thankyou",
}
)
_GRATITUDE_ALLOWED_TOKENS = frozenset(
{
"thank", "you", "thanks", "thx", "ty", "thankyou", "so", "very", "much",
"a", "lot", "the", "for", "your", "my", "all", "and", "to", "too",
"merci", "beaucoup", "bien", "gracias", "gracia", "muchas",
"shukran", "choukran", "ya", "yes", "ok", "okay", "buddy", "mate",
"شكرا", "شكرًا", "شكراً", "جزيلا", "يعيشك", "بارك", "الله", "فيك",
}
)
def _normalize_thanks_text(text):
t = text.strip().lower()
t = re.sub(r"[\s,.!?;:،؟]+", " ", t)
return t.strip()
def is_gratitude_only_message(text):
"""
True if the user message is a short thanks-only utterance (no medical distress cues).
Skips LLM; plays cached ElevenLabs-generated MP3 instead.
"""
if not text or not str(text).strip():
return False
raw = str(text).strip()
if len(raw) > 140:
return False
low = raw.lower()
if any(b in low for b in _GRATITUDE_BAD_SUBSTRINGS):
return False
# Arabic / mixed thanks without strict Latin tokenization
if any(x in raw for x in ("شكرا", "شكرًا", "شكراً", "يعيشك", "بارك الله")):
if "لكن" in low or " but " in low or "however" in low:
return False
if len(raw) <= 90:
return True
norm = _normalize_thanks_text(raw)
if not norm:
return False
tokens = re.findall(r"[\w']+|[^\x00-\x7F]+", norm)
if not tokens:
return False
flat = " ".join(tokens)
if not any(req in flat for req in _GRATITUDE_TOKEN_REQUIRED):
return False
for tok in tokens:
t0 = tok.lower().strip("'")
if t0 in _GRATITUDE_ALLOWED_TOKENS:
continue
if re.fullmatch(r"[\W_]+", tok):
continue
return False
return True
def play_thanks_reply_cached():
"""Play pre-generated English thank-you reply MP3 — no LLM, no live ElevenLabs API."""
path = THANKS_REPLY_MP3
if not os.path.isfile(path):
print(
f"⚠️ Cached thanks audio missing: {path}\n"
" Run: python Elysa/download_greeting_audio.py"
)
return
if not pygame:
return
if not pygame.mixer.get_init():
try:
pygame.mixer.init(buffer=512)
except Exception as e:
print(f"⚠️ Thanks reply: mixer init failed: {e}")
return
try:
broadcast_state("speaking", audio_level=0.8)
pygame.mixer.music.load(path)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
except Exception as e:
print(f"⚠️ Thanks reply playback failed: {e}")
finally:
broadcast_state("neutral")
def play_elysa_wake_greeting():
"""Play local MP3 greeting after wake word — no ElevenLabs round-trip."""
if not os.path.isfile(ELYSA_WAKE_GREETING_MP3):
print(
f"⚠️ Elysa greeting audio missing: {ELYSA_WAKE_GREETING_MP3}\n"
" Run: python Elysa/download_greeting_audio.py"
)
return
if not pygame:
return
if not pygame.mixer.get_init():
try:
pygame.mixer.init(buffer=512)
except Exception as e:
print(f"⚠️ Elysa greeting: mixer init failed: {e}")
return
try:
broadcast_state("speaking", audio_level=0.8)
pygame.mixer.music.load(ELYSA_WAKE_GREETING_MP3)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
except Exception as e:
print(f"⚠️ Elysa greeting playback failed: {e}")
finally:
broadcast_state("neutral")
def play_critical_fainting_escalation_prompt():
"""Play cached critical-fainting escalation line (no live ElevenLabs call)."""
if not os.path.isfile(CRITICAL_FAINTING_ESCALATION_MP3):
print(
f"⚠️ Cached critical escalation audio missing: {CRITICAL_FAINTING_ESCALATION_MP3}\n"
" Run: python Elysa/download_greeting_audio.py"
)
return
if not pygame:
return
if not pygame.mixer.get_init():
try:
pygame.mixer.init(buffer=512)
except Exception as e:
print(f"⚠️ Critical escalation prompt: mixer init failed: {e}")
return
try:
broadcast_state("speaking", audio_level=0.8)
pygame.mixer.music.load(CRITICAL_FAINTING_ESCALATION_MP3)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
except Exception as e:
print(f"⚠️ Critical escalation prompt playback failed: {e}")
finally:
broadcast_state("neutral")
def play_whatsapp_alert_sent_prompt():
"""Play cached WhatsApp alert confirmation (no ElevenLabs call)."""
if not os.path.isfile(WHATSAPP_ALERT_SENT_MP3):
print(
f"⚠️ Cached WhatsApp confirmation missing: {WHATSAPP_ALERT_SENT_MP3}\n"
" Run: python Elysa/download_greeting_audio.py"
)
return
if not pygame:
return
if not pygame.mixer.get_init():
try:
pygame.mixer.init(buffer=512)
except Exception as e:
print(f"⚠️ WhatsApp confirmation: mixer init failed: {e}")
return
try:
broadcast_state("speaking", audio_level=0.8)
pygame.mixer.music.load(WHATSAPP_ALERT_SENT_MP3)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
except Exception as e:
print(f"⚠️ WhatsApp confirmation playback failed: {e}")
finally:
broadcast_state("neutral")
# Maximum number of conversation exchanges to keep in history
MAX_HISTORY_EXCHANGES = 5
def get_response(
user_message,
history,
language=None,
system_prompt_append=None,
voice_wav_bytes=None,
):
"""Generate response using RAG pipeline."""
broadcast_state("thinking")
if not language:
try:
language = detect(user_message)
except LangDetectException:
language = "en"
# Retrieve relevant context
context_docs = retrieve_docs(user_message)
context_text = "\n".join(context_docs) if context_docs else "No relevant context found."
# Single English-output persona: understand any input language, always reply in English.
persona = (
"You are a Medical Assistant specialized in Sudden Fainting (Syncope). "
"Your role is to calm the user down and provide clear, step-by-step instructions. "
"You are reassuring, direct, and professional. "
"If the user says they feel faint, guide them immediately: sit down, lie down, elevate legs. "
"Use your tools if necessary (escalation/notification). "
"Focus ONLY on the medical emergency."
)
# Build system message with context
tools_json = json.dumps(TOOLS, indent=2)
system_message = f"""{persona}
DETECTED_USER_LANGUAGE_HINT (for understanding only, not for output): {language}
INSTRUCTIONS:
- You are a Medical Assistant.
- The user may speak or write in any language (Arabic, French, Tunisian Darija, English, etc.). Understand their intent fully.
- **OUTPUT LANGUAGE**: Always write the JSON `"text"` field for speech in **English only**. Never reply in Arabic, French, or other languages in `"text"`. Tool string fields (e.g. message_text) should also be in English unless a system rule says otherwise.
- **TOOL-FIRST POLICY (STRICT)**: If any available tool can directly solve or materially improve the user's stated problem, choose a tool action first instead of speech-only advice.
- **PRIORITY**: If the user needs immediate attention, emergency escalation, or external notification, USE THE TOOL immediately.
- Prefer `send_whatsapp_alert` when contacting others can improve safety.
- Do not ask unnecessary follow-up questions before using a suitable tool in urgent scenarios.
- **CALM INSTRUCTIONS**: Guide the user step-by-step.
- `send_whatsapp_alert` = "Notify family/friends."
- Do NOT mention being a General or Stratageist.
- Only use context provided.
- Keep wording simple and clear.
- Admit missing info.
- Reject off-topic questions politely.
- Keep responses <60 words.
- Provide practical, actionable advice.
AVAILABLE TOOLS:
{tools_json}
RESPONSE FORMAT:
You must respond in JSON format.
If a suitable tool exists for the user's stated need, return an action JSON.
If you want to speak, return:
{{ "type": "speech", "text": "Your response here (English only)" }}
If you want to perform an action, return:
{{ "type": "action", "name": "tool_name", "args": {{ "arg1": "value" }} }}
CONVERSATION CONTEXT:
{context_text}"""
if system_prompt_append:
system_message = f"{system_message}\n\n{system_prompt_append}"
# Build messages array with conversation history
messages = [{"role": "system", "content": system_message}]
# Limit history to most recent exchanges
recent_history = history[-MAX_HISTORY_EXCHANGES:] if len(history) > MAX_HISTORY_EXCHANGES else history
# Add conversation history
for user_msg, bot_msg in recent_history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
# Add current user message
messages.append({"role": "user", "content": user_message})