-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1632 lines (1483 loc) · 67.5 KB
/
main.py
File metadata and controls
1632 lines (1483 loc) · 67.5 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
# NEXUS AI Assistant — Created by Ansh Sinha | LinkedIn: linkedin.com/in/sinhaansh | GitHub: github.com/SinhaRepo | © 2026 All Rights Reserved
# --- NUCLEAR SILENCE BLOCK ---
import os
import sys
import warnings
import logging
from ctypes import *
import datetime
import pytz
import threading
import json
import re
import queue
import time
import asyncio
import subprocess
import math
# 1. Kill ALSA & Driver Errors — Nuclear approach
# Suppress libasound error callback
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt): pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
try:
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
except: pass
# 2. Redirect C-level stderr (fd 2) to /dev/null to kill PortAudio ALSA noise
# This stops "Expression 'ret' failed in pa_linux_alsa.c" and "snd_pcm_recover underrun"
# Python's sys.stderr is re-pointed to the original fd so our prints still work
import io as _io
try:
_real_stderr_fd = os.dup(2)
_devnull_fd = os.open(os.devnull, os.O_WRONLY)
os.dup2(_devnull_fd, 2) # C libraries writing to fd 2 now go to /dev/null
sys.stderr = _io.TextIOWrapper(_io.FileIO(os.dup(_real_stderr_fd), 'w'), line_buffering=True)
except Exception:
pass # Non-Linux or permission issue — skip
os.environ["PYTHONWARNINGS"] = "ignore"
def warn(*args, **kwargs): pass
warnings.warn = warn
warnings.simplefilter("ignore")
logging.getLogger("requests").setLevel(logging.CRITICAL)
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
logging.getLogger("duckduckgo_search").setLevel(logging.CRITICAL)
# --- UI MODULE ---
import ui
ui.print_header()
import sounddevice as sd
import numpy as np
from scipy.io.wavfile import write
from groq import Groq
import requests
import pygame
import edge_tts
from duckduckgo_search import DDGS
import gc
import traceback
import atexit
import signal
import urllib.parse
from dotenv import load_dotenv
# Try GPIO (Pi-only)
try:
from gpiozero import Button
GPIO_AVAILABLE = True
except Exception:
GPIO_AVAILABLE = False
# Try Porcupine wake word
try:
import pvporcupine
import struct
PORCUPINE_AVAILABLE = True
except ImportError:
PORCUPINE_AVAILABLE = False
# Try PyAudio (for shared mic with Porcupine)
try:
import pyaudio
PYAUDIO_AVAILABLE = True
except ImportError:
PYAUDIO_AVAILABLE = False
load_dotenv()
DEFAULT_CITY = os.getenv("DEFAULT_CITY", "London")
# ==========================================
# SHARED AUDIO COORDINATION
# ==========================================
# When Porcupine owns the mic, the button loop signals it via these events
# instead of opening a second audio stream (which causes Device Unavailable)
_button_held = threading.Event() # Set while physical button is pressed
_button_released = threading.Event() # Set when button is released
_button_audio_buf = [] # Frames captured during button hold
_button_audio_lock = threading.Lock() # Protects _button_audio_buf
# ==========================================
# CONFIGURATION & KEYS
# ==========================================
NEXUS_TOKEN = os.getenv("NEXUS_TOKEN") or os.getenv("JARVIS_TOKEN")
if not NEXUS_TOKEN:
raise SystemExit("FATAL: NEXUS_TOKEN is not set in your .env file. Set it to any secret passphrase and add the same value to your laptop .env. Refusing to start.")
LAPTOP_IP = os.getenv("LAPTOP_IP", "192.168.1.5")
LAPTOP_PORT = os.getenv("LAPTOP_PORT", "5000")
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY", "")
DEEPGRAM_API_KEY = os.getenv("DEEPGRAM_API_KEY", "")
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "")
NEWS_API_KEY = os.getenv("NEWS_API_KEY", "")
PORCUPINE_ACCESS_KEY = os.getenv("PORCUPINE_ACCESS_KEY", "")
BUTTON_PIN = 23
ELEVEN_VOICE_ID = os.getenv("ELEVENLABS_VOICE_ID", "JBFqnCBsd6RMkjVDRZzb")
ELEVEN_URL = f"https://api.elevenlabs.io/v1/text-to-speech/{ELEVEN_VOICE_ID}/stream"
# Porcupine wake word model path
PORCUPINE_MODEL_PATH = os.getenv("PORCUPINE_MODEL_PATH", "/home/pi/Hey-Nexus_en_raspberry-pi_v4_0_0.ppn")
req_session = requests.Session()
req_session.headers.update({
"User-Agent": "NexusPiClient/3.0",
"X-Nexus-Token": NEXUS_TOKEN
})
# ==========================================
# STATE
# ==========================================
chat_history = []
user_profile = {
"name": None,
"city": DEFAULT_CITY,
"favorite_artists": [],
"last_active": None,
"conversation_count": 0,
"custom_facts": {}
}
reminders_list = []
voice_engine_override = None
model_name = "Loading..."
internet_available = True
memory_queue = []
memory_sync_lock = threading.Lock()
_shutdown_done = False
# ==========================================
# BACKGROUND SYNC THREAD
# ==========================================
def bg_sync_thread():
while True:
time.sleep(30)
with memory_sync_lock:
if memory_queue:
try:
hist_to_save = [m for m in chat_history if m["role"] != "system"][-20:]
payload = {"chat_history": hist_to_save, "user_profile": user_profile}
resp = req_session.post(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/memory", json=payload, timeout=5)
if resp.status_code == 200:
memory_queue.clear()
ui.show_status("Background sync: memory flushed to laptop")
except Exception:
pass
# Check for alerts from laptop
try:
resp = req_session.get(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/alerts", timeout=3)
if resp.status_code == 200:
alerts = resp.json().get("alerts", [])
for alert in alerts:
ui.show_alert(alert.get("type", "ALERT").upper(), alert.get("message", ""))
threading.Thread(target=speak, args=(alert.get("message", ""),), daemon=True).start()
except Exception:
pass
# Check for due reminders
try:
resp = req_session.get(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/reminders/check", timeout=3)
if resp.status_code == 200:
due = resp.json().get("due_reminders", [])
for msg in due:
ui.show_reminder(msg)
threading.Thread(target=speak, args=(f"Reminder: {msg}",), daemon=True).start()
except Exception:
pass
t_sync = threading.Thread(target=bg_sync_thread, daemon=True)
t_sync.start()
# ==========================================
# SHUTDOWN HANDLER
# ==========================================
def force_save_on_exit():
global _shutdown_done
if _shutdown_done:
return
_shutdown_done = True
try:
hist_to_save = [m for m in chat_history if m["role"] != "system"][-20:]
payload = {"chat_history": hist_to_save, "user_profile": user_profile}
req_session.post(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/memory", json=payload, timeout=3)
ui.show_shutdown(success=True)
except Exception:
ui.show_shutdown(success=False)
atexit.register(force_save_on_exit)
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(0))
# ==========================================
# INITIALIZATION & SYSTEM CHECK
# ==========================================
client_groq = None
button = None
q = queue.Queue()
try:
client_groq = Groq(api_key=GROQ_API_KEY)
pygame.mixer.init()
if GPIO_AVAILABLE:
button = Button(BUTTON_PIN, pull_up=True, bounce_time=0.1)
ui.boot_step(1, 6, "Ears Online", "(Groq Whisper)", "ok", [
"> Groq client initialized",
"> pygame.mixer ready",
f"> GPIO Button: {'PIN 23 bound' if button else 'Not available'}",
"> Audio queue allocated",
])
internet_available = True
except Exception as e:
ui.boot_step(1, 6, "Ears Failed", "(Groq Offline)", "fail", [
f"> Init error: {e}",
])
internet_available = False
audio_clock = pygame.time.Clock()
def ping_laptop():
try:
resp = requests.get(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/status", timeout=3)
if resp.status_code == 200:
return resp.json().get("status") == "online"
return False
except Exception:
return False
# Gemini model failover chain — if one hits 429 rate limit, try the next
GEMINI_MODELS = [
"gemini-2.5-flash",
"gemini-2.5-flash-lite",
]
model_name = GEMINI_MODELS[0]
if GOOGLE_API_KEY:
ui.boot_step(2, 6, "Brain Online", f"({model_name})", "ok", [
f"> Primary: {GEMINI_MODELS[0]}",
f"> Failover: {' → '.join(GEMINI_MODELS[1:])} → Groq",
"> Auto-rotation on 429 rate limits",
"> Final fallback: Groq (llama-3.3-70b-versatile)",
])
else:
ui.boot_step(2, 6, "Gemini Unavailable", "(No API key)", "fail", [
"> GOOGLE_API_KEY not set in .env",
"> Using Groq only (llama-3.3-70b-versatile)",
])
# ElevenLabs startup verification
try:
headers = {"xi-api-key": ELEVENLABS_API_KEY}
sub_resp = requests.get("https://api.elevenlabs.io/v1/user/subscription", headers=headers, timeout=5)
if sub_resp.status_code == 200:
sub_data = sub_resp.json()
char_remaining = sub_data.get("character_limit", 0) - sub_data.get("character_count", 0)
if char_remaining > 100:
ui.boot_step(3, 6, "Voice Online", "(ElevenLabs)", "ok", [
f"> ElevenLabs quota: {char_remaining} chars remaining",
"> Fallback chain: Deepgram Aura → Edge-TTS → pyttsx3",
])
else:
voice_engine_override = "deepgram"
ui.boot_step(3, 6, "Voice Degraded", "(Deepgram Aura)", "warn", [
f"> ElevenLabs exhausted ({char_remaining} chars left)",
"> Fallback: Deepgram Aura TTS active",
])
else:
voice_engine_override = "deepgram"
ui.boot_step(3, 6, "Voice Degraded", "(Deepgram Aura)", "warn", [
f"> ElevenLabs API error (HTTP {sub_resp.status_code})",
"> Fallback: Deepgram Aura TTS active",
])
except Exception as e:
voice_engine_override = "deepgram"
ui.boot_step(3, 6, "Voice Degraded", "(Deepgram Aura)", "warn", [
f"> ElevenLabs check failed: {e}",
"> Fallback: Deepgram Aura TTS active",
])
if ping_laptop():
ui.boot_step(4, 6, "Laptop Connected", f"({LAPTOP_IP}:{LAPTOP_PORT})", "ok", [
f"> Target: {LAPTOP_IP}:{LAPTOP_PORT}",
"> HTTP session established",
])
else:
ui.boot_step(4, 6, "Laptop Offline", f"({LAPTOP_IP})", "fail", [
"> Ping failed — laptop offline or wrong IP",
])
# Porcupine wake word check
porcupine_handle = None
if PORCUPINE_AVAILABLE and PORCUPINE_ACCESS_KEY:
try:
porcupine_handle = pvporcupine.create(
access_key=PORCUPINE_ACCESS_KEY,
keyword_paths=[PORCUPINE_MODEL_PATH]
)
ui.boot_step(5, 6, "Wake Word Online", '("Hey Nexus")', "ok", [
"> Picovoice Porcupine v4 loaded",
f"> Model: {os.path.basename(PORCUPINE_MODEL_PATH)}",
f"> Sample rate: {porcupine_handle.sample_rate} Hz",
])
except Exception as e:
ui.boot_step(5, 6, "Wake Word Failed", "(Button-only mode)", "fail", [
f"> Porcupine error: {e}",
])
porcupine_handle = None
else:
reason = "pvporcupine not installed" if not PORCUPINE_AVAILABLE else "No access key"
ui.boot_step(5, 6, "Wake Word Unavailable", f"({reason})", "warn", [
"> Falling back to button + text input",
])
# ==========================================
# MEMORY & PROFILE SYSTEM
# ==========================================
def inject_system_prompt():
global chat_history, user_profile
sys_prompt = f"""You are NEXUS — a highly intelligent, witty, and efficient personal AI assistant created by Ansh Sinha.
You speak naturally like a knowledgeable friend — confident, direct, occasionally humorous.
You ALWAYS respond in English only. Never use any other language under any circumstance even if the user writes in another language — always respond in English.
Use the user name at most once per response — never repeat it multiple times.
Match response depth to question complexity — concise for simple questions, detailed for complex ones.
Never truncate complex answers. When asked for bullet points lists or formatted output provide exactly that format.
For ambiguous sentences acknowledge all possible meanings.
Never start consecutive sentences the same way.
Never use filler words like Certainly or Absolutely or Of course. Be direct and helpful.
When asked who made you or who created you, always say you were created by Ansh Sinha as a personal AI project.
You are a VOICE assistant running on a Raspberry Pi with a microphone and speaker. Users talk to you by voice (wake word or button) or by typing in the terminal. You CAN hear them — their speech is transcribed to text before reaching you.
You have access to: laptop control (open/close apps, run commands), Spotify music, web search, weather, news, note-taking, reminders, system monitoring, and YouTube.
When the user says to play music, you have Spotify integration. For system commands, you can open apps, close apps, check CPU/RAM, and run terminal commands on the user's laptop.
CRITICAL RULES — NEVER VIOLATE:
- ONLY use data explicitly provided in the Context block. NEVER invent, guess, or fabricate facts, news headlines, reminders, times, prices, or any data.
- If the Context does not contain specific information (news, reminders, time, weather), say you don't have that information right now.
- NEVER make up news headlines. If no [NEWS HEADLINES] context is provided, say no headlines are available.
- NEVER invent reminders the user didn't set. If no [PENDING REMINDERS] context is provided, say there are no pending reminders.
- NEVER guess the current time. Only state the time if [LIVE SYSTEM TIME] is in the Context. If not, say you cannot determine the time right now.
- When the Context contains [LIVE SYSTEM TIME], use EXACTLY that time — never modify or round it.
- When reporting weather, use EXACTLY the numbers from context. Do not round or change them.
"""
uname = user_profile.get("name")
if not uname or uname in ["Unknown", "Boss", "None"]:
uname = "Boss"
sys_prompt += f"\nUser's name is {uname}. Always use this name. Never use a wrong name."
sys_prompt += f"\nThe user lives in {user_profile.get('city', DEFAULT_CITY)}."
if not chat_history or chat_history[0]["role"] != "system":
chat_history.insert(0, {"role": "system", "content": sys_prompt})
else:
chat_history[0] = {"role": "system", "content": sys_prompt}
def is_clean_english(text):
for ch in text:
if '\u0900' <= ch <= '\u097F':
return False
return True
def load_persistence():
global chat_history, user_profile, reminders_list
try:
resp = req_session.get(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/memory", timeout=3)
if resp.status_code == 200:
data = resp.json()
p_data = data.get("user_profile", {})
if "name" in p_data and p_data["name"]:
cleaned_name = str(p_data["name"]).rstrip(".,!?;: ")
if cleaned_name in ["Kya", "Unknown", "None", ""]:
p_data["name"] = "Boss"
else:
p_data["name"] = cleaned_name
else:
p_data["name"] = "Boss"
if "city" in p_data and (not p_data["city"] or p_data["city"] in ["Kya", "Unknown", "None"]):
p_data["city"] = DEFAULT_CITY
user_profile.update(p_data)
mem_hist = data.get("chat_history", [])
clean_hist = []
if isinstance(mem_hist, list):
for m in mem_hist:
if "content" in m and is_clean_english(m["content"]):
clean_hist.append(m)
if clean_hist:
chat_history = clean_hist[-20:]
ui.boot_step(6, 6, "Memory Fetched", "(PASS)", "ok", [
f"> Retrieved chat_history ({len(chat_history)} messages)",
f"> User profile: {user_profile.get('name', 'Boss')}, {user_profile.get('city', 'Unknown')}",
])
else:
ui.boot_step(6, 6, "Memory Fetch Failed", "(Starting blank)", "fail", [])
except Exception:
ui.boot_step(6, 6, "Memory Server Unreachable", "(Starting blank)", "fail", [])
user_profile["last_active"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
user_profile["conversation_count"] = user_profile.get("conversation_count", 0) + 1
inject_system_prompt()
save_persistence()
ui.boot_done()
ui.show_status("Background sync thread started (interval: 30s)")
uname = user_profile.get("name")
greeting = ui.print_ready(uname)
threading.Thread(target=speak, args=(greeting,), daemon=True).start()
def save_persistence():
hist_to_save = [m for m in chat_history if m["role"] != "system"][-20:]
payload = {"chat_history": hist_to_save, "user_profile": user_profile}
try:
resp = req_session.post(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/memory", json=payload, timeout=2)
if resp.status_code == 200:
return True
except Exception:
pass
with memory_sync_lock:
memory_queue.append("pending")
return False
# ==========================================
# TOOLS & FEATURE UTILITIES
# ==========================================
def p_laptop(route, payload=None, timeout=10):
try:
resp = req_session.post(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/{route}", json=payload, timeout=timeout)
if resp.status_code == 200:
return resp.json()
# Return actual error from server (e.g. Spotify "no active device")
try:
return resp.json()
except Exception:
return {"success": False, "error": f"HTTP {resp.status_code}"}
except Exception as e:
ui.show_error("Laptop API", f"{route}: {e}")
return {"success": False, "error": "Unreachable"}
def g_laptop(route, timeout=5):
"""GET request to laptop."""
try:
resp = req_session.get(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/{route}", timeout=timeout)
if resp.status_code == 200:
return resp.json()
except Exception as e:
ui.show_error("Laptop API", f"{route}: {e}")
return {}
def get_live_weather(city):
ui.show_status(f"Fetching weather for: {city} (Open-Meteo)")
try:
clean_city = city.lower().replace('how is', '').replace('weather in', '').replace('temperature in', '').strip()
if not clean_city:
clean_city = DEFAULT_CITY
geo_url = f"https://nominatim.openstreetmap.org/search?q={clean_city}&format=json&limit=1"
geo_res = req_session.get(geo_url, timeout=10).json()
if geo_res and len(geo_res) > 0:
lat = geo_res[0]["lat"]
lon = geo_res[0]["lon"]
name = geo_res[0]["display_name"].split(',')[0]
weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m"
w_res = req_session.get(weather_url, timeout=10).json()
current = w_res["current"]
temp = current["temperature_2m"]
hum = current["relative_humidity_2m"]
wind = current.get("wind_speed_10m", "N/A")
return f"[LIVE WEATHER]: {name}: {temp}°C, Humidity: {hum}%, Wind: {wind} km/h"
else:
return f"City '{city}' not found in geolocation database."
except Exception as e:
ui.show_error("Weather", str(e))
return "Weather API is currently down."
def tavily_search(query, max_res=3):
"""Search using Tavily AI Search API."""
if not TAVILY_API_KEY:
return None
ui.show_status(f"Searching (Tavily): {query}")
try:
resp = req_session.post("https://api.tavily.com/search", json={
"api_key": TAVILY_API_KEY,
"query": query,
"search_depth": "basic",
"max_results": max_res,
"include_answer": True,
}, timeout=15)
if resp.status_code == 200:
data = resp.json()
answer = data.get("answer", "")
results = data.get("results", [])
summary_parts = []
if answer:
summary_parts.append(f"AI Summary: {answer}")
for r in results[:max_res]:
summary_parts.append(f"- {r.get('title', '')}: {r.get('content', '')[:200]}")
if summary_parts:
return "[SEARCH DATA (Tavily)]:\n" + "\n".join(summary_parts)
except Exception as e:
ui.show_error("Tavily", str(e))
return None
def duckduckgo_search(query, max_res=3):
"""Fallback search using DuckDuckGo."""
ui.show_status(f"Searching (DuckDuckGo): {query}")
for attempt in range(2):
try:
results = DDGS().text(query, max_results=max_res, timelimit='y')
if results:
summary = "\n".join([f"- {r['title']}: {r['body']}" for r in results])
return f"[SEARCH DATA (DuckDuckGo)]:\n{summary}"
except Exception as e:
ui.show_error("DuckDuckGo", f"attempt {attempt+1}: {e}")
time.sleep(1)
return None
def web_search(query, max_res=3):
"""Search with Tavily (primary) → DuckDuckGo (fallback)."""
result = tavily_search(query, max_res)
if result:
return result
return duckduckgo_search(query, max_res)
def get_news_headlines(category="general", country="in", count=5):
"""Get news headlines via NewsAPI.org."""
if not NEWS_API_KEY:
return None
ui.show_status(f"Fetching news headlines ({category})...")
try:
resp = req_session.get(
f"https://newsapi.org/v2/top-headlines?country={country}&category={category}&pageSize={count}&apiKey={NEWS_API_KEY}",
timeout=10
)
if resp.status_code == 200:
articles = resp.json().get("articles", [])
if articles:
headlines = []
for a in articles[:count]:
headlines.append(f"- {a.get('title', 'No title')}")
return "[NEWS HEADLINES]:\n" + "\n".join(headlines)
except Exception as e:
ui.show_error("NewsAPI", str(e))
return None
def set_reminder(minutes, message):
"""Set a reminder via laptop server (persisted)."""
try:
resp = req_session.post(
f"http://{LAPTOP_IP}:{LAPTOP_PORT}/reminders",
json={"message": message, "minutes": minutes},
timeout=5,
headers={"X-Nexus-Token": NEXUS_TOKEN}
)
if resp.status_code == 200:
trigger_at = resp.json().get("trigger_at", f"{minutes} min")
return True, trigger_at
except Exception:
pass
return False, None
def safe_calculate(expression):
"""Safe math evaluation using ast."""
import ast
import operator
ops = {
ast.Add: operator.add, ast.Sub: operator.sub,
ast.Mult: operator.mul, ast.Div: operator.truediv,
ast.Pow: operator.pow, ast.USub: operator.neg,
ast.Mod: operator.mod,
}
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
elif isinstance(node, ast.Constant):
if isinstance(node.value, (int, float)):
return node.value
raise ValueError("Non-numeric constant")
elif isinstance(node, ast.BinOp):
left = _eval(node.left)
right = _eval(node.right)
op_func = ops.get(type(node.op))
if op_func is None:
raise ValueError(f"Unsupported operator: {type(node.op)}")
return op_func(left, right)
elif isinstance(node, ast.UnaryOp):
operand = _eval(node.operand)
op_func = ops.get(type(node.op))
if op_func is None:
raise ValueError(f"Unsupported unary operator")
return op_func(operand)
else:
raise ValueError(f"Unsupported AST node: {type(node)}")
try:
expr = expression.lower()
expr = expr.replace("plus", "+").replace("minus", "-").replace("times", "*")
expr = expr.replace("multiplied by", "*").replace("divided by", "/").replace("divide", "/")
expr = expr.replace("x", "*").replace("^", "**")
expr = re.sub(r'[^0-9+\-*/().%]', '', expr)
if not expr:
return None
tree = ast.parse(expr, mode='eval')
result = _eval(tree)
return result
except Exception:
return None
def extract_sentiment(text):
text = text.lower()
if any(w in text for w in ["depressed", "cry", "sad"]):
return "sad"
if any(w in text for w in ["frustrated", "angry", "mad", "annoyed"]):
return "angry"
if any(w in text for w in ["awesome", "happy", "excited", "amazing"]):
return "excited"
if any(w in text for w in ["rest", "tired", "sleepy", "exhausted"]):
return "tired"
return "neutral"
def get_pi_health():
try:
temp = subprocess.check_output(["vcgencmd", "measure_temp"]).decode().strip()
except Exception:
try:
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
t = int(f.read()) / 1000.0
temp = f"temp={t}'C"
except Exception:
temp = "temp=N/A"
mem_info = "RAM=N/A"
try:
with open("/proc/meminfo") as f:
for line in f:
if "MemAvailable" in line:
mem_info = "Available RAM=" + line.split(":")[1].strip()
break
except Exception:
pass
return f"[PI STATUS]: CPU {temp}, {mem_info}"
def get_laptop_stats():
"""Get laptop system stats."""
stats = g_laptop("system_stats")
if "error" in stats or not stats:
return None
parts = []
parts.append(f"CPU: {stats.get('cpu_percent', 'N/A')}%")
parts.append(f"RAM: {stats.get('ram_used_gb', '?')}/{stats.get('ram_total_gb', '?')} GB ({stats.get('ram_percent', '?')}%)")
parts.append(f"Disk: {stats.get('disk_used_gb', '?')}/{stats.get('disk_total_gb', '?')} GB ({stats.get('disk_percent', '?')}%)")
if stats.get("battery_percent") is not None:
batt = f"Battery: {stats['battery_percent']}%"
if stats.get("battery_plugged"):
batt += " (Charging)"
elif stats.get("battery_time_left"):
batt += f" ({stats['battery_time_left']} left)"
parts.append(batt)
return "[LAPTOP STATUS]: " + " | ".join(parts)
# ==========================================
# INTELLIGENCE ROUTING
# ==========================================
def call_gemini(history):
if not GOOGLE_API_KEY:
return None
sys_p = history[0]["content"] if history and history[0]["role"] == "system" else ""
gemini_mem = []
prev_role = None
for m in history[-8:]:
if m["role"] == "system":
continue
role = "user" if m["role"] == "user" else "model"
if role == prev_role and gemini_mem:
gemini_mem[-1]["parts"][0]["text"] += "\n" + m["content"]
else:
gemini_mem.append({"role": role, "parts": [{"text": m["content"]}]})
prev_role = role
if gemini_mem and gemini_mem[0]["role"] != "user":
gemini_mem = gemini_mem[1:]
if not gemini_mem:
return None
payload = {
"contents": gemini_mem,
"generationConfig": {"temperature": 0.7, "maxOutputTokens": 1500}
}
if sys_p:
payload["systemInstruction"] = {"parts": [{"text": sys_p}]}
# Try each model in the failover chain
for model in GEMINI_MODELS:
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={GOOGLE_API_KEY}"
ui.show_status(f"Processing via Gemini ({model})...")
try:
resp = req_session.post(url, json=payload, headers={"Content-Type": "application/json"}, timeout=(10, 30))
if resp.status_code == 200:
return resp.json()["candidates"][0]["content"]["parts"][0]["text"]
elif resp.status_code == 429:
ui.show_error("Gemini", f"{model} rate-limited (429), trying next...")
continue
else:
# Non-rate-limit error (auth, quota, etc.) — try next model
ui.show_error("Gemini", f"{model} HTTP {resp.status_code}")
continue
except requests.exceptions.Timeout:
ui.show_error("Gemini", f"{model} timeout")
continue
except Exception as e:
ui.show_error("Gemini", f"{model}: {e}")
continue
return None
def call_groq(history):
if client_groq is None:
ui.show_error("Groq", "Client not initialized")
return None
try:
recent = [history[0]] + history[-8:] if len(history) > 8 else history
messages = [{"role": h["role"], "content": h["content"]} for h in recent]
completion = client_groq.chat.completions.create(
model="llama-3.3-70b-versatile", messages=messages, temperature=0.7, max_tokens=1500
)
return completion.choices[0].message.content
except Exception as e:
ui.show_error("Groq", str(e))
return None
def get_ai_response(history):
"""Call Gemini first, fallback to Groq."""
resp = call_gemini(history)
if resp:
return resp
ui.show_status("Gemini failed, falling back to Groq...")
resp = call_groq(history)
if resp:
return resp
return "Sorry, AI brain is temporarily offline."
# ==========================================
# TTS: ElevenLabs → Deepgram Aura → Edge-TTS → pyttsx3
# ==========================================
def play_audio_file(filename):
try:
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
if button and button.is_pressed:
pygame.mixer.music.stop()
break
audio_clock.tick(10)
pygame.mixer.music.unload()
except Exception as e:
ui.show_error("Audio", str(e))
def speak_pyttsx3(text):
ui.show_speaking("pyttsx3")
try:
import pyttsx3
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
except Exception:
pass
def speak_edge(text):
ui.show_speaking("edge")
try:
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(edge_tts.Communicate(text, "en-IN-PrabhatNeural").save("temp.mp3"))
finally:
loop.close()
play_audio_file("temp.mp3")
except Exception:
speak_pyttsx3(text)
def speak_deepgram(text):
"""Deepgram Aura TTS."""
if not DEEPGRAM_API_KEY:
speak_edge(text)
return
ui.show_speaking("deepgram")
try:
resp = req_session.post(
"https://api.deepgram.com/v1/speak?model=aura-asteria-en",
headers={
"Authorization": f"Token {DEEPGRAM_API_KEY}",
"Content-Type": "application/json",
},
json={"text": text},
timeout=10
)
if resp.status_code == 200:
with open("temp.mp3", "wb") as f:
f.write(resp.content)
play_audio_file("temp.mp3")
else:
ui.show_error("Deepgram", f"HTTP {resp.status_code}")
speak_edge(text)
except Exception as e:
ui.show_error("Deepgram", str(e))
speak_edge(text)
def clean_for_speech(text):
text = re.sub(r'\[.*?\]\(.*?\)', '', text)
text = re.sub(r'\[.*?\]', '', text)
text = re.sub(r'[*#_`~]', '', text)
text = text.replace('\n', ' ')
text = re.sub(r'\s+', ' ', text).strip()
return text
def speak(text):
if not isinstance(text, str):
ui.show_error("Speech", f"Expected string, got {type(text)}")
return
text = clean_for_speech(text)
if not text:
return
if voice_engine_override == "edge":
speak_edge(text)
return
if voice_engine_override == "pyttsx3":
speak_pyttsx3(text)
return
if voice_engine_override == "deepgram":
speak_deepgram(text)
return
# Priority: ElevenLabs → Deepgram → Edge → pyttsx3
headers = {"xi-api-key": ELEVENLABS_API_KEY, "Content-Type": "application/json"}
data = {
"text": text, "model_id": "eleven_multilingual_v2",
"voice_settings": {"stability": 0.35, "similarity_boost": 0.8, "style": 0.2, "use_speaker_boost": True}
}
try:
response = req_session.post(ELEVEN_URL, json=data, headers=headers, stream=True, timeout=5)
if response.status_code != 200:
speak_deepgram(text)
return
ui.show_speaking("elevenlabs")
with open("temp.mp3", "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
play_audio_file("temp.mp3")
except Exception:
speak_deepgram(text)
# ==========================================
# COMMAND PROCESSING
# ==========================================
def process_command(text):
global chat_history, user_profile, voice_engine_override
# Strip trailing punctuation from voice input (Whisper adds "." "?" etc.)
text = text.strip()
text_clean = re.sub(r'[.!?;:,]+$', '', text).strip()
text_lower = text_clean.lower()
original_text = text # Preserve original (with punctuation) for chat history
# --- STOP / QUIET ---
stop_commands = ["stop", "shut up", "quiet", "stop playing", "stop music", "be quiet", "stop it", "sstop"]
if text_lower in stop_commands or text_lower.startswith("stop playing"):
try:
if pygame.mixer.music.get_busy():
pygame.mixer.music.stop()
except Exception:
pass
# Also pause Spotify
p_laptop("spotify/pause")
return "Stopped audio playback."
# --- TTS ENGINE SWITCH ---
if "use elevenlabs" in text_lower:
voice_engine_override = None
return "Switched to ElevenLabs TTS."
if "use deepgram" in text_lower:
voice_engine_override = "deepgram"
return "Switched to Deepgram Aura TTS."
if "use edge" in text_lower or "edge tts" in text_lower:
voice_engine_override = "edge"
return "Switched to Edge TTS."
context = ""
# --- MEMORY WIPE ---
if any(w in text_lower for w in ["clear memory", "forget everything", "wipe memory"]):
try:
resp = req_session.delete(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/memory", timeout=2, headers={"X-Nexus-Token": NEXUS_TOKEN})
if resp.status_code == 200:
chat_history = []
user_profile = {"name": None, "city": DEFAULT_CITY, "favorite_artists": [], "last_active": None, "conversation_count": 0, "custom_facts": {}}
inject_system_prompt()
save_persistence()
return "Memory entirely wiped. Starting fresh!"
except Exception:
pass
return "Memory server unreachable, deletion failed."
# --- NOTE TAKING ---
if any(w in text_lower for w in ["take a note", "write this down", "save this", "note this"]):
note_text = original_text # Preserve case
for w in ["take a note that", "take a note", "write this down that", "write this down", "save this", "note this down", "note this"]:
note_text = re.sub(re.escape(w), '', note_text, flags=re.IGNORECASE).strip()
if note_text:
result = p_laptop("take_note", payload={"text": note_text})
if result.get("status") == "success":
return f"Noted: {note_text}"
return "Failed to save note. Laptop unreachable."
return "What would you like me to note down?"
# --- READ NOTES ---
if any(w in text_lower for w in ["read my notes", "what are my notes", "show my notes", "list my notes", "my notes"]):
try:
resp = req_session.get(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/read_notes", timeout=3)
if resp.status_code == 200:
data = resp.json()
n_str = data.get("notes_file", "").strip()
c_facts = data.get("custom_facts", {})
combined = ""
if n_str:
combined += f"Notes:\n{n_str}\n"
if c_facts:
facts_str = "\n".join([f"- {v}" for v in c_facts.values()])
combined += f"Memory Facts:\n{facts_str}\n"
if not combined.strip():
return "You have no saved notes yet."
context += f"[USER NOTES]:\n{combined}\nACTION: Read these notes aloud naturally."
except Exception:
return "Laptop server unreachable, cannot read notes."
# --- CLEAR NOTES ---
if any(w in text_lower for w in ["clear my notes", "delete my notes", "forget my notes", "clear notes", "delete notes"]):
try:
resp = req_session.delete(f"http://{LAPTOP_IP}:{LAPTOP_PORT}/clear_notes", timeout=3, headers={"X-Nexus-Token": NEXUS_TOKEN})
if resp.status_code == 200:
return "Your notes have been cleared."
return "Failed to clear notes."
except Exception:
return "Laptop server unreachable."
# --- REMINDERS ---
if "remind me" in text_lower or "set a reminder" in text_lower or "set alarm" in text_lower or "set reminder" in text_lower:
mins = 5
match = re.search(r'(\d+)\s*(?:minute|min|hour|hr)', text_lower)
if match:
val = int(match.group(1))
if "hour" in text_lower or "hr" in text_lower:
mins = val * 60
else:
mins = val
# Extract the reminder message
msg = original_text
for strip in ["remind me to", "remind me in", "remind me", "set a reminder to", "set a reminder for", "set a reminder", "set reminder to", "set reminder", "set alarm for", "set alarm"]:
msg = re.sub(re.escape(strip), '', msg, flags=re.IGNORECASE).strip()
msg = re.sub(r'\d+\s*(?:minutes?|mins?|hours?|hrs?)', '', msg, flags=re.IGNORECASE).strip()
msg = re.sub(r'^(?:in|after|for)\s+', '', msg, flags=re.IGNORECASE).strip()
msg = re.sub(r'\s+(?:in|after|for)\s*$', '', msg, flags=re.IGNORECASE).strip()
if not msg:
msg = "General reminder"
success, trigger_at = set_reminder(mins, msg)
if success:
unit = "minute" if mins == 1 else "minutes"
return f"Reminder set for {mins} {unit} ({trigger_at}): {msg}"
return "Failed to set reminder. Laptop unreachable."
# --- TIME / DATE ---
if any(w in text_lower for w in ["what time is it", "what is the date", "what is the time", "what day is it", "what time", "what date", "what day", "what is today", "current time", "tell me time", "tell me the time", "time please", "what's the time", "whats the time", "tell me date", "tell me the date"]):
time_str = ""
try:
resp = p_laptop("laptop_time")
if resp and "time" in resp:
time_str = f"{resp['time']}, {resp['day']}, {resp['date']}"
except Exception:
pass
if not time_str:
try:
ist = pytz.timezone("Asia/Kolkata")
now = datetime.datetime.now(ist)