-
Notifications
You must be signed in to change notification settings - Fork 0
/
launch.py
284 lines (233 loc) · 8.3 KB
/
launch.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
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
import os
import time
import json
import openai
import keyboard
from modules.Apis import TGWapi, TTSapi
from scipy.io.wavfile import write
from modules.Gui import Gui
from PySide6.QtWidgets import QApplication
import sys
import re
import numpy as np
speechresponderpath = os.path.join(os.getenv("APPDATA"), "EDDI", "speechresponder.out")
linescontent = []
lineslength = 0
def init_whisper():
import whisper
global whisper_model
whisper_model = whisper.load_model("base")
def load_config():
global config
with open("config.json", "r") as f:
config = json.load(f)
# load prompts
with open(config["prompts"]["ask"]["alpaca"], "r") as f:
config["prompts"]["ask"]["alpaca"] = f.read()
with open(config["prompts"]["rephrase"]["alpaca"], "r") as f:
config["prompts"]["rephrase"]["alpaca"] = f.read()
with open(config["prompts"]["rephrase2"]["alpaca"], "r") as f:
config["prompts"]["rephrase2"]["alpaca"] = f.read()
with open(config["prompts"]["ask"]["vicuna"], "r") as f:
config["prompts"]["ask"]["vicuna"] = f.read()
with open(config["prompts"]["rephrase"]["vicuna"], "r") as f:
config["prompts"]["rephrase"]["vicuna"] = f.read()
with open(config["prompts"]["rephrase2"]["vicuna"], "r") as f:
config["prompts"]["rephrase2"]["vicuna"] = f.read()
with open(config["prompts"]["ask"]["openai"], "r") as f:
config["prompts"]["ask"]["openai"] = f.read()
with open(config["prompts"]["rephrase"]["openai"], "r") as f:
config["prompts"]["rephrase"]["openai"] = f.read()
def load_messages():
global messages
with open("data/messages.json", "r") as f:
messages = json.load(f)
def ask_text_OpenAI(text):
system_prompt = config["prompts"]["ask"]["openai"]
start = time.time()
print("OpenAI API time: ", end="", flush=True)
last_messages = messages[-30:]
last_messages = list(
map(
lambda message: {"role": message["role"], "content": message["text"]},
last_messages,
)
)
composed_prompt = (
[{"role": "system", "content": system_prompt}]
+ last_messages
+ [{"role": "user", "content": text}]
)
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=composed_prompt
)
print(str(round(time.time() - start, 2)) + "s")
return response.choices[0].message.content
def rephrase_text_OpenAI(text):
system_prompt = config["prompts"]["rephrase"]["openai"]
start = time.time()
print("OpenAI API time: ", end="", flush=True)
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": text},
],
)
except:
print("OpenAI API error, using original text")
return text
print(str(round(time.time() - start, 2)) + "s")
return response.choices[0].message.content
def init_openai_api():
openai.api_key = config["openai_api_key"]
def logText(text, role="assistant"):
message = {
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime()),
"role": role,
"text": text.strip(),
}
messages.append(message)
with open("data/messages.json", "w") as f:
json.dump(messages, f, indent=4)
def audioLength(audio, sr):
# calculates the length of an audio in milliseconds
return int(len(audio) / sr * 1000)
def audiosLength(audios, sr):
# calculates the length of a list of audios in milliseconds
return sum([audioLength(audio, sr) for audio in audios])
def playQueue(audios, sr):
# concatenate every audio in one audio
audio = audios[0]
for i in range(1, len(audios)):
audio = np.concatenate((audio, audios[i]))
# play the audio
ttsapi.just_play(audio, sr)
def checkPunctuation(text):
if text[-1] not in [".", "!", "?"]:
text += "."
return text
def splitAndPlaySentences(text, debug=False):
# splitting text into sentences
texts = re.split(r"([.!?]) ", text)
# putting back the punctuation
texts = ["".join(texts[i : i + 2]) for i in range(0, len(texts), 2)]
if len(texts) > 1:
audios = []
sr = 0
for txt in texts:
txt = txt.strip()
txt = checkPunctuation(txt)
if len(txt) > 0:
audio, sr = ttsapi.generate(txt, play=False, debug=debug)
audios.append(audio)
if config["gui"]:
gui.display_message(text, audiosLength(audios, sr) + 2000)
print("Speaking: " + text)
playQueue(audios, sr)
if config["gui"]:
gui.wait()
else:
audio, sr = ttsapi.generate(text, play=False, debug=debug)
if config["gui"]:
gui.display_message(text, audioLength(audio, sr) + 2000)
print("Speaking: " + text)
ttsapi.just_play(audio, sr)
if config["gui"]:
gui.wait()
def playSentences(text, debug=False):
# we don't split the text, just create the audio and play it
audio, sr = ttsapi.generate(text, play=False, debug=debug)
if config["gui"]:
gui.display_message(text, audioLength(audio, sr) + 2000)
print("Speaking: " + text)
ttsapi.just_play(audio, sr)
if config["gui"]:
gui.wait()
# loop of the checker and speaker
def checkForChangesAndSpeak():
global lineslength
try:
with open(speechresponderpath, "r") as f:
lines = f.readlines()
if len(lines) > lineslength:
print("New line detected")
except:
print("Could not read file")
return
if lineslength == 0:
lineslength = len(lines) - 1
if (len(lines) > 0) and lineslength != len(lines):
i = lineslength
while i < len(lines):
start = time.time()
text = lines[i]
# get last 3 lines from the current line
logs = lines[i - 3 : i]
# strip the lines
logs = [log.strip() for log in logs]
#text = TGWapi(config).rephrase2(eddi_message=lines[i], logs=logs, debug=True, max_new_tokens=150)
text = TGWapi(config).rephrase(text, debug=True, max_new_tokens=150)
logText(text, role="assistant")
splitAndPlaySentences(text, debug=True)
print("Total time: " + str(round(time.time() - start, 2)) + "s")
i += 1
lineslength = len(lines)
def checkForKeypress():
if keyboard.is_pressed("ctrl+*"):
question = input("Question: ")
answer = TGWapi(config).ask(
question, context_messages=messages[-30:], max_new_tokens=400, debug=True
)
logText(question, role="user")
logText(answer, role="assistant")
playSentences(answer, debug=True)
if config["whisper"]["use"]:
if keyboard.is_pressed("ctrl+y"):
ttsapi.generate("Yes, Commander?", play=True, debug=True)
audio = ttsapi.record()
write("tmp/recorded.wav", 44100, audio)
print("Transcribing...")
result = whisper_model.transcribe("tmp/recorded.wav", language="english")
question = result["text"].strip()
print("Recorded text: " + question)
answer = TGWapi(config).ask(
question,
context_messages=messages[-30:],
max_new_tokens=400,
debug=True,
)
logText(question, role="user")
logText(answer, role="assistant")
playSentences(answer, debug=True)
def init_gui():
global app
global gui
app = QApplication(sys.argv)
gui = Gui()
gui.show()
def main():
load_config()
load_messages()
if config["whisper"]["use"]:
init_whisper()
init_openai_api()
global ttsapi
ttsapi = TTSapi(config)
if config["gui"]:
init_gui()
print("test")
while True:
checkForChangesAndSpeak()
checkForKeypress()
if config["gui"]:
# when gui is used, we will use the gui loop for waiting
gui.sleep(250)
else:
time.sleep(0.25)
# this is only needed if we don't use the loop
if config["gui"]:
sys.exit(app.exec_())
if __name__ == "__main__":
main()