From b90201bf9f14e787a770d68b300639cd3160254e Mon Sep 17 00:00:00 2001 From: tesseractAZ <192581158+tesseractAZ@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:06:26 -0700 Subject: [PATCH 1/2] Release v0.129.0: a wake-up cancel survives the line's sound-alikes On a G.711 line "cancel" came back as "Campbell.", "Campful." and "Okay, I'm full.", so nothing matched and the wake-up being called off rang (2026-08-21, 2026-11-23). switchboard-stt's time mode now answers CANCEL-LIKE for a whole reply shaped like "cancel", and the wake-up AGI acts on it only when a wake-up is set. A don't/not/keep/leave anywhere stops any cancel; an echo of the prompt does nothing. A call that understood nothing while a wake-up was set reads it back as still set (WAKEUP_RESULT=kept). A lone "Oh."/"zero" no longer sets midnight. Each wake-up recording leaves a size-only breadcrumb. Co-Authored-By: Claude Opus 5.5 --- switchboard/CHANGELOG-ARCHIVE.md | 30 ++ switchboard/CHANGELOG.md | 61 ++- switchboard/Dockerfile | 2 +- switchboard/config.yaml | 2 +- .../docs/reference/wake-ups-and-clock.md | 12 + switchboard/rootfs/usr/bin/switchboard-config | 11 +- switchboard/rootfs/usr/bin/switchboard-stt | 153 +++++- .../usr/share/switchboard/wakeup/timeparse.py | 9 + .../asterisk/agi-bin/switchboard-wakeup.agi | 102 +++- switchboard/tests/test_operator_agi.py | 28 +- switchboard/tests/test_switchboard_config.py | 13 + .../tests/test_switchboard_stt_server.py | 5 +- switchboard/tests/test_wakeup_cancel.py | 480 ++++++++++++++++++ switchboard/tests/test_wakeup_snooze.py | 2 + 14 files changed, 852 insertions(+), 58 deletions(-) create mode 100644 switchboard/tests/test_wakeup_cancel.py diff --git a/switchboard/CHANGELOG-ARCHIVE.md b/switchboard/CHANGELOG-ARCHIVE.md index 98311da..fe6fa28 100644 --- a/switchboard/CHANGELOG-ARCHIVE.md +++ b/switchboard/CHANGELOG-ARCHIVE.md @@ -3,6 +3,36 @@ Earlier Switchboard releases, newest first. The most recent ones are in [CHANGELOG.md](CHANGELOG.md). +## 0.118.0 + +**The "phones dropped" card says only what is true of each phone it names.** + +- The link-health monitor also catches a fleet that drops between two samples, + from Asterisk's log. Its card said the phones "came back before the next + health check" and were "up now, not a current outage" whenever enough phones + had gone Unreachable since the last sample, without looking at the sample it + was judged on. Twice that sample showed them down: 2026-11-02 01:01 MST + (08:01 UTC), the gateway's weekly reboot caught mid-reboot (8 wired ports + down), and 2026-11-07 19:06 MST (02:06 UTC on 11-08), a router reboot (all 9 + phones down). Both fleets were back by the next sample. +- The card is now judged per phone against the sample. A "dropped briefly ... + up now" card is posted only when every phone that dropped is reachable in + it. Otherwise a "phones dropped" card is posted at once, naming the phones + still unreachable at that check, and a later check replaces it under the + same id: who was back, and who, if anyone, still was not. "Not a current + outage" is said only once every one of them is back and the sample is not a + fleet outage. Phones re-register one at a time, so a sample can show one to + three still down while the fleet is below the outage threshold; judged per + fleet, that read as healed. +- "All phones" and "nothing was reachable" are said only when every + registered phone dropped. The threshold is half the fleet, and a phone that + stayed up (often the cordless, which the outside line rings) kept working. +- If the phones stay down, the outage alert ("phones unreachable") follows as + before and the card says so when the outage threshold is met. A second drop + while a card is open gets a card of its own; each is updated under its own + id. +- Asterisk's log is now read just before each sample rather than after it, so + every drop counted was logged before the sample that judges it. ## 0.117.0 **An alert Home Assistant could not accept is posted once it answers.** diff --git a/switchboard/CHANGELOG.md b/switchboard/CHANGELOG.md index 4872531..7364230 100644 --- a/switchboard/CHANGELOG.md +++ b/switchboard/CHANGELOG.md @@ -1,8 +1,36 @@ # Changelog -Recent releases. Releases up to 0.117.0 are in the +Recent releases. Releases up to 0.118.0 are in the [changelog archive](https://github.com/tesseractAZ/Switchboard/blob/main/switchboard/CHANGELOG-ARCHIVE.md). +## 0.129.0 + +**A wake-up can be cancelled when the phone line turns "cancel" into a +sound-alike, and a call that understood nothing says the wake-up is still set.** + +- **A "cancel" that comes back as another word now cancels.** Telephone audio + loses most of an "s", and the recogniser wrote "cancel" as "Campbell." and + "Campful." on 2026-08-21 and as "Okay, I'm full." and "Campful." on + 2026-11-23, the second time with the prompt hint added after the first in + place. Both times nothing matched and the wake-up being called off rang. When + a wake-up is set, a reply shaped like "cancel" (the whole reply, at most two + words besides fillers such as "okay") now cancels it, as the word does. With + no wake-up set it counts as not understood. Times are read first, as before. + CORPUS_PLACEHOLDER +- **A "don't" stops a cancel.** "I don't want to cancel" and "never mind, keep + it" used to cancel. A "don't", "not", "keep" or "leave" anywhere in the reply + now cancels nothing, and the call asks again. An echo of the recogniser's own + prompt, which read as a cancel or as 6:53 PM, now does nothing. +- **A call that understood nothing ends with the wake-up that is still set.** + It used to end "No wake-up call was set", which was false whenever one was. It + now plays the recording that opens the call, "You already have a wake-up + call…", and the time. +- **A reply of only "Oh." or "zero" no longer sets midnight.** Read as the hour + 0, it replaced a set wake-up with 12:00 AM. "Oh seven hundred", "seven oh + five" and "zero zero thirty" read as before. +- **Each wake-up recording leaves a breadcrumb in the log**: its length and why + it ended, never the words, as the operator's recordings already do. + ## 0.128.0 **The web terminal listens on an IPv6 address; comments left behind by the @@ -385,34 +413,3 @@ documentation pass are corrected.** means only reachable but not yet measured. Units and `state_class` do not change. - A failed push no longer names its target in the add-on log. - -## 0.118.0 - -**The "phones dropped" card says only what is true of each phone it names.** - -- The link-health monitor also catches a fleet that drops between two samples, - from Asterisk's log. Its card said the phones "came back before the next - health check" and were "up now, not a current outage" whenever enough phones - had gone Unreachable since the last sample, without looking at the sample it - was judged on. Twice that sample showed them down: 2026-11-02 01:01 MST - (08:01 UTC), the gateway's weekly reboot caught mid-reboot (8 wired ports - down), and 2026-11-07 19:06 MST (02:06 UTC on 11-08), a router reboot (all 9 - phones down). Both fleets were back by the next sample. -- The card is now judged per phone against the sample. A "dropped briefly ... - up now" card is posted only when every phone that dropped is reachable in - it. Otherwise a "phones dropped" card is posted at once, naming the phones - still unreachable at that check, and a later check replaces it under the - same id: who was back, and who, if anyone, still was not. "Not a current - outage" is said only once every one of them is back and the sample is not a - fleet outage. Phones re-register one at a time, so a sample can show one to - three still down while the fleet is below the outage threshold; judged per - fleet, that read as healed. -- "All phones" and "nothing was reachable" are said only when every - registered phone dropped. The threshold is half the fleet, and a phone that - stayed up (often the cordless, which the outside line rings) kept working. -- If the phones stay down, the outage alert ("phones unreachable") follows as - before and the card says so when the outage threshold is met. A second drop - while a card is open gets a card of its own; each is updated under its own - id. -- Asterisk's log is now read just before each sample rather than after it, so - every drop counted was logged before the sample that judges it. diff --git a/switchboard/Dockerfile b/switchboard/Dockerfile index 7547364..fa19eff 100644 --- a/switchboard/Dockerfile +++ b/switchboard/Dockerfile @@ -231,4 +231,4 @@ LABEL \ org.opencontainers.image.title="Switchboard" \ org.opencontainers.image.description="Asterisk PBX for analog home phones" \ org.opencontainers.image.source="https://github.com/tesseractAZ/Switchboard" \ - io.hass.version="0.128.0" + io.hass.version="0.129.0" diff --git a/switchboard/config.yaml b/switchboard/config.yaml index 8d15bd8..a3a8fac 100644 --- a/switchboard/config.yaml +++ b/switchboard/config.yaml @@ -1,6 +1,6 @@ --- name: Switchboard -version: "0.128.0" +version: "0.129.0" slug: switchboard description: >- Instrumented Asterisk 20 PBX for analog house phones on a Grandstream GXW4216 diff --git a/switchboard/docs/reference/wake-ups-and-clock.md b/switchboard/docs/reference/wake-ups-and-clock.md index 83a5764..802cb5a 100644 --- a/switchboard/docs/reference/wake-ups-and-clock.md +++ b/switchboard/docs/reference/wake-ups-and-clock.md @@ -9,6 +9,18 @@ and reads it back before it hangs up. If it is wrong, dial the code again: it reads out the time that is set and asks for a new one or "cancel". Say "cancel" (or "clear", "never mind") to remove a pending wake-up. +**"Cancel" on a phone line.** Telephone audio loses most of an "s", and the +recogniser fills the gap with a word it knows: "cancel" has come back as +"Campbell", "Campful", "Pencil" and "Okay, I'm full". So when a wake-up is set, +a reply shaped like "cancel" cancels it as the word does. It must be the whole +reply, at most two words besides fillers such as "okay" or "please". With no +wake-up set, the same reply counts as not understood, and the call asks again. +A spoken time is always read as a time first, and a reply that is only "oh" +or "zero" is not read as midnight. A "don't", "not", "keep" or "leave" +anywhere in a reply cancels nothing. Every call ends by saying what is now true: the time it is +set for, that it was cancelled, or, when a wake-up was set and nothing was +understood, the time it is still set for. + - **One wake-up per room.** Setting a new one replaces the old. - At the set time the room rings for `wakeup_ring_seconds` (default 60). Once answered, the call fires the wake-up scene (if one is set), speaks a greeting diff --git a/switchboard/rootfs/usr/bin/switchboard-config b/switchboard/rootfs/usr/bin/switchboard-config index b64c9e9..af427f5 100644 --- a/switchboard/rootfs/usr/bin/switchboard-config +++ b/switchboard/rootfs/usr/bin/switchboard-config @@ -777,7 +777,12 @@ def render_operator_context(joined: str, automation_on: bool = False, def render_wakeup_context() -> list[str]: """The [wakeup] context (dial the code -> AGI sets/changes/cancels a wake-up, then the dialplan reads it back) and [wakeup-deliver] (the scheduler service - originates the room INTO this to actually ring it at the chosen time).""" + originates the room INTO this to actually ring it at the chosen time). + + WAKEUP_RESULT=kept means a wake-up was set, nothing the caller said was + understood, and it is still set: the call ends by reading it back with the + same recording that opened it (sw-wakeup-exists), not with sw-wakeup-none's + "No wake-up call was set", which on that path is the opposite of the truth.""" return [ ";; ----- Wake-up calls -----", "[wakeup]", @@ -789,12 +794,16 @@ def render_wakeup_context() -> list[str]: " same = n,NoOp(wakeup result=${WAKEUP_RESULT} epoch=${WAKEUP_EPOCH})", " same = n,GotoIf($[\"${WAKEUP_RESULT}\" = \"set\"]?setdone)", " same = n,GotoIf($[\"${WAKEUP_RESULT}\" = \"cancelled\"]?cancelled)", + " same = n,GotoIf($[\"${WAKEUP_RESULT}\" = \"kept\"]?kept)", " same = n,Goto(none)", f" same = n(setdone),Playback({prompt('sw-wakeup-set')})", " same = n,SayUnixTime(${WAKEUP_EPOCH},,IMp)", " same = n,Goto(bye)", f" same = n(cancelled),Playback({prompt('sw-wakeup-cancelled')})", " same = n,Goto(bye)", + f" same = n(kept),Playback({prompt('sw-wakeup-exists')})", + " same = n,SayUnixTime(${WAKEUP_EPOCH},,IMp)", + " same = n,Goto(bye)", f" same = n(none),Playback({prompt('sw-wakeup-none')})", f" same = n(bye),Playback({prompt('sw-goodbye')})", f" same = n,Playback({prompt('sw-endtone')})", diff --git a/switchboard/rootfs/usr/bin/switchboard-stt b/switchboard/rootfs/usr/bin/switchboard-stt index e65f858..5c0896b 100644 --- a/switchboard/rootfs/usr/bin/switchboard-stt +++ b/switchboard/rootfs/usr/bin/switchboard-stt @@ -304,18 +304,136 @@ def _recording_to_text(infile: str, prompt: str) -> str: # Time vocabulary to bias whisper for the wake-up flow. -# The caller is offered "say a new time, or say cancel" (sw-wakeup-change), and -# the parser below accepts cancel/clear/remove/delete/never mind/stop/forget — -# but whisper needs a PRIOR for those words or it returns a sound-alike. Observed -# live 2026-08-21 05:58: a caller said "cancel" twice at the change prompt and got -# 'Campbell.' then 'Campful.', so nothing matched, both attempts burned, and the -# 06:00 wake-up they were trying to call off stayed set. This is the identical -# failure the lights menu already documents for "list" ('Left'/'Lift'); priming -# the vocabulary is the same fix. Times still win — timeparse runs first. +# The caller is offered "To set a new time, say it now. To cancel, say cancel." +# (sw-wakeup-change), and time_reply below accepts cancel/clear/remove/delete/ +# never mind/stop/forget — but whisper needs a PRIOR for those words or it +# returns a sound-alike. Observed live 2026-08-21 05:58: a caller said "cancel" +# twice at the change prompt and got 'Campbell.' then 'Campful.', so nothing +# matched, both attempts burned, and the 06:00 wake-up they were trying to call +# off stayed set. This is the identical failure the lights menu already +# documents for "list" ('Left'/'Lift'); priming the vocabulary was the first +# fix. It is not enough on its own: on 2026-11-23 06:29, with this prompt sent, +# "cancel" came back as "Okay, I'm full." then 'Campful.' again, and the 06:30 +# wake-up rang. time_reply's sound-alike tier is the second. Times still win — +# timeparse runs first. _TIME_PROMPT = ("A time of day, for example: seven a.m., six thirty, " "quarter past seven, ten forty five, half past six, noon, midnight. " "Or say cancel to clear it.") +# ---- The wake-up reply: a time, cancel, a sound-alike of cancel, or nothing ---- +# +# WHY CANCEL NEEDS MORE THAN THE WORD. Every call reaches whisper as G.711 at +# 8 kHz, so nothing above 4 kHz survives — where most of an /s/ lives. "Cancel" +# arrives with its middle consonant smeared or gone and its vowels intact, and +# whisper fills the gap with a word it knows: 'Campbell.', 'Campful.' (2026-08-21 +# and 2026-11-23, live), "Okay, I'm full." (2026-11-23, live: the /k/ swallowed +# by "okay"), 'Pencil.' and 'Cancellate.' (synthetic voices through the same +# channel and recogniser, 2026-11-23). The prompt prime above does not stop it. +# +# THE COST IS LOPSIDED. A missed cancel rings a caller who is already awake. A +# FALSE cancel deletes the wake-up, and they oversleep. So the new tier is narrow +# and fenced: +# * timeparse runs first, so nothing it reads as a time is ever a cancel; +# * a sound-alike is a separate answer, CANCEL-LIKE, which the wake-up AGI acts +# on only when a wake-up is set — the one time cancel was offered; +# * it must be the WHOLE reply (at most two words once fillers are dropped); +# * a "don't", "not", "keep" or "leave" anywhere stops any cancel; +# * an echo of this prompt's own framing does nothing at all. +# The literal tier is the regex the wake-up flow has always used, unchanged. +_CANCEL_WORDS = re.compile(r"\b(cancel|clear|remove|delete|never mind|nevermind|stop|forget)\b") +# Filler a short reply may carry around the word. "no", "dont" and "not" are NOT +# filler: they carry meaning. +_CANCEL_FILLER = frozenset({"okay", "ok", "um", "uh", "so", "oh", "please", "yeah", + "hmm", "well", "the", "it", "just", "that", "my", "wake", + "up", "call", "alarm"}) +# Anywhere in the reply, these stop a cancel: "I don't want to cancel", +# "never mind, keep it". Both directions of doubt end in a retry, never a delete. +_CANCEL_VETO = frozenset({"dont", "not", "didnt", "wont", "doesnt", "keep", "leave"}) +# The prompt's own framing. whisper can hand a prompt back on a near-silent +# recording; read as a reply, the full prompt parses as 18:53 and its tail as a +# cancel. Any 4-word run of these does nothing. Each must stay a run of +# _TIME_PROMPT's words (test_wakeup_cancel holds it), so a prompt edit forces an +# update here. +_PROMPT_FRAMING = ("a time of day for example", "or say cancel to clear it") +# One word, or two run together ("Can sell", "Camp full"), shaped like "cancel": +# a /k/ or /p/ onset, a vowel, a nasal, then the smeared middle — a fricative or +# a lip stop (Campbell's b), with an optional stop after the nasal (the p of +# Camp-) — a vowel, and a final l. Built from the observed renderings, not from +# English: it accepts Campbell, Campful, Canful, Pencil, Council, Can sell and +# rejects candle, castle, camel, canal, channel, cancer, Kansas, campus, careful, +# handful, gamble, tinsel, dental (test_wakeup_cancel lists them all). +_CANCEL_SHAPE = re.compile( + r"(?:ck|[ckqp])[aeiouy]{1,2}[nm]{1,2}[pbk]?" + r"(?:ph|sh|[szfvb]|c(?=[eiy])){1,2}[aeiouy]{1,2}l{1,2}") +# What is left of the word when "okay" has swallowed its /k/: "Okay, I'm full." +_CANCEL_TAIL = re.compile(r"(?:ph|sh|[szfvb]|c(?=[eiy])){1,2}[aeiouy]{1,2}l{1,2}") + + +def _reply_tokens(text: str) -> list[str]: + """Lowercase letter-runs, apostrophes dropped (don't -> dont), O.K. -> ok.""" + t = (text or "").lower().replace("’", "'").replace("'", "") + t = re.sub(r"\bo\.?\s?k\b\.?", " ok ", t) + return [w for w in re.split(r"[^a-z]+", t) if w] + + +def _content(tokens: list[str]) -> list[str]: + """`tokens` without filler, and without a word repeating the one before it + ("Cancel, cancel." is one cancel).""" + out: list[str] = [] + for w in tokens: + if w in _CANCEL_FILLER or (out and out[-1] == w): + continue + out.append(w) + return out + + +def _grams(words: list[str], n: int = 4) -> set: + return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)} + + +_ECHO = set().union(*(_grams(p.split()) for p in _PROMPT_FRAMING)) + + +def _sounds_like_cancel(tokens: list[str]) -> bool: + """Is the whole reply a sound-alike of "cancel"? Pure; see _CANCEL_SHAPE.""" + rest = _content(tokens) + if not rest or len(rest) > 2: + return False + if len(rest) == 1: + # Cancelled., Canceled., Cancellate., Cancellation please. — but only as + # the whole reply: "Is it cancelled?" asks, it does not tell. + return rest[0].startswith("cancel") or bool(_CANCEL_SHAPE.fullmatch(rest[0])) + if _CANCEL_SHAPE.fullmatch(rest[0] + rest[1]): + return True # Can sell., Camp full. + # "Okay, cancel" with the /k/ absorbed into "okay": "Okay, I'm full." + i = tokens.index(rest[0]) + return (rest[0] == "im" and i > 0 and tokens[i - 1] in ("okay", "ok") + and bool(_CANCEL_TAIL.fullmatch(rest[1]))) + + +def time_reply(text: str, parse) -> tuple[str, str]: + """The wake-up flow's decision on one transcript. Pure (no I/O, no logging): + `parse` is timeparse.parse, passed in so tests can stub it. + + Returns (stdout, outcome). stdout is what the wake-up AGI reads: 'HH:MM', + 'CANCEL', 'CANCEL-LIKE', or '' (nothing). outcome is a constant label for + the log line — time, cancel, cancel-like, echo, negated or none — and never + a word from the transcript.""" + tokens = _reply_tokens(text) + if _grams(tokens) & _ECHO: + return "", "echo" + hhmm = parse(text) + if hhmm: + return hhmm, "time" + joined = " ".join(tokens) + literal = bool(_CANCEL_WORDS.search(joined)) + alike = not literal and _sounds_like_cancel(tokens) + if literal or alike: + if (_CANCEL_VETO & set(tokens)) or "do not" in joined: + return "", "negated" + return ("CANCEL", "cancel") if literal else ("CANCEL-LIKE", "cancel-like") + return "", "none" + # Above this match score a room result is treated as CONFIDENT and wins over the # feature words; below it (but still >= the room threshold) the feature words get # first refusal. match._score bumps a real match to >= 0.9 — exact fuzzy = 1.0, @@ -399,15 +517,22 @@ def main() -> int: sys.path.insert(0, "/usr/share/switchboard/wakeup") import timeparse # noqa: E402 text = _recording_to_text(args.infile, _TIME_PROMPT) - hhmm = timeparse.parse(text) - if hhmm: - log(f"heard={said(text, words)} -> time={hhmm}") - print(hhmm) - elif re.search(r"\b(cancel|clear|remove|delete|never mind|nevermind|stop|forget)\b", text.lower()): + out, outcome = time_reply(text, timeparse.parse) + # One said()-gated line per outcome (test_privacy_invariants counts them). + if outcome == "time": + log(f"heard={said(text, words)} -> time={out}") + elif outcome == "cancel": log(f"heard={said(text, words)} -> CANCEL") - print("CANCEL") + elif outcome == "cancel-like": + log(f"heard={said(text, words)} -> CANCEL-LIKE") + elif outcome == "negated": + log(f"heard={said(text, words)} -> ignored (negated cancel)") + elif outcome == "echo": + log(f"heard={said(text, words)} -> ignored (prompt echo)") else: log(f"heard={said(text, words)} -> time=None") + if out: + print(out) return 0 # rooms mode (the voice operator). diff --git a/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py b/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py index 0a0dfa8..616a503 100644 --- a/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py +++ b/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py @@ -183,6 +183,15 @@ def parse(text: str): if hour is not None: return _apply_ampm(hour, 0, ampm) + # A lone zero is not a time. whisper writes a breath, a cough or a clipped + # word as "Oh." / "O." / "0."; read as the bare hour 0 it set 00:00, which at + # the change prompt silently REPLACED a 6:30 wake-up with midnight. Only the + # whole reply being one zero is refused: "zero zero thirty" (00:30), "oh + # seven hundred" and "seven oh five" never reach here as a single token, and + # "midnight" is read above. + if len(tokens) == 1 and tokens[0] in ("oh", "o", "zero", "0", "00"): + return None + # " [oh] " / " " / bare "" hour, rest = _two_word_number(tokens) if hour is None: diff --git a/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi b/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi index 372f202..fed0689 100755 --- a/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi +++ b/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi @@ -7,7 +7,9 @@ utterance, shell out to ``switchboard-stt --mode time`` for offline recognition, then SET / CHANGE / CANCEL the caller's wake-up. The AGI only records the request in the store and sets channel vars (WAKEUP_RESULT, WAKEUP_EPOCH); the *dialplan* reads the confirmation back (Playback + SayUnixTime). The scheduler service rings -the room at the chosen time. +the room at the chosen time. WAKEUP_RESULT is set, cancelled, kept (a wake-up +was already set and nothing was understood, so it is read back as still set) or +none. The caller's room ext is taken from the channel name (PJSIP/-...), so it works regardless of caller-ID config. @@ -20,6 +22,7 @@ import os import re import subprocess import sys +import wave sys.path.insert(0, "/usr/share/switchboard/wakeup") import store # noqa: E402 @@ -46,6 +49,16 @@ ASR_DIR = "/run/switchboard/asr" MAX_ATTEMPTS = 2 RECORD_MS = 7000 SILENCE_S = 3 +# switchboard-stt's answer for a reply that SOUNDS like "cancel" without being +# the word ("Campful.", "Okay, I'm full." — see time_reply there). It cancels +# only where cancel was just offered, which is when a wake-up is set; anywhere +# else it is a miss. An AGI that predates it compares == "CANCEL" and so treats +# it as a miss too. +CANCEL_LIKE = "CANCEL-LIKE" +# RECORD's leading-silence remainder, as in switchboard-operator.agi: with s=N, +# res_agi rewinds N-1 s once N s of silence have passed, so a recording in which +# nothing crossed the threshold keeps only the last 1.02 s WHATEVER N is. +SILENT_REMAINDER_S = (0.95, 1.1) def read_env() -> dict: @@ -100,12 +113,57 @@ def channel_ext(channel: str) -> str: return ext if ext.isdigit() else "" +def _rec_summary(reply: str, wav: str) -> str: + """The `bytes=B secs=S end=E [no-speech]` part of the rec breadcrumb. + + Twin of agi_speech.rec_summary and of switchboard-operator.agi's + _rec_summary (this AGI imports nothing from operator/); + test_operator_agi.py holds all three to the same output. `secs` comes from + the WAV header, else from the size (8 kHz 16-bit mono: 16000 B/s behind a + 44-byte header). `end` is the bracketed word in Asterisk's RECORD reply, + whichever it is: "timeout" for both the silence cutoff and the RECORD_MS cap + (secs tells them apart), "hangup", "dtmf", or a failure such as "waitfor" or + "writefile". A reply without one (an empty read) logs no `end`. `no-speech` + marks a file that is only the silence remainder: nothing crossed the silence + threshold, which a silent caller and a muted or dead microphone produce + alike. Only the silence cutoff leaves that remainder, so no reply but + "timeout" earns the flag, whatever the size.""" + # Letters only: Asterisk's own reason word, never free text in the journal. + m = re.search(r"\(([a-z]+)\)", reply or "") + end = m.group(1) if m else "" + tail = f" end={end}" if end else "" + try: + size = os.path.getsize(wav) + except OSError: + return "bytes=-1" + tail # RECORD wrote nothing + secs = None + try: + with wave.open(wav, "rb") as w: + if w.getframerate() > 0 and w.getnframes() > 0: + secs = w.getnframes() / w.getframerate() + except Exception: # noqa: BLE001 (a breadcrumb must never end the call) + pass # a short or odd header: the size below still answers + if secs is None: + secs = max(size - 44, 0) / 16000 + out = f"bytes={size} secs={secs:.2f}{tail}" + lo, hi = SILENT_REMAINDER_S + if end == "timeout" and lo <= secs <= hi: + out += " no-speech" + return out + + def recognize(attempt: int) -> str: - """Record one utterance; return an 'HH:MM', 'CANCEL', or '' (nothing).""" + """Record one utterance; return an 'HH:MM', 'CANCEL', 'CANCEL-LIKE' (a + sound-alike of cancel, see CANCEL_LIKE), or '' (nothing).""" rec = f"{ASR_DIR}/wake-{os.getpid()}-{attempt}" stream(prompt("sw-beep")) - agi(f'RECORD FILE {rec} wav "" {RECORD_MS} s={SILENCE_S}') + reply = agi(f'RECORD FILE {rec} wav "" {RECORD_MS} s={SILENCE_S}') wav = rec + ".wav" + # The WAV is deleted after transcription, so this line is the only evidence + # afterwards of how long a recording was and why it ended (sizes, never + # words). On 2026-11-23 two misses left nothing to say whether the caller + # was cut off or spoke the whole word. + sys.stderr.write(f"[wakeup] rec attempt={attempt} {_rec_summary(reply, wav)}\n") out = "" # Start STT before the "one moment" prompt so inference overlaps its playback # (the child only touches the WAV + loopback whisper-server, not the AGI channel). @@ -205,11 +263,22 @@ def main() -> None: agi(f"EXEC SayUnixTime {tgt},,IMp") else: stream(prompt("sw-wakeup-didnt-catch")) - stream(prompt("sw-wakeup-change")) # "…say a new time, or say cancel." + stream(prompt("sw-wakeup-change")) # "To set a new time, say it now. To cancel, say cancel." else: stream(prompt("sw-wakeup-ask") if attempt == 0 else prompt("sw-wakeup-didnt-catch")) result = recognize(attempt) + if result == CANCEL_LIKE: + # The line turned "cancel" into something that only sounds like it. + # It counts only where cancel was just offered: with no wake-up set + # the caller was asked for a time, so it is a miss and they are asked + # again. (A failed store read above also lands here, erring toward + # keeping the alarm.) + if existing: + sys.stderr.write("[wakeup] a sound-alike of cancel, with a wake-up set: cancelling\n") + result = "CANCEL" + else: + sys.stderr.write("[wakeup] a sound-alike of cancel, with no wake-up set: asking again\n") if result == "CANCEL": removed = store.cancel(ext) record_change(ext, removed=removed) @@ -222,9 +291,34 @@ def main() -> None: set_var("WAKEUP_RESULT", "set") return + if existing: + # Nothing understood, and a wake-up was set when the call began. Say it + # is still set rather than "No wake-up call was set", which a caller who + # just tried to cancel hears as the opposite of the truth. Read the store + # again: the claim must be about what is set NOW. + epoch = _still_set(ext) + if epoch: + set_var("WAKEUP_EPOCH", str(epoch)) + set_var("WAKEUP_RESULT", "kept") + return set_var("WAKEUP_RESULT", "none") +def _still_set(ext: str) -> int | None: + """The target epoch of the wake-up stored for `ext` now, or None if there is + none, it is unreadable, or its epoch is not a positive int. Never raises: a + doubt means "none", so the call never claims a wake-up that may not exist.""" + try: + entry = store.get(ext) + except Exception as exc: # noqa: BLE001 + sys.stderr.write(f"[wakeup] store re-read failed: {exc}\n") + return None + tgt = entry.get("target_epoch") if isinstance(entry, dict) else None + if isinstance(tgt, int) and not isinstance(tgt, bool) and tgt > 0: + return tgt + return None + + if __name__ == "__main__": try: main() diff --git a/switchboard/tests/test_operator_agi.py b/switchboard/tests/test_operator_agi.py index 4a60610..d5b367a 100644 --- a/switchboard/tests/test_operator_agi.py +++ b/switchboard/tests/test_operator_agi.py @@ -25,6 +25,7 @@ _ROOT = Path(__file__).resolve().parents[1] _OPERATOR_AGI = _ROOT / "rootfs" / "var" / "lib" / "asterisk" / "agi-bin" / "switchboard-operator.agi" _SPEECH = _ROOT / "rootfs" / "usr" / "share" / "switchboard" / "operator" / "agi_speech.py" +_WAKEUP_AGI = _ROOT / "rootfs" / "var" / "lib" / "asterisk" / "agi-bin" / "switchboard-wakeup.agi" _failures = 0 @@ -64,10 +65,31 @@ def _wav(path: str, frames: int) -> str: SILENCE_REPLY = "200 result=0 (timeout) endpos=8160" +def _wakeup(): + """The wake-up AGI imports `store` and `delivery` at module level; stub them + and restore sys.path and sys.modules (conftest's tripwire).""" + import sys + import types + saved_mods = {k: sys.modules.get(k) for k in ("store", "delivery")} + saved_path = list(sys.path) + sys.modules["store"] = types.ModuleType("store") + sys.modules["delivery"] = types.ModuleType("delivery") + try: + return SourceFileLoader("sb_wakeup_agi_recdiag", str(_WAKEUP_AGI)).load_module() + finally: + sys.path[:] = saved_path + for k, v in saved_mods.items(): + if v is None: + sys.modules.pop(k, None) + else: + sys.modules[k] = v + + def _twins(): - """Both copies of the rule, each under its own name.""" - op, sp = _operator(), _speech() - return (("operator", op._rec_summary), ("speech", sp.rec_summary)) + """Every copy of the rule, each under its own name.""" + op, sp, wk = _operator(), _speech(), _wakeup() + return (("operator", op._rec_summary), ("speech", sp.rec_summary), + ("wakeup", wk._rec_summary)) def test_a_silent_capture_is_sized_and_flagged() -> None: diff --git a/switchboard/tests/test_switchboard_config.py b/switchboard/tests/test_switchboard_config.py index 26d5458..d694766 100644 --- a/switchboard/tests/test_switchboard_config.py +++ b/switchboard/tests/test_switchboard_config.py @@ -814,6 +814,19 @@ def test_wakeup_dialplan() -> None: check("wakeup: [wakeup] context runs the AGI", "[wakeup]" in on and "AGI(switchboard-wakeup.agi)" in on) check("wakeup: [wakeup-deliver] context greets + says the time", "[wakeup-deliver]" in on and "switchboard/sw-wakeup-greeting" in on and "SayUnixTime(,,IMp)" in on) + # A call that understood nothing while a wake-up was set ends by reading it + # back as still set (the opening recording), not with "No wake-up call was set". + ctx = on.split("[wakeup]\n", 1)[1].split("\n[", 1)[0].splitlines() + kept_if = ' same = n,GotoIf($["${WAKEUP_RESULT}" = "kept"]?kept)' + check("wakeup: kept is routed before the fall-through to none", + kept_if in ctx and ctx.index(kept_if) < ctx.index(" same = n,Goto(none)")) + i = ctx.index(" same = n(kept),Playback(switchboard/sw-wakeup-exists)") + check("wakeup: kept reads the wake-up back, then says goodbye", + ctx[i + 1:i + 3] == [" same = n,SayUnixTime(${WAKEUP_EPOCH},,IMp)", + " same = n,Goto(bye)"]) + check("wakeup: none and cancelled still play their own recordings", + " same = n(none),Playback(switchboard/sw-wakeup-none)" in ctx + and " same = n(cancelled),Playback(switchboard/sw-wakeup-cancelled)" in ctx) default_on = sbc.render_extensions({"rooms": rooms, "trunk": {}}) check("wakeup: on by default at 42", "exten = 42,1,NoOp(Wake-up call)" in default_on) off = sbc.render_extensions({"rooms": rooms, "wakeup_enabled": False, "trunk": {}}) diff --git a/switchboard/tests/test_switchboard_stt_server.py b/switchboard/tests/test_switchboard_stt_server.py index 6a33193..9152a0b 100644 --- a/switchboard/tests/test_switchboard_stt_server.py +++ b/switchboard/tests/test_switchboard_stt_server.py @@ -197,8 +197,9 @@ def test_server_disabled_uses_cli() -> None: def test_time_prompt_primes_the_cancel_vocabulary() -> None: """The wake-up flow OFFERS "cancel" aloud, so the recognizer must expect it. - sw-wakeup-change says "say a new time, or say cancel", and switchboard-stt's - time mode accepts cancel/clear/remove/delete/never mind/stop/forget — but + sw-wakeup-change says "To set a new time, say it now. To cancel, say + cancel.", and switchboard-stt's time mode accepts cancel/clear/remove/ + delete/never mind/stop/forget — but whisper needs a PRIOR for those words or it returns a sound-alike. Observed live 2026-08-21 05:58:35 and 05:58:51: a caller said "cancel" twice at that prompt and got 'Campbell.' then 'Campful.'; neither matched, both attempts diff --git a/switchboard/tests/test_wakeup_cancel.py b/switchboard/tests/test_wakeup_cancel.py new file mode 100644 index 0000000..b8e25f5 --- /dev/null +++ b/switchboard/tests/test_wakeup_cancel.py @@ -0,0 +1,480 @@ +"""Cancelling a wake-up when the phone line turns "cancel" into a sound-alike. + + python3 -m pytest switchboard/tests/test_wakeup_cancel.py + +Every call reaches whisper as G.711 at 8 kHz, where most of an /s/ is gone, so +"cancel" comes back as a word that only sounds like it. Live, at the change +prompt ("To set a new time, say it now. To cancel, say cancel."): + + 2026-08-21 05:58:35 'Campbell.' -> nothing matched + 2026-08-21 05:58:51 'Campful.' -> nothing matched; the 06:00 rang + 2026-11-23 06:29:45 "Okay, I'm full." -> nothing matched + 2026-11-23 06:30:00 'Campful.' -> nothing matched; the 06:30 rang + +The caller said "cancel" each time. The prompt prime added after the first +morning was in place for the second. switchboard-stt's time_reply now answers +CANCEL-LIKE for a reply shaped like "cancel", and the wake-up AGI acts on it +only when a wake-up is set, which is when cancel was just offered. + +A false cancel is the expensive mistake: the wake-up is deleted and the caller +oversleeps. Most of this file is about what must NOT cancel. +""" +import contextlib +import io +import json +import os +import re +import sys +import tempfile +import types +import wave +from importlib.machinery import SourceFileLoader +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SHARE = ROOT / "rootfs" / "usr" / "share" / "switchboard" +STT = ROOT / "rootfs" / "usr" / "bin" / "switchboard-stt" +AGI = ROOT / "rootfs" / "var" / "lib" / "asterisk" / "agi-bin" / "switchboard-wakeup.agi" + + +def _load_stt(): + """switchboard-stt imports `match`/`lights_match` from operator/; restore + sys.path afterwards (conftest's tripwire).""" + saved = list(sys.path) + sys.path.insert(0, str(SHARE / "operator")) + try: + return SourceFileLoader("stt_wakeup_cancel", str(STT)).load_module() + finally: + sys.path[:] = saved + + +stt = _load_stt() +# The REAL parser: the guarantee "a time is never a cancel" is only as good as +# the parser it is checked against. +tp = SourceFileLoader("timeparse_wakeup_cancel", str(SHARE / "wakeup" / "timeparse.py")).load_module() + + +def reply(text): + return stt.time_reply(text, tp.parse) + + +# --------------------------------------------------------------------------- # +# 1. What the line did to "cancel". +# --------------------------------------------------------------------------- # + +LIVE = ["Campbell.", "Campful.", "Okay, I'm full."] + + +@pytest.mark.parametrize("heard", LIVE) +def test_the_live_mishearings_are_sound_alikes(heard): + assert reply(heard) == ("CANCEL-LIKE", "cancel-like") + + +@pytest.mark.parametrize("heard", [ + "O.K., I'm full.", "OK, I'm full.", "Okay, I’m full.", "okay im full", + "Campbell, Campbell.", "Okay, Campbell.", "Campful, please.", +]) +def test_the_same_mishearings_written_differently(heard): + assert reply(heard) == ("CANCEL-LIKE", "cancel-like") + + +# What synthetic voices saying "cancel" produced through the same channel (8 kHz +# G.711 u-law) and the add-on's own recogniser (whisper.cpp base.en, the live +# prompt), 2026-11-23. Each is a reply a caller would have given in full. +SYNTHETIC = [ + "Pencil.", "Pencil, please.", "Pencil the wake up.", "Cancellate.", +] + + +@pytest.mark.parametrize("heard", SYNTHETIC) +def test_what_the_channel_did_to_synthetic_voices(heard): + assert reply(heard) == ("CANCEL-LIKE", "cancel-like") + + +@pytest.mark.parametrize("heard", [ + "Canful.", "Kansel.", "Can sell.", "Camp full.", "Camp bell.", "Can fall.", + "Council.", "Counsel.", "Canceled.", "Cancelled.", "Cancels.", "Cancelling.", + "Okay, canceled.", "Cancellation, please.", +]) +def test_the_shape_generalises_a_little(heard): + assert reply(heard) == ("CANCEL-LIKE", "cancel-like") + + +# --------------------------------------------------------------------------- # +# 2. What must never become a cancel. +# --------------------------------------------------------------------------- # + +@pytest.mark.parametrize("heard", [ + # English words near "cancel" that the shape is built to refuse. + "Candle.", "Castle.", "Camel.", "Canal.", "Channel.", "Cancer.", "Kansas.", + "Campus.", "Capful.", "Careful.", "Handful.", "Gamble.", "Cannibal.", + "Kennel.", "Chancel.", "Compel.", "Hansel.", "Tinsel.", "Dental.", "Kendall.", + "Damsel.", "Console.", "Casual.", "Just casual.", "Castle the wake up!", + # What is left of the word, alone, is not the word. + "Full.", "Fell.", "Bell.", "Fill.", "Call.", "Can call.", "I'm full.", "Cool.", + # A sound-alike inside a longer reply is not the whole reply. + "Can sell tomorrow.", "Pencil sharpener.", "Council meeting.", "Campbell soup.", + "Okay, I'm full now.", "I'm full, okay.", "Okay, I'm cool.", + # Real replies that are not cancel. + "Okay, I'm fine.", "Okay, I'm up.", "Okay, I'm awake.", "Okay, I'm well.", + "Keep it.", "Leave it.", "No.", "Yes.", "Okay.", "Thank you.", + "Thank you for watching.", "Goodbye.", "Hello?", "What time is it?", "Snooze.", + "You", "Hmm.", "...", "", "God bless you.", "Is it cancelled?", + "Is it canceled now?", +]) +def test_near_words_and_ordinary_replies_do_nothing(heard): + assert reply(heard) == ("", "none"), heard + + +@pytest.mark.parametrize("heard", [ + "Don't cancel.", "No, don't cancel it.", "Do not cancel.", + "I don't want to cancel.", "Never mind, keep it.", "Cancel? No, keep it.", + "Don’t cancel.", "Not cancel.", "Leave it, don't clear it.", +]) +def test_a_negated_cancel_is_only_a_retry(heard): + assert reply(heard) == ("", "negated"), heard + + +@pytest.mark.parametrize("heard", [ + "No, cancel it.", "Say cancel.", "Okay, say cancel.", "I want to clear it", + "Or say cancel.", "Cancel, cancel.", "Cancel my wake-up call.", +]) +def test_real_cancels_that_look_like_vetoes_still_cancel(heard): + assert reply(heard) == ("CANCEL", "cancel"), heard + + +def test_the_literal_family_is_unchanged(): + """The words the flow has always accepted, said alone, still cancel at once, + with the same regex.""" + assert stt._CANCEL_WORDS.pattern == \ + r"\b(cancel|clear|remove|delete|never mind|nevermind|stop|forget)\b" + for w in ("Cancel.", "Clear.", "Remove.", "Delete.", "Never mind.", + "Nevermind.", "Stop.", "Forget it.", "Okay, cancel."): + assert reply(w) == ("CANCEL", "cancel"), w + + +def test_a_prompt_echo_does_nothing(): + """whisper can hand its prompt back on a near-silent recording. Read as a + reply, the full prompt parses as 18:53 and its tail as a cancel.""" + assert tp.parse(stt._TIME_PROMPT) == "18:53" # what used to happen + assert reply(stt._TIME_PROMPT) == ("", "echo") + assert reply("Or say cancel to clear it.") == ("", "echo") + assert reply("A time of day, for example, six thirty.") == ("", "echo") + words = " ".join(stt._reply_tokens(stt._TIME_PROMPT)) + for framing in stt._PROMPT_FRAMING: + assert framing in words, framing # edit the prompt, update the veto + + +# --------------------------------------------------------------------------- # +# 3. A time is always a time. +# --------------------------------------------------------------------------- # + +_HOURS = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", + "ten", "eleven", "twelve"] +_MINUTES = ["", "oh five", "ten", "fifteen", "twenty", "twenty five", "thirty", + "thirty five", "forty", "forty five", "fifty", "fifty five"] +_LEADS = ["", "um ", "okay ", "okay, ", "make it ", "set it for ", "wake me at ", + "so ", "uh, "] +_TAILS = ["", " a.m.", " p.m.", " am", " in the morning", ".", "!"] + + +def _spoken_times(): + for lead in _LEADS: + for h in _HOURS: + for m in _MINUTES: + for tail in _TAILS: + yield f"{lead}{h} {m}".strip() + tail + for h in _HOURS: + for rel in ("quarter past", "half past", "quarter to", "ten past", + "twenty to"): + yield f"{lead}{rel} {h}" + for h in range(1, 13): + for m in range(0, 60, 5): + yield f"{h}:{m:02d}" + yield f"{h}:{m:02d} a.m." + yield f"{h}.{m:02d}." + + +# Live and synthetic renderings of spoken times, as whisper wrote them. +WRITTEN_TIMES = [ + "Six thirty-five, eight, seven.", "Five forty a.m.", "Six a.m.", + "Six twenty a.m.", "Six forty a.m.", "eight a.m.", "Six fifteen a.m.", + "Six twenty five a.m.", "Six thirty a.m.", "six thirty.", "6.15 a.m.", + "6. 25 a.m.", "5.45.", ", six thirty.", "Quarter past seven.", + "Half past six.", "eight o'clock", "Eight o'clock.", "seven a.m.", + "noon", "midnight", "oh seven hundred", "zero seven thirty", + "zero zero thirty", "seven oh five", "nineteen thirty", +] + + +def test_no_spoken_time_is_ever_touched(): + n = 0 + for phrase in list(_spoken_times()) + WRITTEN_TIMES: + hhmm = tp.parse(phrase) + got = reply(phrase) + n += 1 + if hhmm: + assert got == (hhmm, "time"), phrase + else: + assert got[0] not in ("CANCEL", "CANCEL-LIKE"), phrase + assert got[1] != "echo", phrase + assert n > 10_000, n + + +# --------------------------------------------------------------------------- # +# 4. A lone zero is not midnight. +# --------------------------------------------------------------------------- # + +@pytest.mark.parametrize("heard", ["Oh.", "Oh!", "O.", "oh", "zero", "Zero.", "0.", "0", "00"]) +def test_a_lone_zero_sets_nothing(heard): + """whisper writes a breath or a clipped word as "Oh." Read as the hour 0, it + REPLACED a set wake-up with midnight; at the change prompt that is a lost + alarm, as costly as a false cancel.""" + assert tp.parse(heard) is None + assert reply(heard) == ("", "none") + + +@pytest.mark.parametrize("heard, hhmm", [ + ("oh seven hundred", "07:00"), ("zero seven thirty", "07:30"), + ("oh five", "05:00"), ("seven oh five", "07:05"), ("zero zero thirty", "00:30"), + ("midnight", "00:00"), ("twelve am", "00:00"), ("0:30", "00:30"), +]) +def test_zero_inside_a_time_still_reads(heard, hhmm): + assert tp.parse(heard) == hhmm + + +# --------------------------------------------------------------------------- # +# 5. The wake-up AGI: a sound-alike cancels only where cancel was offered, and a +# call that understood nothing says the wake-up is still set. +# --------------------------------------------------------------------------- # + +class _Call: + """The real AGI on the real store and ledger, with its channel stubbed.""" + + def __init__(self, tmp_path): + self.store = SourceFileLoader("store_wakeup_cancel", + str(SHARE / "wakeup" / "store.py")).load_module() + self.store.PATH = str(tmp_path / "wakeups.json") + self.delivery = SourceFileLoader("delivery_wakeup_cancel", + str(SHARE / "webui" / "delivery.py")).load_module() + self.delivery.OUTCOME_PATH = str(tmp_path / "delivery-outcomes.jsonl") + saved_mods = {k: sys.modules.get(k) for k in ("store", "delivery")} + saved_path = list(sys.path) + sys.modules["store"] = self.store + sys.modules["delivery"] = self.delivery + try: + self.agi = SourceFileLoader("wakeup_agi_cancel", str(AGI)).load_module() + finally: + sys.path[:] = saved_path + for k, v in saved_mods.items(): + if v is None: + sys.modules.pop(k, None) + else: + sys.modules[k] = v + assert self.agi.store is self.store and self.agi.delivery is self.delivery + self.sent = [] + + def dial(self, ext, heard): + """`ext` dials the wake-up code; the recogniser answers each attempt + with the next item of `heard`. Returns how many attempts ran.""" + answers = iter(heard) + attempts = [] + self.sent = [] + + def recognize(attempt): + attempts.append(attempt) + return next(answers) + + def agi(cmd): + self.sent.append(cmd) + return "200 result=0" + + self.agi.read_env = lambda: {"agi_channel": f"PJSIP/{ext}-0000000d"} + self.agi.agi = agi + self.agi.recognize = recognize + self.agi.main() + return len(attempts) + + def var(self, name): + vals = [m.group(1) for c in self.sent + for m in [re.fullmatch(rf'SET VARIABLE {name} "(.*)"', c)] if m] + return vals[-1] if vals else None + + def rows(self): + p = Path(self.delivery.OUTCOME_PATH) + return [json.loads(l) for l in p.read_text().splitlines() if l.strip()] \ + if p.exists() else [] + + +@pytest.fixture +def call(tmp_path): + return _Call(tmp_path) + + +def test_the_morning_of_2026_11_23_now_cancels(call): + """ext 19 had 06:30 set and said "cancel"; the line made it a sound-alike.""" + call.store.set_wakeup("19", "06:30") + assert call.dial("19", ["CANCEL-LIKE"]) == 1 + assert call.store.get("19") is None + assert call.var("WAKEUP_RESULT") == "cancelled" + [row] = call.rows() + assert (row["outcome"], row["source"], row["removed"]) == ("cancelled", "phone", True) + + +def test_a_sound_alike_with_nothing_set_is_only_a_miss(call): + """With no wake-up, the caller was asked for a TIME, not offered cancel.""" + assert call.dial("19", ["CANCEL-LIKE", "CANCEL-LIKE"]) == 2 + assert call.var("WAKEUP_RESULT") == "none" + assert call.rows() == [] and call.store.get("19") is None + + +def test_a_sound_alike_then_a_time_with_nothing_set_sets_the_time(call): + assert call.dial("19", ["CANCEL-LIKE", "06:45"]) == 2 + assert call.var("WAKEUP_RESULT") == "set" + assert call.store.get("19")["hhmm"] == "06:45" + + +def test_two_misses_with_a_wake_up_set_say_it_is_still_set(call): + call.store.set_wakeup("19", "06:30") + epoch = call.store.get("19")["target_epoch"] + assert call.dial("19", ["", ""]) == 2 + assert call.var("WAKEUP_RESULT") == "kept" + assert call.var("WAKEUP_EPOCH") == str(epoch) + assert call.store.get("19")["target_epoch"] == epoch # untouched + assert call.rows() == [] # nothing changed + # It was offered change-or-cancel both times, as before. + streamed = [c for c in call.sent if c.startswith("STREAM FILE")] + assert [s.split()[2].rsplit("/", 1)[-1] for s in streamed] == [ + "sw-wakeup-exists", "sw-wakeup-change", "sw-wakeup-didnt-catch", "sw-wakeup-change"] + + +def test_kept_never_claims_a_wake_up_that_is_gone(call, monkeypatch): + call.store.set_wakeup("19", "06:30") + real_get = call.store.get + reads = [] + + def vanish(ext): + reads.append(ext) + return real_get(ext) if len(reads) == 1 else None + monkeypatch.setattr(call.store, "get", vanish) + call.dial("19", ["", ""]) + assert call.var("WAKEUP_RESULT") == "none" and len(reads) == 2 + + +@pytest.mark.parametrize("bad", [OSError("disk"), {"target_epoch": "x"}, + {"target_epoch": True}, {"target_epoch": 0}, []]) +def test_kept_with_an_unreadable_or_odd_entry_is_none(call, monkeypatch, bad): + call.store.set_wakeup("19", "06:30") + real_get = call.store.get + reads = [] + + def odd(ext): + reads.append(ext) + if len(reads) == 1: + return real_get(ext) + if isinstance(bad, Exception): + raise bad + return bad + monkeypatch.setattr(call.store, "get", odd) + call.dial("19", ["", ""]) + assert call.var("WAKEUP_RESULT") == "none" + + +def test_the_literal_word_and_a_time_behave_as_before(call): + call.store.set_wakeup("19", "06:30") + assert call.dial("19", ["CANCEL"]) == 1 + assert call.var("WAKEUP_RESULT") == "cancelled" and call.store.get("19") is None + assert call.dial("19", ["07:15"]) == 1 + assert call.var("WAKEUP_RESULT") == "set" and call.store.get("19")["hhmm"] == "07:15" + # A literal CANCEL with nothing set still answers "cancelled", as it always has. + call.store.cancel("19") + assert call.dial("19", ["CANCEL"]) == 1 and call.var("WAKEUP_RESULT") == "cancelled" + + +def test_an_unknown_answer_is_a_miss_not_a_cancel(call): + """Anything that is not exactly CANCEL, CANCEL-LIKE or HH:MM changes nothing.""" + call.store.set_wakeup("19", "06:30") + assert call.dial("19", ["cancel", "CANCEL-LIKE?"]) == 2 + assert call.var("WAKEUP_RESULT") == "kept" and call.store.get("19") is not None + + +def test_the_recording_leaves_a_breadcrumb_without_words(call, monkeypatch, capsys): + """recognize() itself: the RECORD reply and the file's length reach stderr, + the recognised words do not.""" + tmp = tempfile.mkdtemp() + try: + monkeypatch.setattr(call.agi, "ASR_DIR", tmp) + + def agi(cmd): + m = re.match(r"RECORD FILE (\S+) wav", cmd) + if m: + with wave.open(m.group(1) + ".wav", "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(8000) + w.writeframes(b"\0\0" * 8160) # the 1.02 s silence remainder + return "200 result=0 (timeout) endpos=8160" + return "200 result=0" + + class _Proc: + def communicate(self, timeout=None): + return ("CANCEL-LIKE\n", + "[switchboard-stt] heard=<8 chars> -> CANCEL-LIKE\n") + + monkeypatch.setattr(call.agi, "agi", agi) + monkeypatch.setattr(call.agi.subprocess, "Popen", lambda *a, **k: _Proc()) + capsys.readouterr() + assert call.agi.recognize(0) == "CANCEL-LIKE" + err = capsys.readouterr().err + assert "[wakeup] rec attempt=0 bytes=16364 secs=1.02 end=timeout no-speech" in err + assert "campful" not in err.lower() + assert not os.listdir(tmp) # the WAV is still deleted + finally: + for f in os.listdir(tmp): + os.unlink(os.path.join(tmp, f)) + os.rmdir(tmp) + + +def test_the_agi_decision_log_holds_no_words(call, capsys): + call.store.set_wakeup("19", "06:30") + capsys.readouterr() + call.dial("19", ["CANCEL-LIKE"]) + err = capsys.readouterr().err + assert "[wakeup] a sound-alike of cancel, with a wake-up set: cancelling" in err + + +# --------------------------------------------------------------------------- # +# 6. switchboard-stt's own log line for each new outcome follows the policy. +# --------------------------------------------------------------------------- # + +@pytest.mark.parametrize("heard, outcome, stdout", [ + ("Campful.", "-> CANCEL-LIKE", "CANCEL-LIKE"), + ("I don't want to cancel the zebra.", "-> ignored (negated cancel)", ""), + ("Or say cancel to clear it, zebra.", "-> ignored (prompt echo)", ""), +]) +@pytest.mark.parametrize("policy", [True, False]) +def test_the_new_outcomes_log_words_only_when_allowed(tmp_path, monkeypatch, capsys, + heard, outcome, stdout, policy): + feats = tmp_path / "features.json" + feats.write_text(json.dumps({"assistant": {"transcripts": policy}})) + monkeypatch.setattr(stt, "FEATURES", str(feats)) + monkeypatch.setattr(stt, "_recording_to_text", lambda infile, prompt: heard) + monkeypatch.setattr(sys, "argv", ["switchboard-stt", "--in", "r.wav", "--mode", "time"]) + monkeypatch.setattr(sys, "path", list(sys.path)) + monkeypatch.setitem(sys.modules, "timeparse", types.SimpleNamespace(parse=tp.parse)) + capsys.readouterr() + assert stt.main() == 0 + got = capsys.readouterr() + assert outcome in got.err and got.out.strip() == stdout + if policy: + assert repr(heard) in got.err + else: + assert f"<{len(heard)} chars>" in got.err + assert "zebra" not in got.err and "campful" not in got.err.lower() + + +if __name__ == "__main__": + import _runner + raise SystemExit(_runner.run(globals())) diff --git a/switchboard/tests/test_wakeup_snooze.py b/switchboard/tests/test_wakeup_snooze.py index 16be75b..7ce2a1d 100644 --- a/switchboard/tests/test_wakeup_snooze.py +++ b/switchboard/tests/test_wakeup_snooze.py @@ -398,6 +398,8 @@ def test_a_phone_set_before_the_ring_is_not_a_snooze(tmp_path, mst, set_at): @pytest.mark.parametrize("second, change, new_hhmm", [ ("06:25", "set", "06:25"), ("CANCEL", "cancelled", None), + # A sound-alike of cancel ("Campful.") with the 06:20 just set: a cancel. + ("CANCEL-LIKE", "cancelled", None), ]) def test_the_newest_phone_change_names_the_snooze(tmp_path, mst, second, change, new_hhmm): From 5e87fcef3b53774ca68bbf89ffcfbef81c73e2a9 Mon Sep 17 00:00:00 2001 From: tesseractAZ <192581158+tesseractAZ@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:02:26 -0700 Subject: [PATCH 2/2] Review fixes: zero and duration replies, silent recordings, corpus-tuned shape - timeparse: a zero with no other number after it ("Oh, oh, oh.", "Oh, oh, okay.") and a length of time ("ten more minutes", "one second") are not times; both used to replace a set wake-up (midnight, or that hour). - The wake-up AGI does not transcribe a recording flagged no-speech; the attempt is a miss. - _CANCEL_SHAPE takes a t after the nasal (Can't feel) and a final e (Console), from a 1,288-recording synthetic corpus: 535/560 cancels caught (516 before), 0 of 728 times/other replies become one. - Tests pin each veto word, the 4-word echo window, the filler list, the tail and shape anchors, digit zero-hours; the privacy scan floor is 9. Co-Authored-By: Claude Opus 5.5 --- switchboard/CHANGELOG.md | 20 ++- .../docs/reference/wake-ups-and-clock.md | 15 +- switchboard/rootfs/usr/bin/switchboard-stt | 21 +-- .../usr/share/switchboard/wakeup/timeparse.py | 31 +++- .../asterisk/agi-bin/switchboard-wakeup.agi | 19 ++- switchboard/tests/test_privacy_invariants.py | 10 +- switchboard/tests/test_wakeup_cancel.py | 150 ++++++++++++++---- 7 files changed, 201 insertions(+), 65 deletions(-) diff --git a/switchboard/CHANGELOG.md b/switchboard/CHANGELOG.md index 7364230..d689fed 100644 --- a/switchboard/CHANGELOG.md +++ b/switchboard/CHANGELOG.md @@ -16,19 +16,27 @@ sound-alike, and a call that understood nothing says the wake-up is still set.** a wake-up is set, a reply shaped like "cancel" (the whole reply, at most two words besides fillers such as "okay") now cancels it, as the word does. With no wake-up set it counts as not understood. Times are read first, as before. - CORPUS_PLACEHOLDER + Checked against 1,288 recordings of 28 synthetic voices sent through the same + 8 kHz channel and recogniser: 535 of 560 spoken cancels now cancel (516 + before), and none of the 728 spoken times and other replies becomes one. - **A "don't" stops a cancel.** "I don't want to cancel" and "never mind, keep it" used to cancel. A "don't", "not", "keep" or "leave" anywhere in the reply - now cancels nothing, and the call asks again. An echo of the recogniser's own + now cancels nothing; the reply counts as not understood. An echo of the recogniser's own prompt, which read as a cancel or as 6:53 PM, now does nothing. - **A call that understood nothing ends with the wake-up that is still set.** It used to end "No wake-up call was set", which was false whenever one was. It now plays the recording that opens the call, "You already have a wake-up call…", and the time. -- **A reply of only "Oh." or "zero" no longer sets midnight.** Read as the hour - 0, it replaced a set wake-up with 12:00 AM. "Oh seven hundred", "seven oh - five" and "zero zero thirty" read as before. -- **Each wake-up recording leaves a breadcrumb in the log**: its length and why +- **Two kinds of reply no longer replace a wake-up with the wrong time.** A + zero with no other number after it ("Oh.", or whisper's "Oh, oh, oh." on + noise) was read as the hour 0 and set midnight. A length of time ("ten more + minutes", "one second") was read as that hour. Both now count as not + understood. "Oh seven hundred", "seven oh five", "zero zero thirty" and + "ten past seven" read as before. +- **A recording with no speech in it is not transcribed.** When nothing rose + above the silence threshold, whisper still answered something, and any + answer could act on the wake-up. The attempt now counts as a miss. +- **Each wake-up recording leaves a line in the log** with its length and why it ended, never the words, as the operator's recordings already do. ## 0.128.0 diff --git a/switchboard/docs/reference/wake-ups-and-clock.md b/switchboard/docs/reference/wake-ups-and-clock.md index 802cb5a..aeb3ec1 100644 --- a/switchboard/docs/reference/wake-ups-and-clock.md +++ b/switchboard/docs/reference/wake-ups-and-clock.md @@ -14,12 +14,15 @@ recogniser fills the gap with a word it knows: "cancel" has come back as "Campbell", "Campful", "Pencil" and "Okay, I'm full". So when a wake-up is set, a reply shaped like "cancel" cancels it as the word does. It must be the whole reply, at most two words besides fillers such as "okay" or "please". With no -wake-up set, the same reply counts as not understood, and the call asks again. -A spoken time is always read as a time first, and a reply that is only "oh" -or "zero" is not read as midnight. A "don't", "not", "keep" or "leave" -anywhere in a reply cancels nothing. Every call ends by saying what is now true: the time it is -set for, that it was cancelled, or, when a wake-up was set and nothing was -understood, the time it is still set for. +wake-up set, the same reply counts as not understood. +A spoken time is always read as a time first. Two kinds of reply are not +read as a time at all: a zero with no other number after it ("oh", "oh, oh, +oh"), which used to be midnight, and a length of time ("ten more minutes", +"one second"), which used to be that hour. A "don't", "not", "keep" or "leave" +anywhere in a reply cancels nothing, and a recording in which nothing rose +above the silence threshold is not sent to the recogniser. When a wake-up was +set and nothing was understood, the call ends by reading out the time it is +still set for. - **One wake-up per room.** Setting a new one replaces the old. - At the set time the room rings for `wakeup_ring_seconds` (default 60). Once diff --git a/switchboard/rootfs/usr/bin/switchboard-stt b/switchboard/rootfs/usr/bin/switchboard-stt index 5c0896b..e3bd1f9 100644 --- a/switchboard/rootfs/usr/bin/switchboard-stt +++ b/switchboard/rootfs/usr/bin/switchboard-stt @@ -355,16 +355,19 @@ _CANCEL_VETO = frozenset({"dont", "not", "didnt", "wont", "doesnt", "keep", "lea # _TIME_PROMPT's words (test_wakeup_cancel holds it), so a prompt edit forces an # update here. _PROMPT_FRAMING = ("a time of day for example", "or say cancel to clear it") -# One word, or two run together ("Can sell", "Camp full"), shaped like "cancel": -# a /k/ or /p/ onset, a vowel, a nasal, then the smeared middle — a fricative or -# a lip stop (Campbell's b), with an optional stop after the nasal (the p of -# Camp-) — a vowel, and a final l. Built from the observed renderings, not from -# English: it accepts Campbell, Campful, Canful, Pencil, Council, Can sell and -# rejects candle, castle, camel, canal, channel, cancer, Kansas, campus, careful, -# handful, gamble, tinsel, dental (test_wakeup_cancel lists them all). +# One word, or two run together ("Can sell", "Can't feel"), shaped like +# "cancel": a /k/ or /p/ onset, a vowel, a nasal, then the smeared middle — a +# fricative or a lip stop (Campbell's b), with an optional stop after the nasal +# (the p of Camp-, the t of Can't) — a vowel, and a final l (Console's e +# allowed). Built from the observed renderings, not from English: it accepts +# Campbell, Campful, Canful, Pencil, Council, Console, Can sell, Can't feel and +# rejects candle, castle, camel, canal, channel, cancer, Kansas, campus, +# careful, handful, gamble, tinsel, dental (test_wakeup_cancel lists them all). +# Over the 234,454 words of an English dictionary it accepts 25, every one a +# word nobody says to a wake-up prompt (cymbal, pinball, painful ...). _CANCEL_SHAPE = re.compile( - r"(?:ck|[ckqp])[aeiouy]{1,2}[nm]{1,2}[pbk]?" - r"(?:ph|sh|[szfvb]|c(?=[eiy])){1,2}[aeiouy]{1,2}l{1,2}") + r"(?:ck|[ckqp])[aeiouy]{1,2}[nm]{1,2}[pbkt]?" + r"(?:ph|sh|[szfvb]|c(?=[eiy])){1,2}[aeiouy]{1,2}l{1,2}e?") # What is left of the word when "okay" has swallowed its /k/: "Okay, I'm full." _CANCEL_TAIL = re.compile(r"(?:ph|sh|[szfvb]|c(?=[eiy])){1,2}[aeiouy]{1,2}l{1,2}") diff --git a/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py b/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py index 616a503..6574748 100644 --- a/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py +++ b/switchboard/rootfs/usr/share/switchboard/wakeup/timeparse.py @@ -21,6 +21,16 @@ "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19, } _TENS = {"twenty": 20, "thirty": 30, "forty": 40, "fifty": 50} +# The ways whisper writes a zero, and the words that make a count a duration. +_ZEROS = ("oh", "o", "zero", "0", "00") +_DURATION = frozenset({"more", "minute", "minutes", "min", "mins", "second", "seconds", + "sec", "secs", "moment", "hour", "hours"}) + + +def _nonzero(word: str) -> bool: + """Is `word` a number other than zero (a number word, a tens word, digits)?""" + return ((word in _ONES and _ONES[word] > 0) or word in _TENS + or (word.isdigit() and int(word) > 0)) def _normalize(text: str) -> str: @@ -183,13 +193,20 @@ def parse(text: str): if hour is not None: return _apply_ampm(hour, 0, ampm) - # A lone zero is not a time. whisper writes a breath, a cough or a clipped - # word as "Oh." / "O." / "0."; read as the bare hour 0 it set 00:00, which at - # the change prompt silently REPLACED a 6:30 wake-up with midnight. Only the - # whole reply being one zero is refused: "zero zero thirty" (00:30), "oh - # seven hundred" and "seven oh five" never reach here as a single token, and - # "midnight" is read above. - if len(tokens) == 1 and tokens[0] in ("oh", "o", "zero", "0", "00"): + # A zero with no other number after it is not a time. whisper writes a + # breath, a cough or a clipped word as "Oh." / "O." / "0.", and noise as a + # repetition loop ("Oh, oh, oh."); read as the hour 0 each set 00:00, which + # at the change prompt silently REPLACED a 6:30 wake-up with midnight. + # "zero zero thirty" (00:30) and "oh oh five" keep their minutes; "oh seven + # hundred", "seven oh five", "midnight" and a digit clock are read above or + # never start with a zero. + if tokens and tokens[0] in _ZEROS and not any(_nonzero(w) for w in tokens[1:]): + return None + # A count followed by a length of time is not a clock time: "ten more + # minutes" (a caller dialling in mid-ring to snooze) set 10:00 and "one + # second" 01:00, each replacing the wake-up. Relative times ("ten past + # seven", "five to six") are read above and never reach here. + if any(w in _DURATION for w in tokens[1:]): return None # " [oh] " / " " / bare "" diff --git a/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi b/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi index fed0689..70a6105 100755 --- a/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi +++ b/switchboard/rootfs/var/lib/asterisk/agi-bin/switchboard-wakeup.agi @@ -161,9 +161,22 @@ def recognize(attempt: int) -> str: wav = rec + ".wav" # The WAV is deleted after transcription, so this line is the only evidence # afterwards of how long a recording was and why it ended (sizes, never - # words). On 2026-11-23 two misses left nothing to say whether the caller - # was cut off or spoke the whole word. - sys.stderr.write(f"[wakeup] rec attempt={attempt} {_rec_summary(reply, wav)}\n") + # words). On 2026-11-23 two misses left nothing to say how long either + # recording was or why it ended. + summary = _rec_summary(reply, wav) + sys.stderr.write(f"[wakeup] rec attempt={attempt} {summary}\n") + if summary.endswith(" no-speech"): + # Nothing crossed the silence threshold: the file is only RECORD's + # silence remainder. whisper hands back something for silence anyway + # ("You", "Thank you.", a piece of its own prompt), and here any answer + # can cancel or replace a wake-up. So it is not transcribed, and the + # attempt is a miss: the caller is asked again. + sys.stderr.write("[wakeup] no speech in the recording: not transcribed\n") + try: + os.unlink(wav) + except OSError: + pass + return "" out = "" # Start STT before the "one moment" prompt so inference overlaps its playback # (the child only touches the WAV + loopback whisper-server, not the AGI channel). diff --git a/switchboard/tests/test_privacy_invariants.py b/switchboard/tests/test_privacy_invariants.py index c2ce99d..b26343a 100644 --- a/switchboard/tests/test_privacy_invariants.py +++ b/switchboard/tests/test_privacy_invariants.py @@ -604,10 +604,12 @@ def test_no_voice_script_writes_recognised_words_to_stderr_ungated(): assert not offenders, ( "recognised speech reaches stderr, which is the add-on journal, without " "said():\n " + "\n ".join(offenders)) - # ...and the scan SEES the sites it is there for: the six heard= lines in - # switchboard-stt, the assistant's per-turn line, and agi_speech.say()'s two - # failure lines. Fewer means a rename blinded it, not that the lines went away. - assert gated["switchboard-stt"] >= 6, gated + # ...and the scan SEES the sites it is there for: the nine heard= lines in + # switchboard-stt (six wake-up outcomes: time, cancel, cancel-like, negated, + # echo, none; one transcribe; two rooms), the assistant's per-turn line, and + # agi_speech.say()'s two failure lines. Fewer means a rename blinded it, not + # that the lines went away. + assert gated["switchboard-stt"] >= 9, gated assert gated["switchboard-assistant.agi"] >= 1, gated assert gated["agi_speech.py"] >= 2, gated diff --git a/switchboard/tests/test_wakeup_cancel.py b/switchboard/tests/test_wakeup_cancel.py index b8e25f5..ebe0424 100644 --- a/switchboard/tests/test_wakeup_cancel.py +++ b/switchboard/tests/test_wakeup_cancel.py @@ -82,9 +82,13 @@ def test_the_same_mishearings_written_differently(heard): # What synthetic voices saying "cancel" produced through the same channel (8 kHz # G.711 u-law) and the add-on's own recogniser (whisper.cpp base.en, the live -# prompt), 2026-11-23. Each is a reply a caller would have given in full. +# prompt), 2026-11-23: 1,288 recordings of 28 voices, of which 535 of 560 +# cancels now cancel (516 before) and none of 728 times and other replies +# becomes one. Each is a reply a caller would have given in full. SYNTHETIC = [ - "Pencil.", "Pencil, please.", "Pencil the wake up.", "Cancellate.", + "Campbell.", "Pencil.", "Pencil, please.", "Pencil that.", "Pencil the wake up.", + "Cancellate.", "Can't feel.", "Can't feel it.", "Can't feel that.", + "Can't feel the wake up.", "Console it.", ] @@ -111,12 +115,18 @@ def test_the_shape_generalises_a_little(heard): "Candle.", "Castle.", "Camel.", "Canal.", "Channel.", "Cancer.", "Kansas.", "Campus.", "Capful.", "Careful.", "Handful.", "Gamble.", "Cannibal.", "Kennel.", "Chancel.", "Compel.", "Hansel.", "Tinsel.", "Dental.", "Kendall.", - "Damsel.", "Console.", "Casual.", "Just casual.", "Castle the wake up!", + "Damsel.", "Casual.", "Just casual.", "Castle the wake up!", "Castle, please.", + "Can't live.", "Can't do it.", "Can't be weird.", "Can't sleep.", + # A word that only CONTAINS the shape is not shaped like it. + "Councilman.", "Pencils.", "Encouncil.", "Pinballs.", # What is left of the word, alone, is not the word. "Full.", "Fell.", "Bell.", "Fill.", "Call.", "Can call.", "I'm full.", "Cool.", # A sound-alike inside a longer reply is not the whole reply. "Can sell tomorrow.", "Pencil sharpener.", "Council meeting.", "Campbell soup.", "Okay, I'm full now.", "I'm full, okay.", "Okay, I'm cool.", + # "Okay, I'm" followed by a word that only STARTS like the tail. + "Okay, I'm fully up.", "Okay, I'm feeling up.", "Okay, I'm fuller.", + "Okay, I'm feeling it.", # Real replies that are not cancel. "Okay, I'm fine.", "Okay, I'm up.", "Okay, I'm awake.", "Okay, I'm well.", "Keep it.", "Leave it.", "No.", "Yes.", "Okay.", "Thank you.", @@ -132,11 +142,30 @@ def test_near_words_and_ordinary_replies_do_nothing(heard): "Don't cancel.", "No, don't cancel it.", "Do not cancel.", "I don't want to cancel.", "Never mind, keep it.", "Cancel? No, keep it.", "Don’t cancel.", "Not cancel.", "Leave it, don't clear it.", + # One reply per veto word, each the only veto in it. + "Never mind, leave it.", "Stop, leave it.", "I didn't say cancel.", + "No, I won't cancel it.", "That doesn't mean cancel.", "Didn't cancel.", + "Won't cancel.", "Doesn't cancel.", "Keep it, never mind.", ]) def test_a_negated_cancel_is_only_a_retry(heard): assert reply(heard) == ("", "negated"), heard +def test_the_veto_words_are_these(): + assert stt._CANCEL_VETO == {"dont", "not", "didnt", "wont", "doesnt", "keep", "leave"} + + +# Written out, not read from the module: trimming the set must fail here. +FILLER = ["okay", "ok", "um", "uh", "so", "oh", "please", "yeah", "hmm", "well", + "the", "it", "just", "that", "my", "wake", "up", "call", "alarm"] + + +@pytest.mark.parametrize("w", FILLER) +def test_every_filler_around_a_sound_alike_still_cancels(w): + assert reply(f"{w.capitalize()}, Campful.") == ("CANCEL-LIKE", "cancel-like") + assert reply(f"Campbell, {w}.") == ("CANCEL-LIKE", "cancel-like") + + @pytest.mark.parametrize("heard", [ "No, cancel it.", "Say cancel.", "Okay, say cancel.", "I want to clear it", "Or say cancel.", "Cancel, cancel.", "Cancel my wake-up call.", @@ -162,6 +191,12 @@ def test_a_prompt_echo_does_nothing(): assert reply(stt._TIME_PROMPT) == ("", "echo") assert reply("Or say cancel to clear it.") == ("", "echo") assert reply("A time of day, for example, six thirty.") == ("", "echo") + # Exactly four words of the framing is already an echo (the window is 4). + assert reply("Cancel to clear it.") == ("", "echo") + assert reply("Time of day for.") == ("", "echo") + assert reply("Say cancel to clear it.") == ("", "echo") + # Three are not: a real "Or say cancel." still cancels. + assert reply("Or say cancel.") == ("CANCEL", "cancel") words = " ".join(stt._reply_tokens(stt._TIME_PROMPT)) for framing in stt._PROMPT_FRAMING: assert framing in words, framing # edit the prompt, update the veto @@ -227,8 +262,13 @@ def test_no_spoken_time_is_ever_touched(): # 4. A lone zero is not midnight. # --------------------------------------------------------------------------- # -@pytest.mark.parametrize("heard", ["Oh.", "Oh!", "O.", "oh", "zero", "Zero.", "0.", "0", "00"]) -def test_a_lone_zero_sets_nothing(heard): +@pytest.mark.parametrize("heard", [ + "Oh.", "Oh!", "O.", "oh", "zero", "Zero.", "0.", "0", "00", + # whisper's repetition loop on noise, and a zero before a non-number. + "Oh, oh.", "Oh, oh, oh.", "Oh, oh, oh, oh, oh, oh, oh, oh.", "Oh... oh... oh...", + "Zero, zero, zero.", "O, O, O.", "0 0", "0.00", "Oh, oh, okay.", "Oh, oh, wait.", +]) +def test_a_zero_with_no_other_number_sets_nothing(heard): """whisper writes a breath or a clipped word as "Oh." Read as the hour 0, it REPLACED a set wake-up with midnight; at the change prompt that is a lost alarm, as costly as a false cancel.""" @@ -236,15 +276,40 @@ def test_a_lone_zero_sets_nothing(heard): assert reply(heard) == ("", "none") +def test_a_stuttered_cancel_is_a_cancel_not_midnight(): + assert reply("Oh, oh, cancel.") == ("CANCEL", "cancel") + + @pytest.mark.parametrize("heard, hhmm", [ ("oh seven hundred", "07:00"), ("zero seven thirty", "07:30"), ("oh five", "05:00"), ("seven oh five", "07:05"), ("zero zero thirty", "00:30"), - ("midnight", "00:00"), ("twelve am", "00:00"), ("0:30", "00:30"), + ("oh oh five", "00:05"), ("oh oh hundred", "00:00"), ("midnight", "00:00"), + ("twelve am", "00:00"), ("0:30", "00:30"), ("0:00", "00:00"), ("0000", "00:00"), + ("0.30", "00:30"), ("0 45", "00:45"), ]) def test_zero_inside_a_time_still_reads(heard, hhmm): assert tp.parse(heard) == hhmm +@pytest.mark.parametrize("heard", [ + "One second.", "Hold on, one second.", "One moment, please.", "Ten more minutes.", + "Five more minutes.", "Fifteen minutes.", "Two hours.", "Five more.", +]) +def test_a_length_of_time_is_not_a_clock_time(heard): + """A caller dialling in mid-ring to snooze says "ten more minutes"; read as + 10:00 it replaced the wake-up.""" + assert tp.parse(heard) is None + assert reply(heard) == ("", "none") + + +@pytest.mark.parametrize("heard, hhmm", [ + ("ten past seven", "07:10"), ("five to six", "05:55"), ("twenty minutes past six", "06:20"), + ("quarter past seven", "07:15"), ("seven thirty", "07:30"), +]) +def test_relative_times_still_read(heard, hhmm): + assert tp.parse(heard) == hhmm + + # --------------------------------------------------------------------------- # # 5. The wake-up AGI: a sound-alike cancels only where cancel was offered, and a # call that understood nothing says the wake-up is still set. @@ -400,36 +465,46 @@ def test_an_unknown_answer_is_a_miss_not_a_cancel(call): assert call.var("WAKEUP_RESULT") == "kept" and call.store.get("19") is not None -def test_the_recording_leaves_a_breadcrumb_without_words(call, monkeypatch, capsys): - """recognize() itself: the RECORD reply and the file's length reach stderr, - the recognised words do not.""" - tmp = tempfile.mkdtemp() - try: - monkeypatch.setattr(call.agi, "ASR_DIR", tmp) +def _recorded(call, monkeypatch, tmp, frames): + """Run the REAL recognize() with RECORD writing `frames` of 8 kHz audio and + switchboard-stt stubbed to answer CANCEL-LIKE. Returns (result, stt spawns).""" + monkeypatch.setattr(call.agi, "ASR_DIR", tmp) + spawned = [] - def agi(cmd): - m = re.match(r"RECORD FILE (\S+) wav", cmd) - if m: - with wave.open(m.group(1) + ".wav", "wb") as w: - w.setnchannels(1) - w.setsampwidth(2) - w.setframerate(8000) - w.writeframes(b"\0\0" * 8160) # the 1.02 s silence remainder - return "200 result=0 (timeout) endpos=8160" - return "200 result=0" + def agi(cmd): + m = re.match(r"RECORD FILE (\S+) wav", cmd) + if m: + with wave.open(m.group(1) + ".wav", "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(8000) + w.writeframes(b"\0\0" * frames) + return f"200 result=0 (timeout) endpos={frames}" + return "200 result=0" - class _Proc: - def communicate(self, timeout=None): - return ("CANCEL-LIKE\n", - "[switchboard-stt] heard=<8 chars> -> CANCEL-LIKE\n") + class _Proc: + def communicate(self, timeout=None): + return ("CANCEL-LIKE\n", "[switchboard-stt] heard=<8 chars> -> CANCEL-LIKE\n") - monkeypatch.setattr(call.agi, "agi", agi) - monkeypatch.setattr(call.agi.subprocess, "Popen", lambda *a, **k: _Proc()) + def popen(*a, **k): + spawned.append(a) + return _Proc() + + monkeypatch.setattr(call.agi, "agi", agi) + monkeypatch.setattr(call.agi.subprocess, "Popen", popen) + return call.agi.recognize(0), len(spawned) + + +def test_a_recording_with_no_speech_is_not_transcribed(call, monkeypatch, capsys): + """Only RECORD's 1.02 s silence remainder: whisper would answer something + for it anyway, and here an answer can cancel or replace a wake-up.""" + tmp = tempfile.mkdtemp() + try: capsys.readouterr() - assert call.agi.recognize(0) == "CANCEL-LIKE" + assert _recorded(call, monkeypatch, tmp, 8160) == ("", 0) err = capsys.readouterr().err assert "[wakeup] rec attempt=0 bytes=16364 secs=1.02 end=timeout no-speech" in err - assert "campful" not in err.lower() + assert "[wakeup] no speech in the recording: not transcribed" in err assert not os.listdir(tmp) # the WAV is still deleted finally: for f in os.listdir(tmp): @@ -437,6 +512,21 @@ def communicate(self, timeout=None): os.rmdir(tmp) +def test_a_recording_with_speech_is_transcribed_and_leaves_no_words(call, monkeypatch, capsys): + tmp = tempfile.mkdtemp() + try: + capsys.readouterr() + assert _recorded(call, monkeypatch, tmp, 32800) == ("CANCEL-LIKE", 1) # 4.10 s + err = capsys.readouterr().err + assert "[wakeup] rec attempt=0 bytes=65644 secs=4.10 end=timeout\n" in err + assert "no speech" not in err and "campful" not in err.lower() + assert not os.listdir(tmp) + finally: + for f in os.listdir(tmp): + os.unlink(os.path.join(tmp, f)) + os.rmdir(tmp) + + def test_the_agi_decision_log_holds_no_words(call, capsys): call.store.set_wakeup("19", "06:30") capsys.readouterr()