| 1 |
"""HTTP server for wake word detection.""" |
| 2 |
|
| 3 |
import io |
| 4 |
import logging |
| 5 |
import wave |
| 6 |
from pathlib import Path |
| 7 |
from typing import Set |
| 8 |
|
| 9 |
from flask import Response, jsonify, request |
| 10 |
|
| 11 |
from wyoming.audio import wav_to_chunks |
| 12 |
from wyoming.client import AsyncClient |
| 13 |
from wyoming.error import Error |
| 14 |
from wyoming.wake import Detect, Detection, NotDetected |
| 15 |
|
| 16 |
from .shared import get_app, get_argument_parser |
| 17 |
|
| 18 |
_DIR = Path(__file__).parent |
| 19 |
CONF_PATH = _DIR / "conf" / "wake.yaml" |
| 20 |
|
| 21 |
|
| 22 |
def main(): |
| 23 |
parser = get_argument_parser() |
| 24 |
parser.add_argument("--wake-word-name", action="append") |
| 25 |
parser.add_argument("--samples-per-chunk", type=int, default=1024) |
| 26 |
args = parser.parse_args() |
| 27 |
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO) |
| 28 |
|
| 29 |
app = get_app("wake", CONF_PATH, args) |
| 30 |
|
| 31 |
@app.route("/api/detect-wake-word", methods=["POST", "GET"]) |
| 32 |
async def api_wake() -> Response: |
| 33 |
uri = request.args.get("uri", args.uri) |
| 34 |
if not uri: |
| 35 |
raise ValueError("URI is required") |
| 36 |
|
| 37 |
wake_word_names: Set[str] = set() |
| 38 |
|
| 39 |
async with AsyncClient.from_uri(uri) as client: |
| 40 |
if args.wake_word_name: |
| 41 |
# From command-line |
| 42 |
wake_word_names.update(args.wake_word_name) |
| 43 |
|
| 44 |
wake_word_names.update(request.args.getlist("wake_words")) |
| 45 |
|
| 46 |
if wake_word_names: |
| 47 |
await client.write_event(Detect(list(wake_word_names)).event()) |
| 48 |
|
| 49 |
with io.BytesIO(request.data) as wav_io: |
| 50 |
with wave.open(wav_io, "rb") as wav_file: |
| 51 |
chunks = wav_to_chunks( |
| 52 |
wav_file, |
| 53 |
samples_per_chunk=args.samples_per_chunk, |
| 54 |
start_event=True, |
| 55 |
stop_event=True, |
| 56 |
) |
| 57 |
for chunk in chunks: |
| 58 |
await client.write_event(chunk.event()) |
| 59 |
|
| 60 |
while True: |
| 61 |
event = await client.read_event() |
| 62 |
if event is None: |
| 63 |
raise RuntimeError("Client disconnected") |
| 64 |
|
| 65 |
if Detection.is_type(event.type) or NotDetected.is_type(event.type): |
| 66 |
return jsonify(event.to_dict()) |
| 67 |
|
| 68 |
if Error.is_type(event.type): |
| 69 |
error = Error.from_event(event) |
| 70 |
raise RuntimeError( |
| 71 |
f"Unexpected error from client: code={error.code}, text={error.text}" |
| 72 |
) |
| 73 |
|
| 74 |
app.run(args.host, args.port) |
| 75 |
|
| 76 |
|
| 77 |
if __name__ == "__main__": |
| 78 |
main() |