"""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 volume, the LED. """ from contextlib import aclosing 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), 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. >>> import asyncio >>> def script(*turns): ... it = iter(turns) ... async def listen(skip): return next(it) ... return listen >>> async def ask(text, convo): ... 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: ... yield ("press",) >>> async def transcribe(clip): return clip >>> 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) >>> 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) play open led True led False play gotit thinking True k1 heard: Switch to the PC. thinking False speak Let me try. thinking True thinking False speak Done. thinking False play turn led True led False play gotit thinking True k1 heard: Thanks! thinking False speak You're welcome. Bye! thinking False k1: the brain said goodbye 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) play open led True led False play gotit thinking True k2 heard: Tell me a long story. thinking False thinking False k2: interrupted play turn led True led False k2: quiet; goodbye play bye end k2 Nothing heard, or a failure, gets the huh earcon and another turn; a press while the box listens says goodbye: >>> async def deaf_to_hello(clip): ... if clip == "hello": raise IOError("speech server unreachable") ... return clip >>> run("k3", script(("speech", "[BLANK_AUDIO]"), ("speech", "hello"), ("press", None)), ... **dict(ops, transcribe=deaf_to_hello)) play open led True led False play gotit thinking True thinking False play huh led True led False play gotit thinking True k3: transcribe failed: speech server unreachable thinking False play huh led True led False k3: press; goodbye play bye end k3 """ skip = await play("open") while True: led(True) kind, clip = None, None try: kind, clip = await listen(skip) except Exception as err: kind = None log(f"{convo}: listen failed: {err}") finally: led(False) if kind != "speech": if kind: log(f"{convo}: {kind}; goodbye") reason = kind or "listen failed" break await play("gotit") thinking(True) try: text = (await transcribe(clip)).strip() except Exception as err: log(f"{convo}: transcribe failed: {err}") text = "" if not text or text.startswith("["): # [BLANK_AUDIO] and the like thinking(False) note("huh") skip = await play("huh") continue log(f"{convo} heard: {text}") note("turn") ended = interrupted = failed = False 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 break if event[0] == "reply": ended = event[2] break thinking(True) except Exception as err: log(f"{convo}: ask failed: {err}") failed = True finally: thinking(False) if ended: log(f"{convo}: the brain said goodbye") reason = "goodbye" break if interrupted: log(f"{convo}: interrupted") note("interrupt") if failed: note("huh") skip = await play("huh" if failed else "turn") await play("bye") note("end", reason=reason) await end(convo)