-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfunctions.py
192 lines (149 loc) · 4.87 KB
/
functions.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
190
191
192
#// global modules \\\\\\\\#
import openai
from sys import stdout
import speech_recognition as sr
from subprocess import call, PIPE
from gtts import gTTS
#\\\\\\\\ global modules //
#// local modules \\\\\\\\#
import voice
import errors
import colors
import data
import cursor
import config.complete
#\\\\\\\\ local modules //#
#// functions \\\\\\\\#
#? play the exit sound and then quit
def exit():
voice.play("exit", True)
quit()
#? get the name of the distribution from /etc/os-release
def get_os():
with open('/etc/os-release', 'r') as f:
for key in f.read().splitlines():
if key[:4] == 'NAME':
os = key.split('=')[1]
return os
#? generate a prompt header, containing useful information for the completion
# engine to know
def get_header():
return data.header.format(operating_system=get_os())
#? add punctuation to requests based on whether it's a question or instruction
def punctuate(statement):
if statement.split()[0] in data.questions:
statement += '?'
else:
statement += '.'
return statement
#? calibrate for ambient noise level
def calibrate(m, r):
with m as source:
print("calibrating for ambient noise...")
r.adjust_for_ambient_noise(source)
return r.energy_threshold
#? use speech recognition or keyboard input to get a request from the user
def listen(m, r, use_keyboard):
if use_keyboard:
voice.play("listening")
request = input(colors.cyan + "enter request: " + colors.bright_yellow)
print(colors.reset)
return request
else:
#? listen
with m as source:
voice.play("listening")
print(colors.cyan + "listening: " + colors.reset, end='')
stdout.flush()
audio = r.listen(source)
#? attempt to return request
try:
recognized = r.recognize_google(audio)
request = punctuate(recognized)
print(colors.bright_yellow + request + colors.reset + '\n')
return request
#? didn't understand audio
except sr.UnknownValueError:
print('\n\n' + errors.recognize + '\n')
voice.play('error', block=True)
#? unable to contact api
except sr.RequestError as e:
print('\n\n' + errors.request + e)
voice.play('error', block=True)
#? prompt the user to confirm, then execute a shell command
def run_command(m, r, cmd, use_keyboard):
if use_keyboard:
voice.play('confirm')
confirmation = input(colors.cyan + "confirm (y/N): " + colors.magenta)
print(colors.reset, end='')
if confirmation.lower() in ['y', 'yes']:
print(colors.blue + cursor.line_start + "//// running" + colors.magenta, cmd + colors.reset)
call(["bash", "-c", cmd])
print(colors.blue + r"\\\\ finished")
else:
print()
else:
with m as source:
voice.play('confirm')
print(colors.cyan + "confirm:" + colors.magenta, cmd, end='')
stdout.flush()
audio = r.listen(source)
#? attempt to confirm and run command
try:
recognized = r.recognize_google(audio)
if recognized in data.confirmations:
print(colors.blue + cursor.line_start + "//// running" + colors.magenta, cmd + colors.reset)
call(["bash", "-c", cmd])
print(colors.blue + r"\\\\ finished")
else:
print()
#? didn't understand audio
except sr.UnknownValueError:
print('\n\n' + errors.recognize + '\n')
voice.play('error', block=True)
#? unable to contact api
except sr.RequestError as e:
print('\n\n' + errors.request + e)
voice.play('error', block=True)
return False
print()
return True
#? check whether the user has requested to exit
def should_exit(request):
if request in data.exit_requests: return True
elif request + '.' in data.exit_requests: return True
else: return False
#? request a completion of the given prompt
def complete(m, r, request, prompt, use_keyboard):
#? request completion
response = openai.Completion.create(engine=config.complete.engine,
prompt=prompt,
max_tokens=config.complete.max_tokens,
temperature=config.complete.temperature,
top_p=config.complete.top_p)
#? parse and clean up reply
reply = response.choices[0].text.rstrip().replace('\n\n', '\n')
#? engine didn't understand the prompt, request clarification from the user
if 'ERROR' in reply or reply == '':
print(errors.clarity + '\n')
voice.play('error', block=True)
#? check if reply is a shell command to be executed
elif reply.lstrip()[:2] == '$ ':
cmd = reply.lstrip()[2:].split('\n')[0]
run_command(m, r, cmd, use_keyboard)
return '$ ' + cmd
elif reply.lstrip()[:4] in ['CODE', '```\n']:
code = '\n```\n' + reply.lstrip()[5:] + '\n```\n'
print(colors.reset + request + colors.cyan + code)
return code
#? print reply from the engine
else:
print(colors.reset + request + colors.magenta + reply + '\n')
tts(reply)
return reply
#? speak the given reply using gTTS
def tts(reply):
tts = gTTS(reply)
tts.save('/tmp/sapphire_tts.mp3')
call(['mpv', '--speed=1.25', '/tmp/sapphire_tts.mp3'], stdout=PIPE, stderr=PIPE)
#\\\\\\\\ functions //#