-
Notifications
You must be signed in to change notification settings - Fork 0
/
krystal.py
executable file
·189 lines (156 loc) · 5.84 KB
/
krystal.py
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
#! /usr/bin/env python3
import json
import logging
import signal
import sys
import time
from os import environ
from pathlib import Path
import netifaces
from engine.push.dailyupdates import DailyUpdates
from resources.command_handling import command_handler, process_request_text
from resources.verbal_feedback import verbal_feedback
from root import USER_JSON, EVENT_LOG, AUDIO_MODEL, check_valid_sys_requirements, initialize_env_variables
from snowboy import snowboydecoder
# initialize
welcome_msg = "\nThank you for unpacking me!\nI'm starting to get comfy but...\nI don't really know much about you.\n" \
"Soooo, first thing first,\nif you're registered at AbleInc.us go ahead\nand enter your " \
"AI Key.\n"
interrupted = False
def determine_execution():
print(f"Krystal Alpha ------------- {environ['VERSION']}\n")
position = input('Start as Demo? (y/n) > ')
if position.lower() == 'y':
Startup(demo=True)
else:
Updates.universal_handler('update')
Startup()
class Startup:
def __init__(self, demo=False):
self.data = None
self.demo = demo
self.first_name = None
if self.demo:
self.first_name = 'demo user'
self.run_demo_version()
# self.test()
return
def start(self):
user_json_file = Path(USER_JSON)
try:
if not user_json_file.is_file():
sys.stdout.write("Oh my goodness! Hello You!\nThis is our first time meeting :)")
for word in welcome_msg:
sys.stdout.write(word)
sys.stdout.flush()
time.sleep(0.5)
self.verify_member()
return
with open(USER_JSON, 'r') as userdata:
data = json.load(userdata)
name = data['name']
key = data['AIKEY']
username = data['username']
self.first_name = name
status = Updates.universal_handler('status', payload=username)
if status[0] is False:
print(status[1])
sys.exit()
self.run_main_version()
except KeyError:
self.verify_member()
def verify_member(self):
print('Verifying account...')
aikey = input("AI Key: ")
valid_user = Updates.universal_handler('verify', payload=aikey)
if valid_user is None:
print('Could not verify user account. Exiting program.')
sys.exit()
self.first_name = valid_user
self.run_main_version()
def hello(self):
verbal_feedback(phrase=f'Hello, {self.first_name.title()}', vocal_tone='misc', vocal_speed=185,
vocal_volume=0.55)
@staticmethod
def test():
try:
while True:
request = input('Yes? > ')
prefix, str_concat = process_request_text(request)
command_handler(True, (prefix, str_concat))
except KeyboardInterrupt:
sys.exit()
def run_main_version(self):
self.hello()
Updates.universal_handler('push')
while bool(environ['AUTO_REFRESH']):
hey_krystal()
start_processes()
def run_demo_version(self):
self.hello()
print("Thank you for using Krystal. In demo mode you will not receive\n"
"notifications or automatic updates. This account is not personalized.")
while bool(environ['AUTO_REFRESH']):
hey_krystal()
start_processes()
def save_conversation(user_statement, krystal_statement):
"""
Sends spoken and response conversation to Able servers. Conversation
logs are kept for users to view in the Able Access Conversation Portal.
:param user_statement: the user spoken dialogue
:param krystal_statement: krystal's response to user
:return:
"""
Updates.universal_handler(use='conversation', user_statement=user_statement, krystal_statement=krystal_statement)
return
def signal_handler(signal, frame):
global interrupted
interrupted = True
def interrupt_callback():
global interrupted
return interrupted
def hey_krystal():
"""
Detects "Hey Krystal"
:return:
"""
# capture SIGINT signal, e.g., Ctrl+C
signal.signal(signal.SIGINT, signal_handler)
detector = snowboydecoder.HotwordDetector(AUDIO_MODEL, sensitivity=0.5)
# main loop
detector.start(detected_callback=snowboydecoder.play_audio_file,
interrupt_check=interrupt_callback,
sleep_time=0.03)
detector.terminate()
def start_processes():
"""
Start processes after "Hey Krystal" is triggered
:return:
"""
verbal_feedback('Yes?')
if not command_handler():
log_events.error('COMMAND HELPER FAILURE')
environ['AUTO_REFRESH'] = 'False'
else:
log_events.info('command handler - success')
if __name__ == '__main__':
initialize_env_variables()
check_valid_sys_requirements()
# Logger
logging.basicConfig(filename=EVENT_LOG, format='%(asctime)s:%(levelname)s:%(name)s - %(message)s',
level=logging.INFO)
log_events = logging.getLogger('krystal.py')
start_datetime = f' Started on {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))}'
try:
ip4 = netifaces.ifaddresses('en0')[netifaces.AF_INET][0]['addr']
ip6 = netifaces.ifaddresses('en0')[netifaces.AF_INET6][0]['addr']
except KeyError:
ip4 = netifaces.ifaddresses('en7')[netifaces.AF_INET][0]['addr']
ip6 = netifaces.ifaddresses('en7')[netifaces.AF_INET6][0]['addr']
network_msg = f' Network Info - IP4: {ip4}, IP6: {ip6}'
log_events.info(start_datetime)
log_events.info(network_msg)
# Updates library
Updates = DailyUpdates()
# Start application
determine_execution()