| 1 |
"""Wake word detection""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import contextlib |
| 5 |
import logging |
| 6 |
from asyncio.subprocess import Process |
| 7 |
from dataclasses import dataclass |
| 8 |
from typing import Any, Dict, List, Optional |
| 9 |
|
| 10 |
from .audio import AudioChunk, AudioChunkConverter |
| 11 |
from .client import AsyncClient |
| 12 |
from .event import Event, Eventable |
| 13 |
|
| 14 |
_LOGGER = logging.getLogger(__name__) |
| 15 |
|
| 16 |
DOMAIN = "wake" |
| 17 |
_DETECTION_TYPE = "detection" |
| 18 |
_DETECT_TYPE = "detect" |
| 19 |
_NOT_DETECTED_TYPE = "not-detected" |
| 20 |
|
| 21 |
|
| 22 |
@dataclass |
| 23 |
class Detection(Eventable): |
| 24 |
"""Wake word was detected.""" |
| 25 |
|
| 26 |
name: Optional[str] = None |
| 27 |
"""Name of model.""" |
| 28 |
|
| 29 |
timestamp: Optional[int] = None |
| 30 |
"""Timestamp of audio chunk with detection""" |
| 31 |
|
| 32 |
speaker: Optional[str] = None |
| 33 |
"""Name of speaker.""" |
| 34 |
|
| 35 |
context: Optional[Dict[str, Any]] = None |
| 36 |
"""Context for next interaction.""" |
| 37 |
|
| 38 |
@staticmethod |
| 39 |
def is_type(event_type: str) -> bool: |
| 40 |
return event_type == _DETECTION_TYPE |
| 41 |
|
| 42 |
def event(self) -> Event: |
| 43 |
data: Dict[str, Any] = { |
| 44 |
"name": self.name, |
| 45 |
"timestamp": self.timestamp, |
| 46 |
"speaker": self.speaker, |
| 47 |
} |
| 48 |
if self.context is not None: |
| 49 |
data["context"] = self.context |
| 50 |
|
| 51 |
return Event(type=_DETECTION_TYPE, data=data) |
| 52 |
|
| 53 |
@staticmethod |
| 54 |
def from_event(event: Event) -> "Detection": |
| 55 |
data = event.data or {} |
| 56 |
return Detection( |
| 57 |
name=data.get("name"), |
| 58 |
timestamp=data.get("timestamp"), |
| 59 |
speaker=data.get("speaker"), |
| 60 |
context=data.get("context"), |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
@dataclass |
| 65 |
class Detect(Eventable): |
| 66 |
"""Wake word detection request. |
| 67 |
|
| 68 |
Followed by AudioStart, AudioChunk+, AudioStop |
| 69 |
""" |
| 70 |
|
| 71 |
names: Optional[List[str]] = None |
| 72 |
"""Names of models to detect (None = any).""" |
| 73 |
|
| 74 |
context: Optional[Dict[str, Any]] = None |
| 75 |
"""Context for next interaction.""" |
| 76 |
|
| 77 |
@staticmethod |
| 78 |
def is_type(event_type: str) -> bool: |
| 79 |
return event_type == _DETECT_TYPE |
| 80 |
|
| 81 |
def event(self) -> Event: |
| 82 |
data: Dict[str, Any] = {"names": self.names} |
| 83 |
if self.context is not None: |
| 84 |
data["context"] = self.context |
| 85 |
|
| 86 |
return Event(type=_DETECT_TYPE, data=data) |
| 87 |
|
| 88 |
@staticmethod |
| 89 |
def from_event(event: Event) -> "Detect": |
| 90 |
data = event.data or {} |
| 91 |
return Detect(names=data.get("names"), context=data.get("context")) |
| 92 |
|
| 93 |
|
| 94 |
@dataclass |
| 95 |
class NotDetected(Eventable): |
| 96 |
"""Audio stream ended before wake word was detected.""" |
| 97 |
|
| 98 |
context: Optional[Dict[str, Any]] = None |
| 99 |
"""Context for next interaction.""" |
| 100 |
|
| 101 |
@staticmethod |
| 102 |
def is_type(event_type: str) -> bool: |
| 103 |
return event_type == _NOT_DETECTED_TYPE |
| 104 |
|
| 105 |
def event(self) -> Event: |
| 106 |
data: Dict[str, Any] = {} |
| 107 |
if self.context is not None: |
| 108 |
data["context"] = self.context |
| 109 |
|
| 110 |
return Event(type=_NOT_DETECTED_TYPE, data=data) |
| 111 |
|
| 112 |
@staticmethod |
| 113 |
def from_event(event: Event) -> "NotDetected": |
| 114 |
if not event.data: |
| 115 |
return NotDetected() |
| 116 |
|
| 117 |
return NotDetected(context=event.data.get("context")) |
| 118 |
|
| 119 |
|
| 120 |
class WakeProcessAsyncClient(AsyncClient, contextlib.AbstractAsyncContextManager): |
| 121 |
"""Context manager for doing wake word detection with an external program.""" |
| 122 |
|
| 123 |
def __init__( |
| 124 |
self, |
| 125 |
rate: int, |
| 126 |
width: int, |
| 127 |
channels: int, |
| 128 |
program: str, |
| 129 |
program_args: List[str], |
| 130 |
) -> None: |
| 131 |
super().__init__() |
| 132 |
|
| 133 |
self.rate = rate |
| 134 |
self.width = width |
| 135 |
self.channels = channels |
| 136 |
self.program = program |
| 137 |
self.program_args = program_args |
| 138 |
|
| 139 |
self._proc: Optional[Process] = None |
| 140 |
self._chunk_converter = AudioChunkConverter(rate, width, channels) |
| 141 |
|
| 142 |
async def connect(self) -> None: |
| 143 |
self._proc = await asyncio.create_subprocess_exec( |
| 144 |
self.program, |
| 145 |
*self.program_args, |
| 146 |
stdin=asyncio.subprocess.PIPE, |
| 147 |
stdout=asyncio.subprocess.PIPE, |
| 148 |
) |
| 149 |
|
| 150 |
async def disconnect(self) -> None: |
| 151 |
assert self._proc is not None |
| 152 |
assert self._proc.stdin is not None |
| 153 |
|
| 154 |
try: |
| 155 |
if self._proc.returncode is None: |
| 156 |
# Terminate process gracefully |
| 157 |
self._proc.stdin.close() |
| 158 |
await self._proc.wait() |
| 159 |
except ProcessLookupError: |
| 160 |
# Expected when process has already exited |
| 161 |
pass |
| 162 |
except Exception: |
| 163 |
_LOGGER.exception("Unexpected error stopping process: %s", self.program) |
| 164 |
finally: |
| 165 |
self._proc = None |
| 166 |
|
| 167 |
async def __aenter__(self) -> "WakeProcessAsyncClient": |
| 168 |
await self.connect() |
| 169 |
return self |
| 170 |
|
| 171 |
async def __aexit__(self, exc_type, exc, tb): |
| 172 |
await self.disconnect() |
| 173 |
|
| 174 |
async def read_event(self) -> Optional[Event]: |
| 175 |
assert self._proc is not None |
| 176 |
assert self._proc.stdout is not None |
| 177 |
|
| 178 |
line = (await self._proc.stdout.readline()).decode("utf-8").strip() |
| 179 |
name = line if line else None |
| 180 |
return Detection(name=name).event() |
| 181 |
|
| 182 |
async def write_event(self, event: Event) -> None: |
| 183 |
assert self._proc is not None |
| 184 |
assert self._proc.stdin is not None |
| 185 |
|
| 186 |
if not AudioChunk.is_type(event.type): |
| 187 |
return |
| 188 |
|
| 189 |
chunk = AudioChunk.from_event(event) |
| 190 |
|
| 191 |
# Convert sample rate/width/channels if necessary |
| 192 |
chunk = self._chunk_converter.convert(chunk) |
| 193 |
|
| 194 |
self._proc.stdin.write(chunk.audio) |
| 195 |
await self._proc.stdin.drain() |