This repository has been archived by the owner on Aug 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 101
/
app.py
executable file
·1350 lines (1001 loc) · 39.8 KB
/
app.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
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
"""Rhasspy web application server."""
import argparse
import asyncio
import atexit
import concurrent.futures
import json
import logging
import os
import re
import shutil
import time
from functools import wraps
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from uuid import uuid4
import attr
import json5
from quart import (
Quart,
Response,
jsonify,
request,
safe_join,
send_file,
send_from_directory,
websocket,
)
from quart_cors import cors
from swagger_ui import quart_api_doc
from rhasspy.actor import ActorSystem, ConfigureEvent, RhasspyActor
from rhasspy.core import RhasspyCore
from rhasspy.events import (
IntentRecognized,
ProfileTrainingFailed,
VoiceCommand,
WakeWordDetected,
WavTranscription,
)
from rhasspy.utils import (
FunctionLoggingHandler,
buffer_to_wav,
get_all_intents,
get_ini_paths,
get_wav_duration,
load_phoneme_examples,
read_dict,
recursive_remove,
)
# -----------------------------------------------------------------------------
# Quart Web App Setup
# -----------------------------------------------------------------------------
logger = logging.getLogger(__name__)
loop = asyncio.get_event_loop()
app = Quart("rhasspy")
app.secret_key = str(uuid4())
app = cors(app)
# WAV data from last voice command
last_voice_wav: Optional[bytes] = None
# -----------------------------------------------------------------------------
# Parse Arguments
# -----------------------------------------------------------------------------
parser = argparse.ArgumentParser("Rhasspy")
parser.add_argument(
"--profile", "-p", required=True, type=str, help="Name of profile to load"
)
parser.add_argument("--host", type=str, help="Host for web server", default="0.0.0.0")
parser.add_argument("--port", type=int, help="Port for web server", default=12101)
parser.add_argument(
"--system-profiles",
type=str,
help="Directory with base profile files (read only)",
default=os.path.join(os.getcwd(), "profiles"),
)
parser.add_argument(
"--user-profiles",
type=str,
help="Directory with user profile files (read/write)",
default=os.path.expanduser("~/.config/rhasspy/profiles"),
)
parser.add_argument(
"--set",
"-s",
nargs=2,
action="append",
help="Set a profile setting value",
default=[],
)
parser.add_argument(
"--ssl", nargs=2, help="Use SSL with <CERT_FILE <KEY_FILE>", default=None
)
parser.add_argument("--log-level", default="DEBUG", help="Set logging level")
args = parser.parse_args()
# Set log level
if "RHASSPY_LOG_LEVEL" in os.environ:
log_level = os.environ["RHASSPY_LOG_LEVEL"]
else:
log_level = args.log_level
logging.basicConfig(level=getattr(logging, log_level.upper()))
logger.debug(args)
system_profiles_dir = os.path.abspath(args.system_profiles)
user_profiles_dir = os.path.abspath(args.user_profiles)
profiles_dirs = [user_profiles_dir, system_profiles_dir]
# -----------------------------------------------------------------------------
# Dialogue Manager Setup
# -----------------------------------------------------------------------------
core = None
# We really, *really* want shutdown to be called
@atexit.register
def shutdown(*_args: Any, **kwargs: Any) -> None:
"""Ensure Rhasspy core is stopped."""
global core
if core is not None:
loop.run_until_complete(loop.create_task(core.shutdown()))
core = None
async def start_rhasspy() -> None:
"""Create actor system and Rhasspy core."""
global core
# Load core
system = ActorSystem()
core = RhasspyCore(
args.profile, system_profiles_dir, user_profiles_dir, actor_system=system
)
# Set environment variables
os.environ["RHASSPY_BASE_DIR"] = os.getcwd()
os.environ["RHASSPY_PROFILE"] = core.profile.name
os.environ["RHASSPY_PROFILE_DIR"] = core.profile.write_dir()
# Add profile settings from the command line
extra_settings = {}
for key, value in args.set:
try:
value = json.loads(value)
except Exception:
pass
logger.debug("Profile: %s=%s", key, value)
extra_settings[key] = value
core.profile.set(key, value)
# Load observer actor to catch intents
observer = system.createActor(WebSocketObserver)
system.ask(observer, ConfigureEvent(core.profile))
await core.start(observer=observer)
logger.info("Started")
# -----------------------------------------------------------------------------
# HTTP API
# -----------------------------------------------------------------------------
@app.route("/api/version")
async def api_version() -> Response:
"""Get Rhasspy version."""
return await send_file(Path("VERSION"))
# -----------------------------------------------------------------------------
@app.route("/api/profiles")
async def api_profiles() -> Response:
"""Get list of available profiles and verify necessary files."""
assert core is not None
profile_names = set()
for profiles_dir in profiles_dirs:
if not os.path.exists(profiles_dir):
continue
for name in os.listdir(profiles_dir):
profile_dir = os.path.join(profiles_dir, name)
if os.path.isdir(profile_dir):
profile_names.add(name)
missing_files = core.check_profile()
downloaded = len(missing_files) == 0
return jsonify(
{
"default_profile": core.profile.name,
"profiles": sorted(profile_names),
"downloaded": downloaded,
"missing_files": missing_files,
}
)
# -----------------------------------------------------------------------------
@app.route("/api/download-profile", methods=["POST"])
async def api_download_profile() -> str:
"""Downloads the current profile."""
assert core is not None
delete = request.args.get("delete", "false").lower() == "true"
await core.download_profile(delete=delete)
return "OK"
@app.route("/api/download-status", methods=["GET"])
async def api_download_status() -> str:
"""Get status of profile download"""
assert core is not None
return "\n".join(core.download_status)
# -----------------------------------------------------------------------------
@app.route("/api/problems", methods=["GET"])
async def api_problems() -> Response:
"""Returns any problems Rhasspy has found."""
assert core is not None
return jsonify(await core.get_problems())
# -----------------------------------------------------------------------------
@app.route("/api/microphones", methods=["GET"])
async def api_microphones() -> Response:
"""Get a dictionary of available recording devices"""
assert core is not None
system = request.args.get("system", None)
return jsonify(await core.get_microphones(system))
# -----------------------------------------------------------------------------
@app.route("/api/test-microphones", methods=["GET"])
async def api_test_microphones() -> Response:
"""Get a dictionary of available, functioning recording devices"""
assert core is not None
system = request.args.get("system", None)
return jsonify(await core.test_microphones(system))
# -----------------------------------------------------------------------------
@app.route("/api/speakers", methods=["GET"])
async def api_speakers() -> Response:
"""Get a dictionary of available playback devices"""
assert core is not None
system = request.args.get("system", None)
return jsonify(await core.get_speakers(system))
# -----------------------------------------------------------------------------
@app.route("/api/listen-for-wake", methods=["POST"])
async def api_listen_for_wake() -> str:
"""Make Rhasspy listen for a wake word"""
assert core is not None
enabled_str = (await request.data).decode().strip().lower()
enabled = enabled_str not in ["false", "off"]
core.listen_for_wake(enabled)
return str(enabled)
# -----------------------------------------------------------------------------
@app.route("/api/listen-for-command", methods=["POST"])
async def api_listen_for_command() -> Response:
"""Wake Rhasspy up and listen for a voice command"""
assert core is not None
no_hass = request.args.get("nohass", "false").lower() == "true"
# Seconds before timing out
timeout = request.args.get("timeout")
if timeout is not None:
timeout = float(timeout)
# Key/value to set in recognized intent
entity = request.args.get("entity")
value = request.args.get("value")
# Emulate wake
wake_json = json.dumps({"wakewordId": "default", "siteId": core.siteId})
await add_ws_event("wake", wake_json)
return jsonify(
await core.listen_for_command(
handle=(not no_hass), timeout=timeout, entity=entity, value=value
)
)
# -----------------------------------------------------------------------------
@app.route("/api/profile", methods=["GET", "POST"])
async def api_profile() -> Union[str, Response]:
"""Read or write profile JSON directly"""
assert core is not None
layers = request.args.get("layers", "all")
if request.method == "POST":
# Ensure that JSON is valid
profile_json = json5.loads(await request.data)
recursive_remove(core.profile.system_json, profile_json)
profile_path = Path(core.profile.write_path("profile.json"))
with open(profile_path, "w") as profile_file:
json.dump(profile_json, profile_file, indent=4)
msg = f"Wrote profile to {profile_path}"
logger.debug(msg)
return msg
if layers == "defaults":
# Read default settings
return jsonify(core.defaults)
if layers == "profile":
# Local settings only
profile_path = Path(core.profile.read_path("profile.json"))
return await send_file(profile_path)
return jsonify(core.profile.json)
# -----------------------------------------------------------------------------
@app.route("/api/lookup", methods=["POST"])
async def api_lookup() -> Response:
"""Get CMU phonemes from dictionary or guessed pronunciation(s)"""
assert core is not None
n = int(request.args.get("n", 5))
assert n > 0, "No pronunciations requested"
data = await request.data
word = data.decode().strip().lower()
assert word, "No word to look up"
result = await core.get_word_pronunciations([word], n)
pronunciations = result.pronunciations
return jsonify(pronunciations[word])
# -----------------------------------------------------------------------------
@app.route("/api/pronounce", methods=["POST"])
async def api_pronounce() -> Union[Response, str]:
"""Pronounce CMU phonemes or word using eSpeak"""
assert core is not None
download = request.args.get("download", "false").lower() == "true"
data = await request.data
pronounce_str = data.decode().strip()
assert pronounce_str, "No string to pronounce"
# phonemes or word
pronounce_type = request.args.get("type", "phonemes")
if pronounce_type == "phonemes":
# Convert from Sphinx to espeak phonemes
phoneme_result = await core.get_word_phonemes(pronounce_str)
espeak_str = phoneme_result.phonemes
else:
# Speak word directly
espeak_str = pronounce_str
speak_result = await core.speak_word(espeak_str)
wav_data = speak_result.wav_data
espeak_phonemes = speak_result.phonemes
if download:
# Return WAV
return Response(wav_data, mimetype="audio/wav")
# Play through speakers
core.play_wav_data(wav_data)
return espeak_phonemes
# -----------------------------------------------------------------------------
@app.route("/api/play-wav", methods=["POST"])
async def api_play_wav() -> str:
"""Play WAV data through the configured audio output system"""
assert core is not None
if request.content_type == "audio/wav":
wav_data = await request.data
else:
# Interpret as URL
data = await request.data
url = data.decode()
logger.debug("Loading WAV data from %s", url)
async with core.session.get(url) as response:
wav_data = await response.read()
# Play through speakers
logger.debug("Playing %s byte(s)", len(wav_data))
core.play_wav_data(wav_data)
return "OK"
# -----------------------------------------------------------------------------
@app.route("/api/phonemes")
def api_phonemes():
"""Get phonemes and example words for a profile"""
assert core is not None
speech_system = core.profile.get("speech_to_text.system", "pocketsphinx")
examples_path = Path(
core.profile.read_path(
core.profile.get(
f"speech_to_text.{speech_system}.phoneme_examples",
"phoneme_examples.txt",
)
)
)
# phoneme -> { word, phonemes }
logger.debug("Loading phoneme examples from %s", examples_path)
examples_dict = load_phoneme_examples(examples_path)
return jsonify(examples_dict)
# -----------------------------------------------------------------------------
@app.route("/api/sentences", methods=["GET", "POST"])
async def api_sentences():
"""Read or write sentences for a profile"""
assert core is not None
if request.method == "POST":
# POST
if request.mimetype == "application/json":
# Update multiple ini files at once. Paths as keys (relative to
# profile directory), sentences as values.
num_chars = 0
paths_written = []
sentences_dict = json5.loads(await request.data)
for sentences_path, sentences_text in sentences_dict.items():
# Path is relative to profile directory
sentences_path = Path(core.profile.write_path(sentences_path))
if sentences_text.strip():
# Overwrite file
logger.debug("Writing %s", sentences_path)
sentences_path.parent.mkdir(parents=True, exist_ok=True)
sentences_path.write_text(sentences_text)
num_chars += len(sentences_text)
paths_written.append(sentences_path)
elif sentences_path.is_file():
# Remove file
logger.debug("Removing %s", sentences_path)
sentences_path.unlink()
return f"Wrote {num_chars} char(s) to {[str(p) for p in paths_written]}"
# Update sentences.ini only
sentences_path = Path(
core.profile.write_path(core.profile.get("speech_to_text.sentences_ini"))
)
data = await request.data
with open(sentences_path, "wb") as sentences_file:
sentences_file.write(data)
return f"Wrote {len(data)} byte(s) to {sentences_path}"
# GET
sentences_path_rel = core.profile.read_path(
core.profile.get("speech_to_text.sentences_ini")
)
sentences_path = Path(sentences_path_rel)
if prefers_json():
# Return multiple .ini files, keyed by path relative to profile
# directory.
sentences_dict = {}
if sentences_path.is_file():
try:
# Try user profile dir first
profile_dir = Path(core.profile.user_profiles_dir) / core.profile.name
key = str(sentences_path.relative_to(profile_dir))
except Exception:
# Fall back to system profile dir
profile_dir = Path(core.profile.system_profiles_dir) / core.profile.name
key = str(sentences_path.relative_to(profile_dir))
sentences_dict[key] = sentences_path.read_text()
ini_dir = Path(
core.profile.read_path(core.profile.get("speech_to_text.sentences_dir"))
)
# Add all .ini files from sentences_dir
if ini_dir.is_dir():
for ini_path in ini_dir.glob("*.ini"):
key = str(ini_path.relative_to(core.profile.read_path()))
sentences_dict[key] = ini_path.read_text()
return jsonify(sentences_dict)
# Return sentences.ini contents only
if not sentences_path.is_file():
return "" # no sentences yet
# Return file contents
return await send_file(sentences_path)
# -----------------------------------------------------------------------------
@app.route("/api/custom-words", methods=["GET", "POST"])
async def api_custom_words():
"""Read or write custom word dictionary for a profile"""
assert core is not None
speech_system = core.profile.get("speech_to_text.system", "pocketsphinx")
# Temporary fix for kaldi/custom_words -> kaldi_custom_words.txt
old_kaldi_words_path = Path(core.profile.read_path("kaldi/custom_words.txt"))
if old_kaldi_words_path.is_file():
new_kaldi_words_path = Path(
core.profile.write_path(
core.profile.get(
"speech_to_text.kaldi.custom_words", "custom_words.txt"
)
)
)
if (
new_kaldi_words_path != old_kaldi_words_path
and not new_kaldi_words_path.is_file()
):
logger.warning(
"Moving %s to %s", str(old_kaldi_words_path), str(new_kaldi_words_path)
)
shutil.move(old_kaldi_words_path, new_kaldi_words_path)
if request.method == "POST":
custom_words_path = Path(
core.profile.write_path(
core.profile.get(
f"speech_to_text.{speech_system}.custom_words", "custom_words.txt"
)
)
)
# Update custom words
lines_written = 0
with open(custom_words_path, "w") as custom_words_file:
data = await request.data
lines = data.decode().splitlines()
for line in lines:
line = line.strip()
if not line:
continue
print(line, file=custom_words_file)
lines_written += 1
return f"Wrote {lines_written} line(s) to {custom_words_path}"
custom_words_path = Path(
core.profile.read_path(
core.profile.get(
f"speech_to_text.{speech_system}.custom_words", "custom_words.txt"
)
)
)
# Return custom_words
if prefers_json():
if not custom_words_path.is_file():
return jsonify({}) # no custom_words yet
with open(custom_words_path, "r") as words_file:
return jsonify(read_dict(words_file))
else:
if not custom_words_path.is_file():
return "" # no custom_words yet
# Return file contents
return await send_file(custom_words_path)
# -----------------------------------------------------------------------------
@app.route("/api/train", methods=["POST"])
async def api_train() -> str:
"""Generate speech/intent artifacts for profile."""
no_cache = request.args.get("nocache", "false").lower() == "true"
assert core is not None
start_time = time.time()
logger.info("Starting training")
result = await core.train(no_cache=no_cache)
if isinstance(result, ProfileTrainingFailed):
raise Exception(f"Training failed: {result.reason}")
end_time = time.time()
return "Training completed in %0.2f second(s)" % (end_time - start_time)
# -----------------------------------------------------------------------------
@app.route("/api/restart", methods=["POST"])
async def api_restart() -> str:
"""Restart Rhasspy actors."""
assert core is not None
logger.debug("Restarting Rhasspy")
# Stop
await core.shutdown()
# Start
await start_rhasspy()
logger.info("Restarted Rhasspy")
return "Restarted Rhasspy"
# -----------------------------------------------------------------------------
@app.route("/api/speech-to-text", methods=["POST"])
async def api_speech_to_text() -> str:
"""Transcribe speech from WAV file."""
global last_voice_wav
no_header = request.args.get("noheader", "false").lower() == "true"
assert core is not None
# Prefer 16-bit 16Khz mono, but will convert with sox if needed
wav_data = await request.data
if no_header:
# Wrap in WAV
wav_data = buffer_to_wav(wav_data)
last_voice_wav = wav_data
start_time = time.perf_counter()
result = await core.transcribe_wav(wav_data)
end_time = time.perf_counter()
# Send to websocket
await add_ws_event(
"transcription",
json.dumps(
{"text": result.text, "wakewordId": "default", "siteId": core.siteId}
),
)
if prefers_json():
return jsonify(
{
"text": result.text,
"likelihood": result.confidence,
"transcribe_seconds": (end_time - start_time),
"wav_seconds": get_wav_duration(wav_data),
}
)
return result.text
# -----------------------------------------------------------------------------
@app.route("/api/text-to-intent", methods=["POST"])
async def api_text_to_intent():
"""Recgonize intent from text and optionally handle."""
assert core is not None
data = await request.data
text = data.decode()
no_hass = request.args.get("nohass", "false").lower() == "true"
# Convert text to intent
start_time = time.time()
intent = (await core.recognize_intent(text)).intent
intent["speech_confidence"] = 1
intent_sec = time.time() - start_time
intent["time_sec"] = intent_sec
intent_json = json.dumps(intent)
logger.debug(intent_json)
await add_ws_event("intent", intent_json)
if not no_hass:
# Send intent to Home Assistant
intent = (await core.handle_intent(intent)).intent
return jsonify(intent)
# -----------------------------------------------------------------------------
@app.route("/api/speech-to-intent", methods=["POST"])
async def api_speech_to_intent() -> Response:
"""Transcribe speech, recognize intent, and optionally handle."""
global last_voice_wav
assert core is not None
no_hass = request.args.get("nohass", "false").lower() == "true"
# Prefer 16-bit 16Khz mono, but will convert with sox if needed
wav_data = await request.data
last_voice_wav = wav_data
# speech -> text
start_time = time.time()
transcription = await core.transcribe_wav(wav_data)
text = transcription.text
logger.debug(text)
# Send to websocket
await add_ws_event(
"transcription",
json.dumps({"text": text, "wakewordId": "default", "siteId": core.siteId}),
)
# text -> intent
intent = (await core.recognize_intent(text)).intent
intent["speech_confidence"] = transcription.confidence
intent_sec = time.time() - start_time
intent["time_sec"] = intent_sec
intent_json = json.dumps(intent)
logger.debug(intent_json)
await add_ws_event("intent", intent_json)
if not no_hass:
# Send intent to Home Assistant
intent = (await core.handle_intent(intent)).intent
return jsonify(intent)
# -----------------------------------------------------------------------------
@app.route("/api/start-recording", methods=["POST"])
async def api_start_recording() -> str:
"""Begin recording voice command."""
assert core is not None
buffer_name = request.args.get("name", "")
core.start_recording_wav(buffer_name)
return "OK"
@app.route("/api/stop-recording", methods=["POST"])
async def api_stop_recording() -> Response:
"""End recording voice command. Transcribe and handle."""
global last_voice_wav
assert core is not None
no_hass = request.args.get("nohass", "false").lower() == "true"
buffer_name = request.args.get("name", "")
audio_data = (await core.stop_recording_wav(buffer_name)).data
wav_data = buffer_to_wav(audio_data)
logger.debug("Recorded %s byte(s) of audio data", len(wav_data))
transcription = await core.transcribe_wav(wav_data)
text = transcription.text
logger.debug(text)
# Send to websocket
await add_ws_event(
"transcription",
json.dumps({"text": text, "wakewordId": "default", "siteId": core.siteId}),
)
intent = (await core.recognize_intent(text)).intent
intent["speech_confidence"] = transcription.confidence
intent_json = json.dumps(intent)
logger.debug(intent_json)
await add_ws_event("intent", intent_json)
if not no_hass:
# Send intent to Home Assistant
intent = (await core.handle_intent(intent)).intent
# Save last voice command WAV data
last_voice_wav = wav_data
return jsonify(intent)
@app.route("/api/play-recording", methods=["POST"])
async def api_play_recording() -> str:
"""Play last recorded voice command through the configured audio output system"""
global last_voice_wav
assert core is not None
if last_voice_wav:
# Play through speakers
logger.debug("Playing %s byte(s)", len(last_voice_wav))
core.play_wav_data(last_voice_wav)
return "OK"
# -----------------------------------------------------------------------------
@app.route("/api/unknown-words", methods=["GET"])
async def api_unknown_words() -> Response:
"""Get list of unknown words."""
assert core is not None
speech_system = core.profile.get("speech_to_text.system", "pocketsphinx")
unknown_words = {}
unknown_path = Path(
core.profile.read_path(
core.profile.get(
f"speech_to_text.{speech_system}.unknown_words", "unknown_words.txt"
)
)
)
if unknown_path.is_file():
for line in open(unknown_path, "r"):
line = line.strip()
if line:
word, pronunciation = re.split(r"[ ]+", line, maxsplit=1)
unknown_words[word] = pronunciation
return jsonify(unknown_words)
# -----------------------------------------------------------------------------
last_sentence = ""
@app.route("/api/text-to-speech", methods=["POST"])
async def api_text_to_speech() -> Union[bytes, str]:
"""Speak a sentence with text to speech system."""
global last_sentence
repeat = request.args.get("repeat", "false").strip().lower() == "true"
play = request.args.get("play", "true").strip().lower() == "true"
language = request.args.get("language")
voice = request.args.get("voice")
siteId = request.args.get("siteId")
data = await request.data
sentence = last_sentence if repeat else data.decode().strip()
assert core is not None
result = await core.speak_sentence(
sentence, play=play, language=language, voice=voice, siteId=siteId
)
last_sentence = sentence
if not play:
# Return WAV data instead of speaking
return Response(result.wav_data, mimetype="audio/wav")
return sentence
# -----------------------------------------------------------------------------
@app.route("/api/slots", methods=["GET", "POST"])
async def api_slots() -> Union[str, Response]:
"""Get the values of all slots."""
assert core is not None
if request.method == "POST":
overwrite_all = request.args.get("overwrite_all", "false").lower() == "true"
new_slot_values = json5.loads(await request.data)
slots_dir = Path(
core.profile.write_path(
core.profile.get("speech_to_text.slots_dir", "slots")
)
)
if overwrite_all:
# Remote existing values first
for name in new_slot_values:
slots_path = safe_join(slots_dir, f"{name}")
if slots_path.is_file():
try:
slots_path.unlink()
except Exception:
logger.exception("api_slots")
for name, values in new_slot_values.items():
if isinstance(values, str):
values = [values]
slots_path = slots_dir / name
# Create directories
slots_path.parent.mkdir(parents=True, exist_ok=True)
# Merge with existing values
values = {v.strip() for v in values}
if slots_path.is_file():
values.update(
line.strip() for line in slots_path.read_text().splitlines()
)
# Write merged values
if values:
with open(slots_path, "w") as slots_file:
for value in values:
if value:
print(value, file=slots_file)
return "OK"
# Read slots into dictionary
slots_dir = Path(
core.profile.read_path(core.profile.get("speech_to_text.slots_dir", "slots"))
)
slots_dict = {}
if slots_dir.is_dir():
for slot_file_path in slots_dir.glob("*"):
if slot_file_path.is_file():
slot_name = slot_file_path.name
slots_dict[slot_name] = [
line.strip() for line in slot_file_path.read_text().splitlines()
]
return jsonify(slots_dict)
@app.route("/api/slots/<name>", methods=["GET", "POST"])
def api_slots_by_name(name: str) -> Union[str, Response]:
"""Get or set the values of a slot list."""
assert core is not None
overwrite_all = request.args.get("overwrite_all", "false").lower() == "true"
slots_dir = Path(
core.profile.read_path(core.profile.get("speech_to_text.slots_dir", "slots"))
)
if request.method == "POST":
if overwrite_all:
# Remote existing values first
slots_path = safe_join(slots_dir, f"{name}")
if slots_path.is_file():
try:
slots_path.unlink()
except Exception:
logger.exception("api_slots_by_name")
slots_path = Path(
core.profile.write_path(