The box within reach of the couch: a Raspberry Pi 3B with the AIY Voice HAT, from the first household's configuration, made generic. - box/body: the button service, in Python: press and talk, turns by voice, a press interrupts; the look signal - box/*.js: the ir and look capabilities, behind gates, for the brain; the ask client, the box's side of a conversation - box/module.nix: the services, each confined to the devices and addresses it needs; the private network as an option (a tailnet by default); the Pico found by its USB IDs, as /dev/pdtv26-ir - box/voicehat.nix: the Voice HAT's device tree overlay and ALSA setup - lib.mkBox: a box's whole system from its name, the home server's, the Wi-Fi network's, and who looks after it - checks: box-js, box-py (doctests and pyflakes), and box-system (an example box's system evaluates) Generated-by: Claude Opus 5.5
120 lines
5.4 KiB
Python
120 lines
5.4 KiB
Python
"""The box's button service: press to start a conversation; take turns by talking; press to interrupt.
|
|
|
|
A press opens a conversation: the box chimes (open), the LED lights, and the mics listen until
|
|
the speaker has been quiet a while. The box chimes again (gotit) and the LED blinks while the
|
|
agent thinks: the speech capability transcribes the turn, and the brain answers it through the
|
|
ask capability, perhaps saying a few words first. The box speaks, chimes (turn), and listens
|
|
again. The conversation ends when the brain says goodbye, when no one speaks for a while, or
|
|
when someone presses the button while the box listens; the box chimes bye. A press while the
|
|
agent thinks or speaks interrupts it: it stops, and it's their turn.
|
|
|
|
While the brain looks through the camera (../look.js), the box taps and flashes (look_signal.py).
|
|
|
|
One event loop, no threads. Only _script_io() imports authority (the DisciplinedPython
|
|
recipe); main() narrows it into the parts, each of which gets only what it needs:
|
|
button and light (gpio.py, button.py, light.py), mics (hearing.py), speaker and voice
|
|
(voice.py), hear and brain (brain.py), status (status.py), and the look signal.
|
|
"""
|
|
import asyncio
|
|
import logging
|
|
from functools import partial
|
|
|
|
from brain import Brain, Hear
|
|
from button import Button
|
|
from command import Command
|
|
from converse import converse
|
|
from gpio import HatLines
|
|
from hearing import ARECORD_ARGS, Mics
|
|
from light import Light
|
|
from look_signal import LookSignal
|
|
from status import Status, ignore, poster
|
|
from voice import Speaker, Voice
|
|
|
|
|
|
def activated_socket(environ, getpid, socket):
|
|
"""The socket systemd passed, as fd 3 (socket activation), or None.
|
|
|
|
>>> activated_socket({"LISTEN_FDS": "1", "LISTEN_PID": "42"}, lambda: 42, lambda fileno: f"fd {fileno}")
|
|
'fd 3'
|
|
>>> activated_socket({}, lambda: 42, None) is None
|
|
True
|
|
"""
|
|
if environ.get("LISTEN_FDS") == "1" and environ.get("LISTEN_PID") == str(getpid()):
|
|
return socket(fileno=3)
|
|
return None
|
|
|
|
|
|
async def main(argv, environ, getpid, cwd, request_lines, socket, create_subprocess_exec, open_connection,
|
|
start_unix_server, sleep, monotonic, now):
|
|
"""box.py APLAY ARECORD ESPEAK HEAR_CLIENT SPEAK_CLIENT SPEECH_URL ASK_CLIENT ASK_URL EARCONS STATE_DIR [STATUS_URL]
|
|
|
|
HEAR_CLIENT SPEECH_URL < clip prints its transcript; SPEAK_CLIENT SPEECH_URL < text prints
|
|
a WAV of it; ASK_CLIENT ASK_URL CONVERSATION < text prints the brain's answer as JSON lines.
|
|
EARCONS is a directory of WAVs (voice.EARCONS); STATE_DIR keeps the latest clip.
|
|
STATUS_URL, if any, is a status page, told of each conversation and look, with a heartbeat.
|
|
"""
|
|
(aplay, arecord, espeak, hear_client, speak_client, speech_url, ask_client, ask_url,
|
|
earcons, state_dir, *status_url) = argv[1:]
|
|
command = partial(Command, create_subprocess_exec)
|
|
loop = asyncio.get_running_loop()
|
|
|
|
lines = HatLines(request_lines, "/dev/gpiochip0")
|
|
button = Button()
|
|
loop.add_reader(lines.fileno(), lambda: button.feed(lines.read_edges()))
|
|
light = Light(lines.set_led, monotonic, sleep)
|
|
speaker = Speaker(command(aplay, "-q", "-D", "speaker"), cwd / earcons)
|
|
mics = Mics(command(arecord, *ARECORD_ARGS), keep=(cwd / state_dir / "clip.wav").write_bytes)
|
|
hear = Hear(command(hear_client, speech_url))
|
|
voice = Voice(command(speak_client, speech_url), command(espeak, "--stdout"), speaker, button)
|
|
brain = Brain(command(ask_client, ask_url), button)
|
|
|
|
background = [asyncio.create_task(light.run())]
|
|
note = ignore
|
|
if status_url:
|
|
status = Status(poster(open_connection, status_url[0]), sleep)
|
|
background += [asyncio.create_task(job) for job in (status.run(), status.heartbeat())]
|
|
note = status.note
|
|
listener = activated_socket(environ, getpid, socket)
|
|
if listener:
|
|
await start_unix_server(LookSignal(light, speaker.play, note).handle, sock=listener)
|
|
else:
|
|
logging.info("no look socket from systemd: the brain can't look")
|
|
|
|
logging.info("ready: press to start a conversation")
|
|
note("ready")
|
|
while True:
|
|
await button.wait()
|
|
convo = now().strftime("%Y%m%d-%H%M%S")
|
|
logging.info(f"{convo}: a conversation starts")
|
|
note("conversation")
|
|
await converse(convo, partial(mics.listen, button=button), hear.transcribe, brain.ask,
|
|
voice.speak, speaker.play, light.mics, light.thinking, brain.end,
|
|
logging.info, note)
|
|
button.pressed() # presses during goodbye don't start another
|
|
for task in background:
|
|
if task.done():
|
|
raise RuntimeError(f"a background job stopped: {task.exception()!r}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
def _script_io():
|
|
import os
|
|
import socket
|
|
import sys
|
|
import time
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
import gpiod
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
|
|
return asyncio.run(main(
|
|
argv=list(sys.argv), environ=dict(os.environ), getpid=os.getpid, cwd=Path.cwd(),
|
|
request_lines=gpiod.request_lines, socket=socket.socket,
|
|
create_subprocess_exec=asyncio.create_subprocess_exec,
|
|
open_connection=asyncio.open_connection, start_unix_server=asyncio.start_unix_server,
|
|
sleep=asyncio.sleep, monotonic=time.monotonic, now=datetime.now,
|
|
))
|
|
|
|
raise SystemExit(_script_io())
|