-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathOPSIIE_0_3_80_XP.py
More file actions
2517 lines (2120 loc) · 103 KB
/
Copy pathOPSIIE_0_3_80_XP.py
File metadata and controls
2517 lines (2120 loc) · 103 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
import datetime
from threading import Thread
import ollama
import chromadb
import psycopg
import ast
import unicodedata
import shutil
from psycopg.rows import dict_row
from transformers import BlipProcessor, BlipForConditionalGeneration, AutoProcessor, MusicgenForConditionalGeneration
import PIL
from PIL import Image
import requests
from io import BytesIO
import re
from bs4 import BeautifulSoup
import time
import cv2
import face_recognition
from deepface import DeepFace
import numpy as np
import sys
import pyttsx3
import speech_recognition as sr
import random
import pygame
import requests
import os
import pandas as pd
import PyPDF2
import pdfplumber
from docx import Document
import collections
import librosa
from scipy.spatial.distance import cosine
from scipy.io.wavfile import write
from diffusers import StableDiffusionPipeline
import torch
import torchaudio
from torch import autocast
from web3 import Web3
from dotenv import load_dotenv
import json
import yfinance as yf
# Import color functions from terminal_colors
from terminal_colors import (
pastel_color, pastel_lilac, pastel_pink, pastel_green, pastel_yellow, pastel_blue, pastel_red, pastel_cyan, pastel_magenta, pastel_white, pastel_gray, pastel_light_white, pastel_gradient_bar, set_palette, PASTEL, VIBRANT, select_theme
)
# Native Modules
from utils import (
get_system_prompt,
get_random_expression,
ensure_directory_exists,
clean_filename,
master_user_greetings,
get_agent_intro,
get_agent_display_names
)
from kun import known_user_names, save_known_user_names
from agentic_network import ask_model, start_live_g1_conversation, G1_VOICE_LIVE, KRONOS_LIVE, MODEL_APIS
import markets
from markets import handle_markets_command
from help import display_help, detailed_help_texts, display_detailed_help
from markets_mappings import keyword_mapping
from mail import send_mail, inbox_interaction, EMAIL, PASSWORD
from dna import handle_dna_command, generate_random_dna, is_dna
from room import Room
from video import handle_video_command
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
load_dotenv()
# ___ _ ___ ___ _ _
# / __| | / _ \| _ ) /_\ | |
# | (_ | |_| (_) | _ \/ _ \| |__
# \___|____\___/|___/_/ \_\____|
# *** GLOBAL Settings *** | Initialization | Mode | System Prompt
def print_opsiie_logo_gradient():
logo = [
" ███ ███████ ███████████ █████████ █████ █████ ██████████",
"░░░███ ███░░░░░███ ░░███░░░░░███ ███░░░░░███░░███ ░░███ ░░███░░░░░█",
" ░░░███ ███ ░░███ ░███ ░███░███ ░░░ ░███ ░███ ░███ █ ░ ",
" ░░░███ ░███ ░███ ░██████████ ░░█████████ ░███ ░███ ░██████ ",
" ███░ ░███ ░███ ░███░░░░░░ ░░░░░░░░███ ░███ ░███ ░███░░█ ",
" ███░ ░░███ ███ ░███ ███ ░███ ░███ ░███ ░███ ░ █",
" ███░ ░░░███████░ █████ ░░█████████ █████ █████ ██████████",
"░░░ ░░░░░░░ ░░░░░ ░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░░░ "
]
# Gradient from lilac to pink in the active palette
from terminal_colors import _active_palette
start_color = _active_palette['lilac']
end_color = _active_palette['pink']
steps = max(len(line) for line in logo)
def get_gradient_color(i, total):
r = int(start_color[0] + (end_color[0] - start_color[0]) * i / total)
g = int(start_color[1] + (end_color[1] - start_color[1]) * i / total)
b = int(start_color[2] + (end_color[2] - start_color[2]) * i / total)
return f'\033[38;2;{r};{g};{b}m'
reset = '\033[0m'
print("\n\n", end="") # Add two blank lines before the logo
for line in logo:
for i, char in enumerate(line):
print(get_gradient_color(i, steps - 1) + char, end='')
print(reset)
def display_splash():
"""Displays the splash screen at start-up."""
# Initialize the pygame mixer
pygame.mixer.init()
try:
# Dynamically construct the path to system_sounds/opsiieboot.mp3
sound_path = os.path.join(os.path.dirname(__file__), 'system_sounds', 'opsiieboot.mp3')
pygame.mixer.music.load(sound_path)
pygame.mixer.music.play()
except Exception as e:
print(pastel_red(f"Error fetching opsiieboot.mp3: {str(e)}"))
# Print the Gemini-style gradient logo
print_opsiie_logo_gradient()
print(pastel_green("""
A Self-Centered Intelligence (SCI) Prototype
By ARPA HELLENIC LOGICAL SYSTEMS | Version: 0.3.80 XP | 12 MAY 2026
"""))
time.sleep(2)
# Initialize ChromaDB client
client = chromadb.Client()
vector_db = None
AGENT_DISPLAY_NAMES = get_agent_display_names()
OLLAMA_CHAT_MODEL = os.getenv("OLLAMA_MODEL", "llama3")
OLLAMA_EMBED_MODEL = os.getenv("OLLAMA_EMBED_MODEL", "nomic-embed-text")
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
ORG_ID = os.getenv('ORG_ID')
NYX_ASSISTANT_ID = os.getenv('NYX_ASSISTANT_ID')
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
G1_VOICE_LIVE = os.getenv('G1_VOICE_LIVE')
KRONOS_LIVE = os.getenv('KRONOS_LIVE')
ELEVENLABS_API_KEY = os.getenv('ELEVENLABS_API_KEY')
current_user = None
call_name = None
web3_connection = None
web3_handler = None
current_room = None
WEB3_REQUIRED_ENV_VARS = (
"AGENT_PRIVATE_KEY",
"BASE_RPC_URL",
"ETHEREUM_RPC_URL",
"POLYGON_RPC_URL",
)
def get_missing_web3_env_vars():
return [name for name in WEB3_REQUIRED_ENV_VARS if not os.getenv(name)]
def get_web3_handler():
global web3_handler
if web3_handler is not None:
return web3_handler
missing_env_vars = get_missing_web3_env_vars()
if missing_env_vars:
raise RuntimeError(
"Web3 is not configured. Set "
+ ", ".join(missing_env_vars)
+ " before using Web3 commands."
)
try:
from web3_handler import Web3Handler
web3_handler = Web3Handler(known_user_names)
return web3_handler
except Exception as e:
raise RuntimeError(f"Web3 initialization failed: {str(e)}") from e
#Temporal Data Pocket for SoulSig
#(used as a security measure during the wipe process)
temporary_soul_sig = None
#Temporal Data Pocket for /read
file_context = {}
#System Prompt
system_prompt = get_system_prompt()
# Initial conversation history with the system prompt
convo = [{'role': 'system', 'content': system_prompt}]
# Initialize TTS engine (for voice output)
engine = pyttsx3.init()
# Initialize the microphone globally
recognizer = sr.Recognizer()
mic = sr.Microphone()
MFCC_TARGET_LENGTH = 100
# Track the current mode in the system
current_mode = "text"
def set_mode(mode):
global current_mode
current_mode = mode
print(pastel_cyan(f"Mode set to: {mode}"))
def is_master_user():
"""Check if current user has master (R-grade) privileges."""
global current_user, known_user_names
if not current_user or current_user not in known_user_names:
return False
return known_user_names[current_user]['arpa_id'].startswith('R')
def handle_restricted_command():
"""Handle attempt to access restricted command by non-master user."""
message = pastel_red("This command requires Master User (R-Grade) privileges. Please contact your system administrator for access.")
print(pastel_red(message))
if voice_mode_active or agent_voice_active:
speak_response(message)
return False
# Global voice off by default
voice_mode_active = False
agent_voice_active = False
#Initialize Music Generation
musicgen_model = None
musicgen_processor = None
try:
device = 'cuda' if torch.cuda.is_available() else 'cpu'
musicgen_processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
musicgen_model = MusicgenForConditionalGeneration.from_pretrained(
"facebook/musicgen-small", attn_implementation="eager"
)
musicgen_model = musicgen_model.to(device)
except Exception as e:
print(pastel_red(f"Error initializing MusicGen model: {str(e)}"))
musicgen_model = None
musicgen_processor = None
# __ _____ ___ ___ ___
# \ \ / / _ \_ _/ __| __|
# \ V / (_) | | (__| _|
# \_/ \___/___\___|___|
# *** Voice Interpreter *** | ELEVEN LABS | Speak Response | Custom Sounds | Voice Commands
# ELEVEN LABS API and Voice ID
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
VOICE_ID = os.getenv("VOICE_ID")
NYX_VOICE_ID = os.getenv("NYX_VOICE_ID")
G1_VOICE_ID = os.getenv("G1_VOICE_ID")
G1_VOICE_LIVE = os.getenv('G1_VOICE_LIVE')
def verify_elevenlabs_api():
"""Verifies Eleven Labs API access by making a test request."""
url = 'https://api.elevenlabs.io/v1'
headers = {
'xi-api-key': ELEVENLABS_API_KEY,
'voice_id': VOICE_ID
}
retries = 3
for attempt in range(retries):
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return True
else:
print(pastel_yellow(f"[Warning] Eleven Labs API check attempt {attempt + 1} failed: Status code {response.status_code}"))
except Exception as e:
print(pastel_yellow(f"[Warning] Eleven Labs API check attempt {attempt + 1} failed: {str(e)}"))
time.sleep(2)
return False
def speak_agent_response(text, agent_name):
"""Speaks response using the appropriate voice for the agent, without the agent prefix."""
global VOICE_ID, OPSIE_VOICE_ID, NYX_VOICE_ID, G1_VOICE_ID
# Remove the agent prefix from the spoken response
# This matches patterns like "NYX:" or "G1:" at the start of the text
clean_text = re.sub(r'^\s*[A-Za-z0-9]+:\s*', '', text)
# Temporarily change voice ID based on agent
original_voice = VOICE_ID
try:
if agent_name.lower() == 'nyx':
VOICE_ID = NYX_VOICE_ID
elif agent_name.lower() == 'g1':
VOICE_ID = G1_VOICE_ID
speak_response(clean_text)
finally:
# Restore original voice
VOICE_ID = original_voice
# Speak the response using Eleven Labs API
def speak_response(text):
"""Converts the response text to speech using Eleven Labs API."""
global call_name
if not text:
print(pastel_red("Error: Cannot speak an empty or None response."))
return
url = f'https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream?optimize_streaming_latency=3'
headers = {
'xi-api-key': ELEVENLABS_API_KEY,
'Content-Type': 'application/json'
}
data = {
'text': text,
'voice_id': VOICE_ID
}
response = requests.post(url, json=data, headers=headers)
if response.status_code == 200:
audio_content = response.content
with open("output.mp3", "wb") as f:
f.write(audio_content)
pygame.mixer.init()
pygame.mixer.music.load("output.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
pygame.mixer.music.stop()
pygame.mixer.music.unload()
try:
os.remove("output.mp3")
except PermissionError as e:
print(pastel_red(f"Error deleting the temporary audio file: {str(e)}"))
else:
print(pastel_red(f"Error with Eleven Labs API: {response.status_code}"))
print(pastel_red(response.text))
# List of spoken reference keywords and phrases
custom_words = {
"Opsie": [r'E:\\Agents\\Test 1\\opsie.mp3'],
"Voice off": [r'E:\\Agents\\Test 1\\voiceoff.mp3'],
"send Base Degen": [
r'E:\\Agents\\Test 1\\sendbasedegen.mp3',
r'E:\\Agents\\Test 1\\sendbasedegen2.mp3',
r'E:\\Agents\\Test 1\\sendbasedegen3.mp3'
],
"20 to Ross": [
r'E:\\Agents\\Test 1\\20toross.mp3',
r'E:\\Agents\\Test 1\\20toross2.mp3',
r'E:\\Agents\\Test 1\\20toross3.mp3'
],
"50 to Ross": [
r'E:\\Agents\\Test 1\\50toross.mp3',
r'E:\\Agents\\Test 1\\50toross2.mp3',
r'E:\\Agents\\Test 1\\50toross3.mp3'
]
}
# Load and preprocess the reference sounds
def load_custom_sounds(custom_words):
"""Loads custom sounds as MFCCs."""
loaded_sounds = {}
for word, paths in custom_words.items():
loaded_sounds[word] = []
for path in paths:
try:
audio_data, sr = librosa.load(path, sr=None)
mfcc = librosa.feature.mfcc(y=audio_data, sr=sr)
mfcc = pad_or_trim_mfcc(mfcc, MFCC_TARGET_LENGTH)
loaded_sounds[word].append(mfcc)
except Exception as e:
print(f"Error loading {word} from {path}: {e}")
return loaded_sounds
# Helper function to ensure MFCCs are of a consistent length
def pad_or_trim_mfcc(mfcc, target_length=MFCC_TARGET_LENGTH):
"""
Ensure that the MFCC or audio data array has a consistent length.
Pads or trims the MFCC to the target length.
"""
if mfcc.shape[1] > target_length:
return mfcc[:, :target_length]
elif mfcc.shape[1] < target_length:
# Pad with zeros if it's shorter than the target length
return np.pad(mfcc, ((0, 0), (0, target_length - mfcc.shape[1])), mode='constant')
return mfcc
def calculate_audio_similarity(voice_text_audio, sound_data_audio):
"""Calculate audio similarity using cosine distance of MFCCs."""
mfcc_voice_text = librosa.feature.mfcc(y=voice_text_audio, sr=16000, n_mfcc=13)
mfcc_sound_data = librosa.feature.mfcc(y=sound_data_audio, sr=16000, n_mfcc=13)
# Flatten the MFCCs
mfcc_voice_text_flat = mfcc_voice_text.flatten()
mfcc_sound_data_flat = mfcc_sound_data.flatten()
# Calculate cosine similarity
similarity = 0.65 - cosine(mfcc_voice_text_flat, mfcc_sound_data_flat)
return similarity
# Match input audio with preloaded custom sounds
def match_custom_word(input_audio, custom_sounds, threshold=0.1):
"""Matches input audio against custom word sounds and returns the recognized word."""
input_mfcc = librosa.feature.mfcc(y=input_audio, sr=16000)
for word, reference_mfccs in custom_sounds.items():
for reference_mfcc in reference_mfccs:
similarity = cosine(input_mfcc.flatten(), reference_mfcc.flatten())
if similarity < threshold:
return word
return None
# Load the custom sounds for matching
custom_sounds = load_custom_sounds(custom_words)
def process_custom_words_in_speech(audio):
"""Processes the audio input and replaces recognized custom words."""
input_audio, sr = librosa.load(BytesIO(audio), sr=16000)
matched_word = match_custom_word(input_audio, custom_sounds)
if matched_word:
return matched_word
return None
MFCC_TARGET_LENGTH = 260
def load_custom_sounds(custom_words):
"""Loads and preprocesses custom word sounds."""
loaded_sounds = {}
for word, path in custom_words.items():
if not os.path.exists(path):
print(pastel_red(f"Error: File not found - {path}"))
continue
try:
audio_data, sr = librosa.load(path, sr=None)
mfcc = librosa.feature.mfcc(y=audio_data, sr=sr)
mfcc = pad_or_trim_mfcc(mfcc, MFCC_TARGET_LENGTH)
loaded_sounds[word] = mfcc
except Exception as e:
print(pastel_red(f"Error loading {word} from {path}: {e}"))
return loaded_sounds
def compare_mfccs(input_mfcc, custom_sounds, similarity_threshold=0.8):
"""Compares the MFCC of the input with the preloaded custom sounds."""
input_mfcc_padded = pad_or_trim_mfcc(input_mfcc, MFCC_TARGET_LENGTH)
for word, custom_mfcc in custom_sounds.items():
similarity = np.dot(input_mfcc_padded.flatten(), custom_mfcc.flatten()) / (
np.linalg.norm(input_mfcc_padded.flatten()) * np.linalg.norm(custom_mfcc.flatten()))
if similarity >= similarity_threshold:
return word
return None
# Function that handles voice commands
def handle_voice_command(voice_text):
global voice_mode_active, agent_voice_active
if not voice_text:
return
voice_text = voice_text.lower().strip()
# Check for restricted commands in voice input
command = voice_text.split()[0].lower() if voice_text else ''
if command in ['ask', 'markets', 'dna', '0x'] and not is_master_user():
handle_restricted_command()
return
# Exact match command detection for system commands
if voice_text == "voice off" or voice_text == "exit voice mode":
handle_user_query("/voiceoff")
voice_mode_active = False
agent_voice_active = False
speak_response("Verbal communication protocol bridge collapsed successfully.")
return
# Normal command flow continues if voice mode is active
if voice_mode_active:
# Check if it's a command (starts with / or is a known command word)
is_command = (voice_text.startswith('/') or
voice_text.startswith(('recall ', 'memorize ', 'status', 'help', 'imagine ', 'room',
'markets ', 'read ', 'voice', 'ask', '0x', 'dna', 'video', 'music', 'theme',)))
if voice_text.startswith("recall "):
recall_keyword = voice_text.replace("recall", "").strip()
command = f"/recall {recall_keyword}"
handle_user_query(command)
speak_response(f"Recall command executed successfully for keyword: {recall_keyword}")
return
elif voice_text.startswith("memorize "):
memory_data = voice_text.replace("memorize", "").strip()
command = f"/memorize {memory_data}"
handle_user_query(command)
speak_response(f"Memorized: {memory_data}")
return
elif voice_text == "status":
command = "/status"
handle_user_query(command)
speak_response("System status displayed.")
return
elif voice_text == "help":
handle_user_query("/help")
speak_response("Help displayed.")
return
elif voice_text == "theme":
handle_user_query("/theme")
speak_response("Theme selector activated.")
return
elif voice_text.startswith("imagine "):
prompt = voice_text.replace("imagine", "").strip()
if prompt:
response = handle_imagine_command(f"/imagine {prompt}")
if response:
speak_response(response)
else:
speak_response("Please provide a valid description after 'imagine'.")
return
elif voice_text.startswith("markets "):
command = voice_text.replace("markets", "/markets", 1).strip()
handle_user_query(command)
return
elif voice_text.startswith("read "):
command = voice_text.replace("read", "/read", 1).strip()
handle_user_query(command)
return
# If none of the above commands were matched, execute the generic command
handle_user_query(voice_text)
# Only say "Command executed" if it was an actual command
if is_command:
speak_response("Command executed.")
else:
handle_user_query(voice_text)
# Voice mode toggling function
def toggle_voice_mode(mode):
global voice_mode_active, agent_voice_active
if mode == "/voice":
voice_mode_active = True
agent_voice_active = True
print(pastel_green("Verbal communications protocol initialized."))
speak_response("Voice mode activated. Verbal communication system online.")
# Start a loop to handle voice commands
while voice_mode_active:
voice_text = capture_voice_input()
if voice_text:
handle_voice_command(voice_text)
else:
# If no voice input is captured, exit voice mode
print(pastel_yellow("No voice input detected. Exiting voice mode."))
voice_mode_active = False
agent_voice_active = False
break
elif mode == "/voice1":
agent_voice_active = True
print(pastel_green("SCI voice responses activated. You can keep typing your input."))
speak_response("SCI voice responses activated.")
elif mode == "/voice2":
voice_mode_active = True
agent_voice_active = False
print(pastel_green("User mic input enabled. Agent responds in text only."))
speak_response("Voice mode restricted to user only. I will only respond in text.")
# Start a loop to handle voice commands
while voice_mode_active:
voice_text = capture_voice_input()
if voice_text:
handle_voice_command(voice_text)
else:
# If no voice input is captured, exit voice mode
print(pastel_yellow("No voice input detected. Exiting voice mode."))
voice_mode_active = False
agent_voice_active = False
break
elif mode == "/voiceoff":
voice_mode_active = False
agent_voice_active = False
print(pastel_red("Voice mode deactivated."))
speak_response("Verbal communication protocol bridge collapsed successfully.")
# Define multiple responses for when the system doesn't understand the user's voice input
misunderstood_responses = [
f"Sorry, I didn't catch that, {call_name}",
f"Can you please repeat that {call_name}?",
f"Hmm, I missed that. Could you say it again {call_name}?",
f"I'm having trouble understanding, could you try again {call_name}?",
f"Oops, I didn't quite get that. Can you repeat {call_name}?"
]
# *** Voice Input Interpreter Enhancements ***
# Ensure that before any voice text is processed, we first compare against custom sounds
def interpret_custom_sounds(voice_text_audio):
global custom_sounds
recognized_custom_words = []
# Compare voice input with preloaded custom sounds
for word, sound_data_list in custom_sounds.items():
for sound_data in sound_data_list:
similarity = calculate_audio_similarity(voice_text_audio, sound_data)
if similarity > 0.65:
recognized_custom_words.append(word)
# Replace recognized words in the final voice_text
voice_text = voice_to_text(voice_text_audio)
for word in recognized_custom_words:
voice_text = voice_text.replace(word, recognized_custom_words[0])
return voice_text
def capture_voice_input():
"""Captures voice input using the microphone, handling long and short speech dynamically."""
global voice_mode_active
voice_text = ""
accumulated_speech = ""
start_time = time.time()
max_listening_time = 60
with mic as source:
recognizer.adjust_for_ambient_noise(source)
print(pastel_cyan("Listening for your input..."))
while voice_mode_active:
try:
# Step 1: Capture audio from the microphone
audio = recognizer.listen(source, timeout=10, phrase_time_limit=20)
# Step 2: Transcribe the audio to text using Google Speech API
voice_text = voice_to_text(audio).strip().lower()
accumulated_speech += " " + voice_text
print(pastel_white(f"USER (via voice): {voice_text}"))
# Step 3: Check listening timeout
if time.time() - start_time > max_listening_time:
print(pastel_yellow("Max listening time reached. Processing captured input."))
break
return accumulated_speech.strip()
except sr.WaitTimeoutError:
print(pastel_yellow("No speech detected within the timeout. Listening stopped."))
break
except sr.UnknownValueError:
response = random.choice(misunderstood_responses)
print(pastel_yellow(response))
speak_response(response)
continue
except Exception as e:
print(pastel_red(f"Error during voice recognition: {str(e)}"))
speak_response("An error occurred while processing your speech. Please try again.")
continue
return accumulated_speech.strip() if accumulated_speech else None
def voice_to_text(audio):
"""Converts the captured audio to text using Google Speech API."""
try:
voice_text = recognizer.recognize_google(audio)
return voice_text
except sr.UnknownValueError:
return ""
except Exception as e:
print(pastel_red(f"Error in voice recognition: {str(e)}"))
return ""
# *** Voice Mode Toggling Function ***
def toggle_voice_mode(mode):
global voice_mode_active, agent_voice_active
if mode == "/voice":
voice_mode_active = True
agent_voice_active = True
print(pastel_green("Verbal communications protocol initialized."))
speak_response("Voice mode activated. Verbal communication system online.")
# Start a loop to handle voice commands
while voice_mode_active:
voice_text = capture_voice_input()
if voice_text:
handle_voice_command(voice_text)
else:
# If no voice input is captured, exit voice mode
print(pastel_yellow("No voice input detected. Exiting voice mode."))
voice_mode_active = False
agent_voice_active = False
break
elif mode == "/voice1":
agent_voice_active = True
print(pastel_green("SCI voice responses activated. You can keep typing your input."))
speak_response("SCI voice responses activated.")
elif mode == "/voice2":
voice_mode_active = True
agent_voice_active = False
print(pastel_green("User mic input enabled. Agent responds in text only."))
speak_response("Voice mode restricted to user only. I will only respond in text.")
while voice_mode_active:
voice_text = capture_voice_input()
if voice_text:
handle_voice_command(voice_text)
else:
# If no voice input is captured, exit voice mode
print(pastel_yellow("No voice input detected. Exiting voice mode."))
voice_mode_active = False
agent_voice_active = False
break
elif mode == "/voiceoff":
voice_mode_active = False
agent_voice_active = False
print(pastel_red("Voice mode deactivated."))
speak_response("Verbal communication protocol bridge collapsed successfully.")
# *** Initial lazy voice window ***
def listen_for_voice_command(timeout=5):
"""Listen for a voice command for a limited time window after boot-up."""
global voice_mode_active
start_time = time.time()
voice_text = ""
audio_initialized = False
while time.time() - start_time < timeout:
with mic as source:
print(pastel_cyan(f"Listening for voice commands... You have {timeout} seconds to say 'voice' to continue in voice mode."))
try:
if not audio_initialized:
recognizer.adjust_for_ambient_noise(source)
audio_initialized = True
audio = recognizer.listen(source, timeout=timeout)
voice_text = recognizer.recognize_google(audio).lower()
print(pastel_white(f"USER (via voice): {voice_text}"))
break
except sr.UnknownValueError:
print(pastel_yellow("Waiting for a clear command..."))
except sr.WaitTimeoutError:
print(pastel_yellow("Timeout reached, no voice command detected."))
break
# If "voice" is detected, initialize voice mode
if "voice" in voice_text:
print(pastel_cyan("Lazy mode triggered!"))
toggle_voice_mode("/voice")
else:
# If no voice command is detected, proceed with text interface
print(pastel_yellow("Loading text interface"))
speak_response(f"Default typing mode launching {call_name}. To activate voice mode, simply type /voice, anytime during the conversation.")
# ___ _____ ___ ___ _ __ __ ___ ___ ___ ___ ___ _ _ ___ ___
# / __|_ _| _ \ __| /_\ | \/ | | _ \ __/ __| _ \/ _ \| \| / __| __|
# \__ \ | | | / _| / _ \| |\/| | | / _|\__ \ _/ (_) | .` \__ \ _|
# |___/_|\_\___|____|____\_/\_/_/ \_\_|_\___|___/_| \___/|_|\_|___/___|
# *** Stream Response *** |
def stream_response(prompt):
"""Stream a response from the AI model for regular conversations."""
global convo, agent_voice_active, voice_mode_active
response = ''
stream = ollama.chat(model=OLLAMA_CHAT_MODEL, messages=convo, stream=True)
# Print "OPSIE" prefix for every streamed chunk
print(pastel_green('OPSIE:'), end=' ')
for chunk in stream:
content = chunk.get('message', {}).get('content', '')
response += content
print(content, end='', flush=True)
print()
# Store in main conversation
store_conversations(prompt=prompt, response=response)
convo.append({'role': 'assistant', 'content': response})
# Only speak if voice mode is active
if agent_voice_active or voice_mode_active:
speak_response(response)
return response
def stream_room_response(prompt, conversation):
"""Stream a response from the AI model for room interactions."""
response = ''
stream = ollama.chat(model=OLLAMA_CHAT_MODEL, messages=conversation, stream=True)
for chunk in stream:
content = chunk.get('message', {}).get('content', '')
response += content
return response
def get_opsie_response(prompt, room_system_prompt=None):
"""Get response from Opsie for room interactions."""
# Create a temporary conversation for room interaction
temp_convo = []
# Combine room system prompt with regular system prompt
combined_prompt = f"{get_system_prompt()}\n\nRoom Context: {room_system_prompt}" if room_system_prompt else get_system_prompt()
temp_convo.append({'role': 'system', 'content': combined_prompt})
temp_convo.append({'role': 'user', 'content': prompt})
# Use stream_room_response for room interactions
response = stream_room_response(prompt, temp_convo)
return response
# ___ ___ ___ _ _ ___ ___ _______ __
# / __| __/ __| | | | _ \_ _|_ _\ \ / /
# \__ \ _| (__| |_| | /| | | | \ V /
# |___/___\___|\___/|_|_\___| |_| |_|
# *** Security *** | Facial Recognition | Boot-up and System Checks | Help
#emotions = [
# 'angry',
# 'disgust',
# 'fear',
# 'happy',
# 'sad',
# 'surprise',
# 'neutral'
#]
def detect_emotion(frame):
"""Detects emotions in a given frame using DeepFace."""
try:
result = DeepFace.analyze(frame, actions=['emotion'], enforce_detection=False)
if isinstance(result, list):
result = result[0]
dominant_emotion = result.get('dominant_emotion', None)
if dominant_emotion:
return dominant_emotion
else:
print(pastel_red("[Error] No dominant emotion detected."))
return None
except Exception as e:
print(pastel_red(f"[Error] Failed to detect emotion: {str(e)}"))
return None
def facial_recognition_auth():
"""Performs facial recognition to authenticate the user before boot-up."""
global current_user, call_name, db_params, known_user_names
known_image_paths = {name: user['picture'] for name, user in known_user_names.items() if user['picture']}
known_encodings = {}
for name, path in known_image_paths.items():
try:
known_image = face_recognition.load_image_file(path)
face_encodings = face_recognition.face_encodings(known_image)
if len(face_encodings) > 0:
known_encodings[name] = face_encodings[0]
else:
print(pastel_red(f"[Error] No face found in the image for {name}."))
except Exception as e:
print(pastel_red(f"[Error] Failed to load or process image for {name}: {str(e)}"))
sys.exit()
if not known_encodings:
print(pastel_red("[Error] Unauthorized actor detected. The UBA security protocol will now terminate operations."))
sys.exit()
video_capture = cv2.VideoCapture(0)
if not video_capture.isOpened():
print(pastel_red("[Error] Unable to access the camera. Make sure it's connected and working as expected."))
sys.exit()
print(pastel_red("\n[Security] Performing facial recognition for authentication...DO NOT turn off the camera"))
start_time = time.time()
match_found = False
warning_printed = False
while True:
ret, frame = video_capture.read()
if not ret:
print(pastel_red("[Error] Unable to capture video. Make sure your camera is properly connected and operational."))
video_capture.release()
sys.exit()
rgb_frame = frame[:, :, ::-1]
# Detect the dominant emotion
dominant_emotion = detect_emotion(frame)
# Check if the detected emotion is "angry" or "fear" and fail the authentication
if dominant_emotion in ['angry', 'fear']:
print(pastel_red(f"[Security] Abnormal stress levels detected. Detected emotion: {dominant_emotion}."))
print(pastel_yellow("Please try again when your mental and emotional state is in normalized spectrum."))
video_capture.release()
sys.exit()
# If no emotion is detected or it's a neutral/happy emotion, continue
if dominant_emotion:
print(pastel_green(f"[Security] Emotional state: {dominant_emotion}. Proceeding with facial recognition."))
else:
print(pastel_yellow("[Security] No strong emotion detected. Proceeding with facial recognition."))
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
if len(face_encodings) == 0:
if time.time() - start_time > 9 and not warning_printed:
print(pastel_yellow("[Warning] Step up to the camera. Make sure the lens is clear and not blocked."))
warning_printed = True
if time.time() - start_time > 18:
print(pastel_red("[Error] Failed to authenticate: No face detected. Please ensure you are standing in front of the camera."))
video_capture.release()
sys.exit()
else:
for face_encoding in face_encodings:
for name, known_encoding in known_encodings.items():
match = face_recognition.compare_faces([known_encoding], face_encoding)
if match[0]:
match_found = True
user_info = known_user_names.get(name)
if user_info:
current_user = user_info['full_name']
call_name = user_info['call_name']
db_params = user_info['db_params']
public0x = user_info['public0x']
arpa_id = user_info['arpa_id']
if user_info['arpa_id'].startswith('R'):
print(pastel_green(f"[Security] Authentication successful. Master User recognized. Welcome, {current_user}!"))
# Initialize a separate mixer channel for the greeting
greeting_channel = pygame.mixer.Channel(1)
greeting = random.choice(master_user_greetings).format(call_name=call_name)
def play_greeting():
response = requests.post(
f'https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream',
headers={'xi-api-key': ELEVENLABS_API_KEY, 'Content-Type': 'application/json'},
json={'text': greeting, 'voice_id': VOICE_ID}
)
if response.status_code == 200:
with open("greeting.mp3", "wb") as f:
f.write(response.content)
greeting_sound = pygame.mixer.Sound("greeting.mp3")
greeting_channel.play(greeting_sound)
# Start greeting playback in a separate thread
Thread(target=play_greeting, daemon=True).start()
else:
print(pastel_green(f"[Security] Authentication successful. Welcome, {current_user} ({call_name})!"))
video_capture.release()
return current_user, call_name, db_params, dominant_emotion, public0x, arpa_id
if not match_found:
print(pastel_red("[Error] Unauthorized actor detected. The security protocol will now terminate operations."))
video_capture.release()
sys.exit()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
sys.exit()
# *** Boot-Up Sequence ***
def boot_up_sequence():
"""Boot-up process with auth checks and initializations."""
global current_user, call_name, db_params, dominant_emotion, public0x, arpa_id, vector_db, system_prompt, web3_handler