-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhotword_client.py
More file actions
88 lines (61 loc) · 2.64 KB
/
Copy pathhotword_client.py
File metadata and controls
88 lines (61 loc) · 2.64 KB
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
import os
import sys
import json
import asyncio
import websockets
from tabulate import tabulate
import config
from hotword_types import MessageStatus, MessageType
from wav_player import play_file
script_path = os.path.abspath(__file__)
script_dir = os.path.dirname(script_path)
hotword_audio = None
if config.hotword_audio:
hotword_audio = os.path.join(script_dir, config.hotword_audio)
if not os.path.exists(hotword_audio):
print("hotword_audio is not accessible")
sys.exit(1)
silence_audio = None
if config.silence_audio:
silence_audio = os.path.join(script_dir, config.silence_audio)
if not os.path.exists(silence_audio):
print("silence_audio is not accessible")
sys.exit(1)
async def run_hotword_listener(transcription_queue: asyncio.Queue):
try:
print(f"[hotword_listener]: Starting...\n")
async with websockets.connect(config.hotword_url) as websocket:
await websocket.send(json.dumps(config.hotword_params))
while True:
try:
msg = await asyncio.wait_for(websocket.recv(), timeout=1.0)
data = json.loads(msg)
data_status = data.get("status")
data_type = data.get("type")
msg = data.get("text")
if data_status != MessageStatus.OK.value:
print(f"[hotword_listener]: {data}", flush=True)
continue
if data_type in (MessageType.HOST_INFO.value, MessageType.DEV_INPUT.value):
json_obj = json.loads(msg)
print_dict_tabular(json_obj, data_type)
continue
print(f"[hotword_listener]: {data}")
if hotword_audio and data_type == MessageType.HOTWORD.value:
await play_file(hotword_audio)
if silence_audio and data_type == MessageType.SILENCE.value:
await play_file(silence_audio)
await transcription_queue.put(data)
except asyncio.TimeoutError:
continue # Check stop_event again
except websockets.exceptions.ConnectionClosed:
print("[hotword_listener] WebSocket closed.")
break
except asyncio.CancelledError:
print("[hotword_listener] Cancelled.")
except Exception as e:
print(f"[hotword_listener] Unexpected error: {e}")
def print_dict_tabular(d, title):
print(f"=== {title} ===")
print(tabulate(d.items(), headers=["Key", "Value"], tablefmt="grid"))
print("")