#!/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()