Files
LLeMbas-Android/scripts/gen-wake-phrases.py
T
HomerandClaude Fable 5.2 3046ad154a
CI / check (push) Canceled after 0s
Wake phrases the model can hear: greeting x name, generated pieces, sensitivity
"Hey Lembas" could not work well: Lembas is not a word the model knows.

- The phrase is a greeting (Hey, OK, Hello) and a name (Assistant, Computer,
  Google, and ten ordinary names); the default is Hey Assistant and an old
  saved id reads as it.
- Token pieces are generated, not hand-written: fetch-wakeword.py also takes
  the model's bpe.model from the same pinned archive, gen-wake-phrases.py
  encodes every word with it into wake/WakeWords.kt, CI checks the committed
  table against the tokenizer, and WakeWordsTest checks every piece against
  tokens.txt. "OK" is spelled as the model's speech wrote it, OKAY.
  Elizabeth and Benjamin are dropped (four or more single-letter pieces).
- Each keyword line carries a boosting score and a trigger threshold
  (sherpa-onnx's ":boost #threshold"), chosen by a Sensitivity setting:
  Low 1.0/0.35, Normal 1.5/0.25, High 2.0/0.15; short phrases 0.05 stricter.
  numTrailingBlanks is the engine's own 1.
- Settings says the phrase is English whatever the app's language is, and
  that a Google device nearby answers to Google too.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:49:47 +00:00

109 lines
5.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""The wake phrases, spelled in the model's own token pieces -- generated, never written by hand.
scripts/gen-wake-phrases.py write app/src/main/java/.../wake/WakeWords.kt
scripts/gen-wake-phrases.py --check fail if that file is not what this script writes
A wake phrase is a greeting and a name ("Hey Assistant"). The engine is an open-vocabulary
keyword spotter: it hears any phrase it is given as a sequence of the model's BPE pieces, and the
phone has no tokenizer, so the pieces are worked out here with the model's `bpe.model` (fetched
hash-pinned by `scripts/fetch-wakeword.py`; needs `sentencepiece`, pinned in
`scripts/wake-requirements.txt`) and committed as a Kotlin table. `WakeWordsTest` checks every
piece against the model's `tokens.txt` in CI.
The words are English, as the model is (trained on GigaSpeech), and written the way that speech
was transcribed: capitals, and "OK" as the word OKAY, which is one piece of its own.
A name the tokenizer can only spell out is dropped: with four or more single-letter pieces
(E·LI·Z·A·B·E·TH) nearly every step of the phrase is a sound the model has to place alone, which
is where a spotter misses. What was dropped is listed in the generated file.
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
BPE = ROOT / "build/wakeword/bpe.model"
TOKENS = ROOT / "app/src/full/assets/wakeword/tokens.txt"
OUT = ROOT / "app/src/main/java/eu/llembas/android/wake/WakeWords.kt"
# What the person sees -> what the model heard it written as (where the two differ).
SPOKEN = {"OK": "OKAY"}
GREETINGS = ["Hey", "OK", "Hello"]
# The three that say what it is, then ordinary names of three syllables or more, both genders.
NAMES = [
"Assistant", "Computer", "Google",
"Victoria", "Samantha", "Jessica", "Amanda", "Olivia", "Elizabeth",
"Oliver", "Sebastian", "Jonathan", "Benjamin", "Alexander", "Christopher",
]
MAX_SINGLE_LETTERS = 3
def single_letters(pieces: list[str]) -> int:
return sum(1 for piece in pieces if len(piece.lstrip("▁")) == 1)
def main() -> None:
try:
import sentencepiece
except ImportError:
sys.exit("gen-wake-phrases: needs sentencepiece (pip install -r scripts/wake-requirements.txt, in a venv)")
if not BPE.exists():
sys.exit("gen-wake-phrases: no bpe.model -- run scripts/fetch-wakeword.py first")
model = sentencepiece.SentencePieceProcessor(model_file=str(BPE))
known = {line.rsplit(" ", 1)[0] for line in TOKENS.read_text(encoding="utf-8").splitlines()}
def spell(word: str) -> list[str]:
pieces = model.encode(SPOKEN.get(word.upper(), word.upper()), out_type=str)
unknown = [piece for piece in pieces if piece not in known]
if unknown:
sys.exit(f"gen-wake-phrases: {word}: {unknown} not in tokens.txt")
return pieces
greetings = [(word, spell(word)) for word in GREETINGS]
names, dropped = [], []
for word in NAMES:
pieces = spell(word)
(dropped if single_letters(pieces) > MAX_SINGLE_LETTERS else names).append((word, pieces))
# A phrase is spelled as its two words side by side: true of this tokenizer, and checked.
for greeting, g in greetings:
for name, n in names:
whole = model.encode(f"{SPOKEN.get(greeting.upper(), greeting.upper())} {name.upper()}", out_type=str)
if whole != g + n:
sys.exit(f"gen-wake-phrases: {greeting} {name} is not its words' pieces side by side: {whole}")
def row(word: str, pieces: list[str]) -> str:
return f' WakeWord("{word.lower()}", "{word}", "{" ".join(pieces)}"),'
lines = [
"// Generated by scripts/gen-wake-phrases.py from the model's bpe.model. Do not edit: edit the lists there.",
"package eu.llembas.android.wake",
"",
"/**",
" * The words a wake phrase is made of -- a greeting and a name -- each with its spelling in the",
" * model's BPE pieces (`sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01`). English, as the",
" * model is.",
]
if dropped:
lines += [" *", " * Left out, because the tokenizer can only spell them out letter by letter:"]
lines += [f" * {word} ({' '.join(pieces)})" for word, pieces in dropped]
lines += [" */", "object WakeWords {", " val greetings = listOf("]
lines += [row(word, pieces) for word, pieces in greetings]
lines += [" )", "", " val names = listOf("]
lines += [row(word, pieces) for word, pieces in names]
lines += [" )", "}", ""]
text = "\n".join(lines)
if "--check" in sys.argv:
if not OUT.exists() or OUT.read_text(encoding="utf-8") != text:
sys.exit(f"gen-wake-phrases: {OUT.relative_to(ROOT)} is not what the model's tokenizer gives; run this script")
print(f"gen-wake-phrases: {len(greetings)} greetings, {len(names)} names, as generated")
return
OUT.write_text(text, encoding="utf-8")
print(f"gen-wake-phrases: {len(greetings)} greetings x {len(names)} names; dropped: {', '.join(w for w, _ in dropped) or 'none'}")
if __name__ == "__main__":
main()