feat: the brain can change the box's speaker volume
"Speak up" and "too loud" now work: the reply tool takes louder, in percentage points, and the button service nudges the speaker's softvol before it speaks that reply, so the person hears the change at once. The box keeps the level between 10% and 80% (body/mixer.py). No new port or key: the volume changes only with a reply, in a conversation someone is listening to. Generated-by: Claude Opus 5.5
This commit is contained in:
1 parent
cf503ac247
commit
5191ee9931
11 files changed
+146
-21
No files matched your search
+3
-1
@@ -3,6 +3,7 @@
|
||||
* @file ask-client: the box's side of a conversation with the brain, through its ask capability.
|
||||
* usage: ask-client.js URL CONVERSATION < question.txt
|
||||
* prints JSON lines: {"say": "..."} for each thing the brain says meanwhile,
|
||||
* then, if the brain changed the volume, {"louder": N} (percentage points; negative is softer),
|
||||
* then {"reply": "...", "end": false}; end is true when the brain ends the conversation.
|
||||
* usage: ask-client.js URL CONVERSATION end
|
||||
* tells the brain the conversation is over.
|
||||
@@ -45,7 +46,8 @@ const main = async ({
|
||||
}
|
||||
const question = (await text(stdin)).trim();
|
||||
// Cap'n Web passes the function by reference: the brain calls it back over this session.
|
||||
const { text: reply, end } = await asker.ask(question, conversation, (/** @type {string} */ said) => { line({ say: said }); });
|
||||
const { text: reply, end, louder } = await asker.ask(question, conversation, (/** @type {string} */ said) => { line({ say: said }); });
|
||||
if (louder) line({ louder });
|
||||
line({ reply, end });
|
||||
} finally {
|
||||
gate[Symbol.dispose]();
|
||||
|
||||
+6
-4
@@ -13,7 +13,7 @@ While the brain looks through the camera (../look.js), the box taps and flashes
|
||||
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.
|
||||
(voice.py), the volume (mixer.py), hear and brain (brain.py), status (status.py), and the look signal.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
@@ -27,6 +27,7 @@ from gpio import HatLines
|
||||
from hearing import ARECORD_ARGS, Mics
|
||||
from light import Light
|
||||
from look_signal import LookSignal
|
||||
from mixer import Mixer
|
||||
from status import Status, ignore, poster
|
||||
from voice import Speaker, Voice
|
||||
|
||||
@@ -46,14 +47,14 @@ def activated_socket(environ, getpid, socket):
|
||||
|
||||
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]
|
||||
"""box.py APLAY AMIXER 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,
|
||||
(aplay, amixer, 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()
|
||||
@@ -63,6 +64,7 @@ async def main(argv, environ, getpid, cwd, request_lines, socket, create_subproc
|
||||
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)
|
||||
@@ -88,7 +90,7 @@ async def main(argv, environ, getpid, cwd, request_lines, socket, create_subproc
|
||||
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,
|
||||
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:
|
||||
|
||||
+5
-1
@@ -25,17 +25,21 @@ def answer(line):
|
||||
|
||||
>>> answer(b'{"say": "Let me try."}')
|
||||
('say', 'Let me try.')
|
||||
>>> answer(b'{"louder": -10}')
|
||||
('louder', -10)
|
||||
>>> answer(b'{"reply": "Bye!", "end": true}')
|
||||
('reply', 'Bye!', True)
|
||||
"""
|
||||
event = json.loads(line)
|
||||
if "say" in event:
|
||||
return ("say", event["say"])
|
||||
if "louder" in event:
|
||||
return ("louder", int(event["louder"]))
|
||||
return ("reply", event["reply"], bool(event.get("end")))
|
||||
|
||||
|
||||
class Brain:
|
||||
"""ask(text, convo) yields ("say", text)s, then ("reply", text, end); or ("press",).
|
||||
"""ask(text, convo) yields ("say", text)s, perhaps ("louder", points), then ("reply", text, end); or ("press",).
|
||||
end(convo) tells the brain the conversation is over.
|
||||
|
||||
ask_client is a Command for ask-client, bound to the brain's ask capability.
|
||||
|
||||
+35
-4
@@ -1,17 +1,18 @@
|
||||
"""One conversation with the box, from the press that opened it to goodbye.
|
||||
|
||||
Everything it touches comes in as a function: listen, transcribe, ask, speak, play, the LED.
|
||||
Everything it touches comes in as a function: listen, transcribe, ask, speak, play, the volume, the LED.
|
||||
"""
|
||||
from contextlib import aclosing
|
||||
|
||||
|
||||
async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, end, log,
|
||||
async def converse(convo, listen, transcribe, ask, speak, play, louder, led, thinking, end, log,
|
||||
note=lambda kind, **data: None):
|
||||
"""One conversation, from the press that opened it to goodbye.
|
||||
|
||||
Async: listen(skip_s) returns ("speech", clip), ("quiet", None), or ("press", None).
|
||||
play(name) starts an earcon and returns its length, which listen skips.
|
||||
ask(text, convo) yields ("say", text), then ("reply", text, end); or ("press",).
|
||||
ask(text, convo) yields ("say", text), perhaps ("louder", points), then ("reply", text, end); or ("press",).
|
||||
louder(points) changes the speaker volume, before the reply is spoken, and returns the new level.
|
||||
speak(text) returns False if a press interrupted it. end(convo) tells the brain.
|
||||
Not async: led(on), thinking(on), log(msg), and
|
||||
note(kind, ...) counts it for a status page: turn, huh, interrupt, end.
|
||||
@@ -25,6 +26,9 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
||||
... if text == "Switch to the PC.":
|
||||
... yield ("say", "Let me try.")
|
||||
... yield ("reply", "Done.", False)
|
||||
... elif text == "Speak up!":
|
||||
... yield ("louder", 10)
|
||||
... yield ("reply", "Is this better?", False)
|
||||
... elif text == "Thanks!":
|
||||
... yield ("reply", "You're welcome. Bye!", True)
|
||||
... else:
|
||||
@@ -33,7 +37,8 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
||||
>>> async def speak(text): return print("speak", text) or True
|
||||
>>> async def play(name): return print("play", name) or 0.4
|
||||
>>> async def end(convo): print("end", convo)
|
||||
>>> ops = dict(transcribe=transcribe, ask=ask, speak=speak, play=play, end=end, log=print,
|
||||
>>> async def louder(points): return 45 + points
|
||||
>>> ops = dict(transcribe=transcribe, ask=ask, speak=speak, play=play, louder=louder, end=end, log=print,
|
||||
... led=lambda on: print("led", on), thinking=lambda on: print("thinking", on))
|
||||
>>> run = lambda convo, listen, **kw: asyncio.run(converse(convo, listen, **kw))
|
||||
>>> run("k1", script(("speech", "Switch to the PC."), ("speech", "Thanks!")), **ops)
|
||||
@@ -62,6 +67,26 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
||||
play bye
|
||||
end k1
|
||||
|
||||
The brain can turn the volume up or down; the box does so before it speaks the reply:
|
||||
|
||||
>>> run("k4", script(("speech", "Speak up!"), ("press", None)), **ops)
|
||||
play open
|
||||
led True
|
||||
led False
|
||||
play gotit
|
||||
thinking True
|
||||
k4 heard: Speak up!
|
||||
k4: volume 55%
|
||||
thinking False
|
||||
speak Is this better?
|
||||
thinking False
|
||||
play turn
|
||||
led True
|
||||
led False
|
||||
k4: press; goodbye
|
||||
play bye
|
||||
end k4
|
||||
|
||||
A press while the agent thinks interrupts it; silence ends the conversation:
|
||||
|
||||
>>> run("k2", script(("speech", "Tell me a long story."), ("quiet", None)), **ops)
|
||||
@@ -143,6 +168,12 @@ async def converse(convo, listen, transcribe, ask, speak, play, led, thinking, e
|
||||
try:
|
||||
async with aclosing(ask(text, convo)) as events: # a break closes it now, not someday
|
||||
async for event in events:
|
||||
if event[0] == "louder":
|
||||
try:
|
||||
log(f"{convo}: volume {await louder(event[1])}%")
|
||||
except Exception as err:
|
||||
log(f"{convo}: volume change failed: {err}")
|
||||
continue
|
||||
thinking(False)
|
||||
if event[0] == "press" or not await speak(event[1]):
|
||||
interrupted = True
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""The box's speaker volume: the softvol named speaker (../voicehat.nix), which the brain may nudge.
|
||||
|
||||
The brain asks for louder or softer, in percentage points, with a reply; the box keeps the level
|
||||
within its own bounds, so no reply can make it silent or painfully loud.
|
||||
"""
|
||||
import re
|
||||
|
||||
LOWEST, HIGHEST = 10, 80 # percent; full volume is too loud for a living room
|
||||
|
||||
|
||||
def percent(amixer_out):
|
||||
"""The level amixer sget reports, in percent.
|
||||
|
||||
>>> percent(b"Simple mixer control 'speaker',0\\n Front Left: 115 [45%]\\n Front Right: 115 [45%]\\n")
|
||||
45
|
||||
"""
|
||||
found = re.search(rb"\[(\d+)%\]", amixer_out)
|
||||
if not found:
|
||||
raise IOError(f"no level in amixer's output: {amixer_out[:200]!r}")
|
||||
return int(found.group(1))
|
||||
|
||||
|
||||
def nudge(level, louder, lowest=LOWEST, highest=HIGHEST):
|
||||
"""level, louder by so many points, within bounds.
|
||||
|
||||
>>> nudge(45, 10), nudge(45, -10), nudge(75, 30), nudge(15, -30)
|
||||
(55, 35, 80, 10)
|
||||
"""
|
||||
return max(lowest, min(highest, level + louder))
|
||||
|
||||
|
||||
class Mixer:
|
||||
"""louder(points) changes the speaker's level and returns the new one, in percent.
|
||||
|
||||
amixer is a Command for amixer on the box's sound card (amixer -c voicehat).
|
||||
|
||||
>>> import asyncio
|
||||
>>> class Amixer:
|
||||
... level = 45
|
||||
... async def run(self, *args):
|
||||
... print(args)
|
||||
... if args[-1].endswith("%"): self.level = int(args[-1][:-1])
|
||||
... return f" Front Left: 0 [{self.level}%]".encode()
|
||||
>>> asyncio.run(Mixer(Amixer()).louder(50))
|
||||
('sget', 'speaker')
|
||||
('-q', 'sset', 'speaker', '80%')
|
||||
80
|
||||
"""
|
||||
|
||||
def __init__(self, amixer):
|
||||
self.__amixer = amixer
|
||||
|
||||
async def louder(self, points):
|
||||
level = nudge(percent(await self.__amixer.run("sget", "speaker")), int(points))
|
||||
await self.__amixer.run("-q", "sset", "speaker", f"{level}%")
|
||||
return level
|
||||
+1
-1
@@ -114,7 +114,7 @@ in
|
||||
# -E -s, not -I: box.py imports its siblings in body/, from the store.
|
||||
ExecStart = lib.escapeShellArgs [
|
||||
"${pkgs.python3.withPackages (ps: [ ps.libgpiod ])}/bin/python3" "-E" "-s" "${./body}/box.py"
|
||||
"${pkgs.alsa-utils}/bin/aplay" "${pkgs.alsa-utils}/bin/arecord" "${pkgs.espeak-ng}/bin/espeak-ng"
|
||||
"${pkgs.alsa-utils}/bin/aplay" "${pkgs.alsa-utils}/bin/amixer" "${pkgs.alsa-utils}/bin/arecord" "${pkgs.espeak-ng}/bin/espeak-ng"
|
||||
(script "hear-client" "${speechJs}/hear-client.js") (script "speak-client" "${speechJs}/speak-client.js")
|
||||
cfg.speechUrl
|
||||
(script "ask-client" "${boxJs}/ask-client.js") cfg.askUrl
|
||||
|
||||
+2
-1
@@ -61,7 +61,8 @@
|
||||
}];
|
||||
|
||||
# The amp has no volume control of its own, so a softvol named speaker goes in front of it; everything
|
||||
# plays through it. make volume VOL=30% sets the level; persistence keeps it across reboots.
|
||||
# plays through it. make volume VOL=30% sets the level, and the brain can nudge it (body/mixer.py);
|
||||
# persistence keeps it across reboots.
|
||||
hardware.alsa = {
|
||||
enable = true;
|
||||
enablePersistence = true;
|
||||
|
||||
+11
-4
@@ -10,11 +10,14 @@ import { RpcTarget } from 'capnweb';
|
||||
/** Spoken questions are short. */
|
||||
export const MAX_QUESTION_CHARS = 2000;
|
||||
|
||||
/** The most a reply can change the box's speaker volume, in percentage points; the box keeps its own bounds. */
|
||||
export const MAX_LOUDER = 30;
|
||||
|
||||
/** A conversation id: the box makes them up, so keep them tame. */
|
||||
const CONVERSATION = /^[A-Za-z0-9-]{1,40}$/;
|
||||
|
||||
/**
|
||||
* @typedef {{ text: string, end: boolean }} Answer
|
||||
* @typedef {{ text: string, end: boolean, louder?: number }} Answer
|
||||
* @typedef {{ conversation?: string, onSay?: (text: string) => unknown }} AskOpts
|
||||
* @typedef {{ resolve: (a: Answer) => void, reject: (e: Error) => void, onSay?: AskOpts['onSay'] }} Pending
|
||||
*/
|
||||
@@ -74,13 +77,17 @@ export class Channel {
|
||||
/**
|
||||
* The brain's reply tool. Returns what to tell the brain.
|
||||
* @param {string} chat_id @param {string} text @param {boolean} [end] the conversation is over
|
||||
* @param {number} [louder] change the speaker volume this many percentage points first; negative is softer
|
||||
*/
|
||||
reply(chat_id, text, end = false) {
|
||||
reply(chat_id, text, end = false, louder = undefined) {
|
||||
const p = this.#pending.get(chat_id);
|
||||
if (!p) return `no one is waiting on chat_id ${chat_id}: it timed out or was already answered`;
|
||||
const volumeOk = louder === undefined || (Number.isInteger(louder) && Math.abs(louder) <= MAX_LOUDER);
|
||||
this.#pending.delete(chat_id);
|
||||
p.resolve({ text: String(text), end: end === true });
|
||||
return end === true ? 'spoken; the conversation is over' : 'spoken';
|
||||
p.resolve({ text: String(text), end: end === true, ...(volumeOk && louder ? { louder } : {}) });
|
||||
const outcome = end === true ? 'spoken; the conversation is over' : 'spoken';
|
||||
if (!volumeOk) return `${outcome}, but the volume is unchanged: louder must be a whole number from -${MAX_LOUDER} to ${MAX_LOUDER}`;
|
||||
return louder ? `${outcome}, ${louder > 0 ? 'louder' : 'softer'} by ${Math.abs(louder)} points (within the box's bounds)` : outcome;
|
||||
}
|
||||
|
||||
/** The box says a conversation is over: by goodbye, silence, or a press. @param {string} conversation @param {string} user */
|
||||
|
||||
+17
-1
@@ -1,7 +1,7 @@
|
||||
// Tests for the ask capability's core: no MCP, no network, no real timers.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Channel, Asker, MAX_QUESTION_CHARS } from './ask.js';
|
||||
import { Channel, Asker, MAX_LOUDER, MAX_QUESTION_CHARS } from './ask.js';
|
||||
|
||||
const harness = () => {
|
||||
const sent = [], timers = [];
|
||||
@@ -52,6 +52,22 @@ test('the box ends a conversation; the brain hears it, with no question to answe
|
||||
assert.throws(() => channel.end('k 7; rm', 'box'), /conversation/);
|
||||
});
|
||||
|
||||
test('a reply can turn the volume up or down; out of range, it speaks but leaves the volume', async () => {
|
||||
const { channel } = harness();
|
||||
const up = channel.ask('Speak up!', 'box');
|
||||
assert.match(channel.reply('c1', 'Is this better?', false, 10), /louder by 10/);
|
||||
assert.deepEqual(await up, { text: 'Is this better?', end: false, louder: 10 });
|
||||
const down = channel.ask('Too loud.', 'box');
|
||||
assert.match(channel.reply('c2', 'Sorry.', false, -5), /softer by 5/);
|
||||
assert.deepEqual(await down, { text: 'Sorry.', end: false, louder: -5 });
|
||||
const way = channel.ask('Way up!', 'box');
|
||||
assert.match(channel.reply('c3', 'Okay.', false, MAX_LOUDER + 1), /volume is unchanged/);
|
||||
assert.deepEqual(await way, { text: 'Okay.', end: false });
|
||||
const odd = channel.ask('Louder?', 'box');
|
||||
assert.match(channel.reply('c4', 'Hm.', false, 'max'), /volume is unchanged/);
|
||||
assert.deepEqual(await odd, { text: 'Hm.', end: false });
|
||||
});
|
||||
|
||||
test('replies go to the right question; a stale chat_id is reported, not thrown', async () => {
|
||||
const { channel } = harness();
|
||||
const a = channel.ask('one', 'box');
|
||||
|
||||
+9
-4
@@ -21,7 +21,7 @@ import { networkInterfaces } from 'node:os';
|
||||
import process from 'node:process';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { Asker, Channel } from './ask.js';
|
||||
import { Asker, Channel, MAX_LOUDER } from './ask.js';
|
||||
import { Gate } from './gate.js';
|
||||
import { makeGitHubPost, makeReporter } from './report.js';
|
||||
|
||||
@@ -36,10 +36,15 @@ const INSTRUCTIONS = [
|
||||
|
||||
const REPLY_TOOL = {
|
||||
name: 'reply',
|
||||
description: 'Speak your answer through the box; then it is their turn. Pass chat_id from the inbound <channel> tag. end_conversation true says goodbye and closes the conversation.',
|
||||
description: 'Speak your answer through the box; then it is their turn. Pass chat_id from the inbound <channel> tag. end_conversation true says goodbye and closes the conversation. louder changes the box\'s speaker volume, in percentage points, before it speaks this answer, so they hear the difference: 10 for "speak up", -10 for "too loud", more if they ask for a lot. The box keeps the volume within its own bounds.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { chat_id: { type: 'string' }, text: { type: 'string' }, end_conversation: { type: 'boolean' } },
|
||||
properties: {
|
||||
chat_id: { type: 'string' },
|
||||
text: { type: 'string' },
|
||||
end_conversation: { type: 'boolean' },
|
||||
louder: { type: 'integer', minimum: -MAX_LOUDER, maximum: MAX_LOUDER },
|
||||
},
|
||||
required: ['chat_id', 'text'],
|
||||
},
|
||||
};
|
||||
@@ -241,7 +246,7 @@ const main = async ({
|
||||
}
|
||||
}
|
||||
if (name !== 'reply') return textResult(`no tool ${name}`, true);
|
||||
const outcome = channel.reply(String(args.chat_id), String(args.text ?? ''), args.end_conversation === true);
|
||||
const outcome = channel.reply(String(args.chat_id), String(args.text ?? ''), args.end_conversation === true, args.louder);
|
||||
log(`reply ${args.chat_id}: ${outcome}: ${args.text}`);
|
||||
return textResult(outcome);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ Your body is a small box with a button, near the TV. Through it you have:
|
||||
- They aren't technical: be warm, plain, and brief.
|
||||
- One to three short sentences.
|
||||
- No markdown, lists, URLs, or emoji: it's all read aloud.
|
||||
- If they can't hear you ("speak up", "what?") or you're too loud, change your own volume with louder on your reply: 10 points up or down, more if they ask for a lot. That's the box's speaker, not the TV's; "turn it up" while the TV is on most likely means the TV.
|
||||
|
||||
## The remote
|
||||
|
||||
|
||||
Reference in new issue
Block a user