Files
dckc f50c871521
check / check (push) Waiting to run
feat: mute the TV while the box listens, if the brain turns that on
whisper hears people better without the show behind them. The brain
sets a mute code (and an unmute code, if not the same) with
mute_while_listening on its ir capability, or turns it off; ir-server
keeps the setting in its state directory.

Mute is often a toggle, and the camera can't reliably tell whether the
sound is off, so the box senses nothing: the setting is the brain's
to turn on or off.

The button service holds a connection to ir-server's conversation
socket for each conversation: ir-server mutes when it opens and
unmutes, with the same codes, when it closes. The socket's group is
the button's alone, and the button still can't send any code.

Generated-by: Claude Opus 5.5
2026-12-03 16:49:58 -06:00

128 lines
5.9 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), the volume (mixer.py), muting the TV while it listens (muting.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 mixer import Mixer
from muting import Muting
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,
open_unix_connection, start_unix_server, sleep, monotonic, now):
"""box.py APLAY AMIXER ARECORD ESPEAK HEAR_CLIENT SPEAK_CLIENT SPEECH_URL ASK_CLIENT ASK_URL MUTE_SOCKET 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.
MUTE_SOCKET is the ir service's conversation socket, held open for each conversation (muting.py).
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, amixer, arecord, espeak, hear_client, speak_client, speech_url, ask_client, ask_url,
mute_socket, 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)
mixer = Mixer(command(amixer, "-c", "voicehat"))
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)
muting = Muting(partial(open_unix_connection, mute_socket))
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")
async with muting.during():
await converse(convo, partial(mics.listen, button=button), hear.transcribe, brain.ask,
voice.speak, speaker.play, mixer.louder, 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, open_unix_connection=asyncio.open_unix_connection,
start_unix_server=asyncio.start_unix_server,
sleep=asyncio.sleep, monotonic=time.monotonic, now=datetime.now,
))
raise SystemExit(_script_io())