forked from janvarev/Irene-Voice-Assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runva_webapi.py
261 lines (208 loc) · 7.99 KB
/
runva_webapi.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
# ----------
from fastapi import FastAPI, HTTPException
import uvicorn
from multiprocessing import Process
from termcolor import cprint
import json
from starlette.websockets import WebSocket
#from pydantic import BaseModel
from vacore import VACore
import time
# ------------------- main loop ------------------
webapi_options = None
core = None
model = None # vosk model
#rec = None # vosk recognizer
# --------------- loading options ----------
# move options from old file
import os
if not os.path.exists('runva_webapi.json'):
if os.path.exists('options/webapi.json'):
os.rename('options/webapi.json','runva_webapi.json')
# loading options
from jaa import load_options
default_options={
"host": "127.0.0.1",
"port": 5003,
"log_level": "info",
"use_ssl": False
}
webapi_options = load_options(py_file=__file__,default_options=default_options)
use_ssl = webapi_options["use_ssl"]
# try:
# with open('options/webapi.json', 'r', encoding="utf-8") as f:
# s = f.read(1000000)
# f.close()
# webapi_options = json.loads(s)
# use_ssl = webapi_options["use_ssl"]
# except Exception as e:
# core = VACore()
# core.init_with_plugins()
# core.init_plugin("webapi")
# cprint("Настройки созданы; пожалуйста, перезапустите этот файл", "red")
# exit(-1)
"""
returnFormat Варианты:
- "none" (TTS реакции будут на сервере) (звук на сервере)
- "saytxt" (сервер вернет текст, TTS будет на клиенте) (звук на клиенте)
- "saywav" (TTS на сервере, сервер отрендерит WAV и вернет клиенту, клиент его проиграет) (звук на клиенте) **наиболее универсальный для клиента**
"""
def runCmd(cmd:str,returnFormat:str):
if core.logPolicy == "cmd" or core.logPolicy == "all":
print("Running cmd: ",cmd)
tmpformat = core.remoteTTS
core.remoteTTS = returnFormat
core.remoteTTSResult = ""
core.lastSay = ""
core.execute_next(cmd,core.context)
core.remoteTTS = tmpformat
app = FastAPI()
is_running = True
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles
app.mount("/webapi_client", StaticFiles(directory="webapi_client", html = True), name="webapi_client")
app.mount("/mic_client", StaticFiles(directory="mic_client", html = True), name="mic_client")
@app.websocket("/wsmic")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
from vosk import KaldiRecognizer
rec = KaldiRecognizer(model, 48000)
print("New WebSocket microphone recognition")
while True:
data = await websocket.receive_bytes()
r = process_chunk(rec,data)
await websocket.send_text(r)
def process_chunk(rec,message):
# with open('temp/asr_server_test.wav', 'wb') as the_file:
# the_file.write(message)
if message == '{"eof" : 1}':
return rec.FinalResult()
elif rec.AcceptWaveform(message):
res2 = "{}"
res = rec.Result()
#print("Result:",res)
resj = json.loads(res)
if "text" in resj:
voice_input_str = resj["text"]
#print(restext)
import requests
if voice_input_str != "" and voice_input_str != None:
print(voice_input_str)
#ttsFormatList = ["saytxt"]
res2 = sendRawTxtOrig(voice_input_str,"none,saytxt")
# saywav not supported due to bytes serialization???
if res2 != "NO_VA_NAME":
res2 = json.dumps(res2)
else:
res2 = "{}"
else:
#print("2",rec.PartialResult())
pass
return res2
else:
res = rec.PartialResult()
#print("Part Result:",res)
return rec.PartialResult()
@app.on_event("startup")
async def startup_event():
global core
core = VACore()
core.init_with_plugins()
print("WEB api for VoiceAssistantCore (remote control)")
url = ""
if webapi_options["use_ssl"]:
url = "https://{0}:{1}/".format("localhost",webapi_options["port"])
else:
url = "http://{0}:{1}/".format("localhost",webapi_options["port"])
print("Web client URL (VOSK in browser): ", url+"webapi_client/")
print("Mic client URL (experimental, sends WAV bytes to server): ", url+"mic_client/")
from vosk import Model, SpkModel, KaldiRecognizer
global model
model = Model("model")
# рендерит текст в wav
@app.get("/ttsWav")
async def ttsWav(text:str):
#runCmd(cmd,returnFormat)
tmpformat = core.remoteTTS
core.remoteTTS = "saywav"
core.play_voice_assistant_speech(text)
core.remoteTTS = tmpformat
return core.remoteTTSResult
# выполняет команду Ирины
# Например: привет, погода.
@app.get("/sendTxtCmd")
async def sendSimpleTxtCmd(cmd:str,returnFormat:str = "none"):
runCmd(cmd,returnFormat)
return core.remoteTTSResult
# Посылает распознанный текстовый ввод. Если в нем есть имя помощника, выполняется команда.
# Пример: ирина погода, раз два
@app.get("/sendRawTxt")
async def sendRawTxt(rawtxt:str,returnFormat:str = "none"):
return sendRawTxtOrig(rawtxt,returnFormat)
def sendRawTxtOrig(rawtxt:str,returnFormat:str = "none"):
tmpformat = core.remoteTTS
core.remoteTTS = returnFormat
core.remoteTTSResult = ""
core.lastSay = ""
isFound = core.run_input_str(rawtxt)
core.remoteTTS = tmpformat
if isFound:
return core.remoteTTSResult
else:
return "NO_VA_NAME"
# Обновляет контекст на то же самое время
@app.get("/reinitContext")
async def reinitContext():
if core.contextTimer != None:
core.context_set(core.context,core.contextTimerLastDuration)
return ""
# Запускает внутреннюю процедуру проверки таймеров. Должна запускаться периодически
@app.get("/updTimers")
async def updTimers():
#core.say("аа")
#print("upd timers")
core._update_timers()
return ""
# Сообщает серверу, что клиент воспроизвёл ответ и можно начать отсчёт таймера контекста
@app.get("/replyWasGiven")
async def replyWasGiven():
if core.contextRemoteWaitForCall:
if core.contextTimer != None:
core.contextTimer.start()
#print("debug - run context after webapi call")
def core_update_timers_http(runReq=True):
time.sleep(5) # small sleep before start
while is_running:
try:
import requests
if webapi_options["use_ssl"]:
reqstr = "https://{0}:{1}/updTimers".format(webapi_options["host"],webapi_options["port"])
else:
reqstr = "http://{0}:{1}/updTimers".format(webapi_options["host"],webapi_options["port"])
#print(reqstr)
r = requests.get(reqstr,verify=False)
except Exception:
pass
try:
time.sleep(2)
except:
return
return
@app.on_event("shutdown")
def app_shutdown():
global is_running
cprint("Ctrl-C pressed, exiting Irene.", "yellow")
is_running = False
if __name__ == "__main__":
p = Process(target=core_update_timers_http, args=(False,))
p.start()
if webapi_options["use_ssl"]:
uvicorn.run("runva_webapi:app",
host=webapi_options["host"], port=webapi_options["port"],
ssl_keyfile="localhost.key",
ssl_certfile="localhost.crt",
log_level=webapi_options["log_level"])
else:
uvicorn.run("runva_webapi:app",
host=webapi_options["host"], port=webapi_options["port"],
log_level=webapi_options["log_level"])