diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 589994b..676520b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,14 @@ jobs: - name: Wake-word engine (hash-pinned) run: python3 scripts/fetch-wakeword.py + # The wake phrases' token pieces are generated from the model's own tokenizer (bpe.model, + # fetched above); the committed table must be what it gives. + - name: Wake phrases match the model's tokenizer + run: | + python3 -m venv "$RUNNER_TEMP/wake" + "$RUNNER_TEMP/wake/bin/pip" install --quiet --require-hashes --only-binary :all: -r scripts/wake-requirements.txt + "$RUNNER_TEMP/wake/bin/python" scripts/gen-wake-phrases.py --check + - uses: gradle/actions/wrapper-validation@v4 - uses: gradle/actions/setup-gradle@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index 97aeac9..d7d71bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,22 @@ is in alpha and releases come off `main`. ### Changed +- **Wake phrases the engine can hear.** "Hey Lembas" is gone: Lembas is not a word the engine's + model was ever trained on, so it had to be repeated until it happened to land. The phrase is now + a greeting and a name, each chosen in Settings › Wake word: **Hey**, **OK** or **Hello**, then + **Assistant**, **Computer**, **Google** (Settings says a Google device nearby will answer too), + or an ordinary name -- Victoria, Samantha, Jessica, Amanda, Olivia, Oliver, Sebastian, Jonathan, + Alexander, Christopher. The default is "Hey Assistant", and a phrase saved by an earlier beta + becomes it. The phrases are English whatever language the app is in, and Settings says so: the + model knows English speech only. +- **Sensitivity** (Low, Normal, High) in Settings › Wake word: how easily the phrase is taken as + heard, against how often it starts by mistake. Each phrase now goes to the engine with a + boosting score and a trigger threshold (1.0 / 0.35, 1.5 / 0.25, 2.0 / 0.15; a short phrase such + as "OK Computer" is held 0.05 stricter). These are starting values from the engine's + documentation, not yet tuned on phones. +- The phrases' spelling in the model's token pieces is generated from the model's own tokenizer + (`scripts/gen-wake-phrases.py`) and checked against its token table in CI, instead of written by + hand. Elizabeth and Benjamin are left out: the tokenizer can only spell them letter by letter. - **The wake word says what it is doing**, in its notification and under its switch in Settings: *Starting*, *Listening for "…"*, paused and why (screen off, battery saver, assistant open, no microphone permission, or the microphone gives no sound because another app has it or it is diff --git a/README.md b/README.md index acc0dc4..0b11b24 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,11 @@ certificate). The app trusts CAs you installed, as the browser does. digital assistant app. On Samsung phones also set Settings › Advanced features › Side button › Press and hold › Digital assistant. -There is no wake word. Android reserves always-on hotword detection for the system's own -preinstalled assistant; no app from outside can use it. +A wake word is there if you want one, off by default: Settings › Assistant › Wake word, a +greeting and a name in English ("Hey Assistant"). Android reserves its low-power, always-on +hotword detection for the system's own preinstalled assistant, so LLeMbas listens with an +on-device engine in a microphone service, with a notification up the whole time; nothing leaves +the phone before the word. Not in the F-Droid build. ## Build diff --git a/app/src/full/java/eu/llembas/android/wake/Engine.kt b/app/src/full/java/eu/llembas/android/wake/Engine.kt index a8e8a6b..88f6374 100644 --- a/app/src/full/java/eu/llembas/android/wake/Engine.kt +++ b/app/src/full/java/eu/llembas/android/wake/Engine.kt @@ -51,6 +51,9 @@ object WakeEngine { numThreads = 1, ), keywordsFile = file.path, + // The word counts once one frame of something else follows it (the engine's own + // default; the Kotlin wrapper's is two), so a question may follow straight on. + numTrailingBlanks = 1, ) return SherpaDetector(KeywordSpotter(null, config)) } catch (e: Throwable) { diff --git a/app/src/main/java/eu/llembas/android/auth/Instances.kt b/app/src/main/java/eu/llembas/android/auth/Instances.kt index ea58522..f1be0ec 100644 --- a/app/src/main/java/eu/llembas/android/auth/Instances.kt +++ b/app/src/main/java/eu/llembas/android/auth/Instances.kt @@ -89,8 +89,10 @@ data class Prefs( val assistantConversation: Boolean = true, /** Listen for a wake word on the phone (WakeWordService). Off until the person turns it on. */ val wakeWord: Boolean = false, - /** Which of WakePhrases.all. */ - val wakePhrase: String = "hey_lembas", + /** Which of WakePhrases.all, as `greeting_name`; an id that is no phrase any more reads as the default. */ + val wakePhrase: String = "hey_assistant", + /** WakeSensitivity's id: low, normal or high. */ + val wakeSensitivity: String = "normal", /** Listen only while the screen is on. */ val wakeScreenOnly: Boolean = true, /** The assistant may read the notifications when asked (with Android's notification access). */ diff --git a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt index c65b970..434a70e 100644 --- a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt @@ -53,6 +53,7 @@ import androidx.compose.material.icons.filled.Security import androidx.compose.material.icons.filled.SystemUpdate import androidx.compose.material.icons.filled.Timer import androidx.compose.material.icons.filled.Translate +import androidx.compose.material.icons.filled.Tune import androidx.compose.material.icons.filled.Update import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -106,10 +107,13 @@ import eu.llembas.android.update.offersBetas import eu.llembas.android.wake.WakeEngine import eu.llembas.android.wake.WakeFailure import eu.llembas.android.wake.WakePause +import eu.llembas.android.wake.WakePhrase import eu.llembas.android.wake.WakePhrases +import eu.llembas.android.wake.WakeSensitivity import eu.llembas.android.wake.WakeState import eu.llembas.android.wake.WakeStatus import eu.llembas.android.wake.WakeWordService +import eu.llembas.android.wake.WakeWords import eu.llembas.android.wake.wakeTitle import kotlinx.coroutines.launch @@ -129,6 +133,7 @@ interface SettingsActions { fun assistantConversation(on: Boolean) {} fun wakeWord(on: Boolean) {} fun wakePhrase(id: String) {} + fun wakeSensitivity(id: String) {} fun wakeScreenOnly(on: Boolean) {} fun batterySettings() {} fun notificationSummaries(on: Boolean) {} @@ -272,6 +277,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) { scope.launch { store.savePrefs { it.copy(wakePhrase = id) } } } + override fun wakeSensitivity(id: String) { + scope.launch { store.savePrefs { it.copy(wakeSensitivity = id) } } + } + override fun wakeScreenOnly(on: Boolean) { scope.launch { store.savePrefs { it.copy(wakeScreenOnly = on) } } } @@ -373,6 +382,15 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) { fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -> Unit = {}) { val palette = LocalPalette.current var choosingLanguage by remember { mutableStateOf(false) } + var choosingWake by remember { mutableStateOf(null) } + choosingWake?.let { which -> + ModalBottomSheet(onDismissRequest = { choosingWake = null }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { + WakeChoices(which, state.prefs, onPick = { pick -> + choosingWake = null + pick(actions) + }) + } + } if (choosingLanguage) { ModalBottomSheet(onDismissRequest = { choosingLanguage = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) { LanguageChoices(state.prefs, onPick = { @@ -539,7 +557,7 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () - modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), ) } - item { WakeWordGroup(state, actions) } + item { WakeWordGroup(state, actions, onChoose = { choosingWake = it }) } item { NotificationSummaryGroup(state, actions) } item { PhoneActionsGroup(state, actions) } item { @@ -623,12 +641,16 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () - } } +/** The three things about the wake word that are chosen from a list, each in a sheet. */ +enum class WakeChoice { Greeting, Name, Sensitivity } + /** - * The wake word: off until turned on; the phrase (the engine's own, English); only while the - * screen is on; and what it costs and why a phone may stop it, said before it is turned on. + * The wake word: off until turned on; the phrase as a greeting and a name (English, words the + * engine's model knows); how easily it is taken as heard; only while the screen is on; and what + * it costs and why a phone may stop it, said before it is turned on. */ @Composable -private fun WakeWordGroup(state: SettingsState, actions: SettingsActions) { +private fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onChoose: (WakeChoice) -> Unit) { val palette = LocalPalette.current val on = state.prefs.wakeWord && state.wakeAvailable Group(stringResource(R.string.wake_word)) { @@ -662,16 +684,37 @@ private fun WakeWordGroup(state: SettingsState, actions: SettingsActions) { ) } if (state.wakeAvailable) { - WakePhrases.all.forEach { phrase -> - Rule() - SettingRow( - Icons.Filled.RecordVoiceOver, - "“${phrase.words}”", - showIcon = false, - onClick = { actions.wakePhrase(phrase.id) }, - trailing = { RadioButton(selected = state.prefs.wakePhrase == phrase.id, onClick = { actions.wakePhrase(phrase.id) }) }, - ) - } + val phrase = WakePhrases.byId(state.prefs.wakePhrase) + Rule() + SettingRow( + Icons.Filled.RecordVoiceOver, + "“${phrase.words}”", + subtitle = stringResource(R.string.wake_phrase_line), + onClick = { onChoose(WakeChoice.Name) }, + ) + Rule() + SettingRow( + Icons.Filled.RecordVoiceOver, + stringResource(R.string.wake_greeting), + subtitle = phrase.greeting.words, + showIcon = false, + onClick = { onChoose(WakeChoice.Greeting) }, + ) + Rule() + SettingRow( + Icons.Filled.RecordVoiceOver, + stringResource(R.string.wake_name), + subtitle = if (phrase.name.id == GOOGLE) phrase.name.words + " · " + stringResource(R.string.wake_name_google_line) else phrase.name.words, + showIcon = false, + onClick = { onChoose(WakeChoice.Name) }, + ) + Rule() + SettingRow( + Icons.Filled.Tune, + stringResource(R.string.wake_sensitivity), + subtitle = stringResource(sensitivityLabel(WakeSensitivity.byId(state.prefs.wakeSensitivity))), + onClick = { onChoose(WakeChoice.Sensitivity) }, + ) Rule() SettingRow( Icons.Filled.ScreenLockPortrait, @@ -860,6 +903,84 @@ private fun languageLabel(prefs: Prefs): String = when (prefs.language) { else -> AppLanguage.name(prefs.language) ?: stringResource(R.string.language_account) } +private const val GOOGLE = "google" + +private fun sensitivityLabel(sensitivity: WakeSensitivity): Int = when (sensitivity) { + WakeSensitivity.Low -> R.string.wake_sensitivity_low + WakeSensitivity.Normal -> R.string.wake_sensitivity_normal + WakeSensitivity.High -> R.string.wake_sensitivity_high +} + +/** + * One of the wake word's lists, as a sheet: the greetings, the names (Google's says that a Google + * device nearby answers to it too), or the sensitivity with what each step trades. A pick is + * handed back as what to do with the actions. + */ +@Composable +fun WakeChoices(which: WakeChoice, prefs: Prefs, onPick: ((SettingsActions) -> Unit) -> Unit) { + val phrase = WakePhrases.byId(prefs.wakePhrase) + val google = stringResource(R.string.wake_name_google_line) + val title = stringResource( + when (which) { + WakeChoice.Greeting -> R.string.wake_greeting + WakeChoice.Name -> R.string.wake_name + WakeChoice.Sensitivity -> R.string.wake_sensitivity + }, + ) + // id, words, a line under them, whether it is the one chosen. + val choices: List = when (which) { + WakeChoice.Greeting -> WakeWords.greetings.map { Choice(WakePhrase(it, phrase.name).id, it.words, null, it.id == phrase.greeting.id) } + + WakeChoice.Name -> WakeWords.names.map { + Choice(WakePhrase(phrase.greeting, it).id, it.words, if (it.id == GOOGLE) google else null, it.id == phrase.name.id) + } + + WakeChoice.Sensitivity -> WakeSensitivity.entries.map { + val line = when (it) { + WakeSensitivity.Low -> R.string.wake_sensitivity_low_line + WakeSensitivity.Normal -> R.string.wake_sensitivity_normal_line + WakeSensitivity.High -> R.string.wake_sensitivity_high_line + } + Choice(it.id, stringResource(sensitivityLabel(it)), stringResource(line), it.id == WakeSensitivity.byId(prefs.wakeSensitivity).id) + } + } + ChoiceList(title, choices) { id -> + onPick { actions -> if (which == WakeChoice.Sensitivity) actions.wakeSensitivity(id) else actions.wakePhrase(id) } + } +} + +private data class Choice(val id: String, val title: String, val subtitle: String?, val chosen: Boolean) + +/** A sheet's list of choices: a title, then rows of words that give and a radio button that keeps its size. */ +@Composable +private fun ChoiceList(title: String, choices: List, onPick: (String) -> Unit) { + val palette = LocalPalette.current + LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) { + item { + Text(title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp)) + } + choices.forEach { choice -> + item(key = choice.id) { + Row( + Modifier + .fillMaxWidth() + .clickable { onPick(choice.id) } + .heightIn(min = 56.dp) + .padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text(choice.title, style = MaterialTheme.typography.bodyLarge) + choice.subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) } + } + Spacer(Modifier.width(12.dp)) + RadioButton(selected = choice.chosen, onClick = { onPick(choice.id) }) + } + } + } + } +} + /** * Settings › Language, as a sheet: the account's language (the default), the phone's, then every * language the app has, each named in itself so a person who cannot read the current one still diff --git a/app/src/main/java/eu/llembas/android/wake/Wake.kt b/app/src/main/java/eu/llembas/android/wake/Wake.kt index a30800a..65b6f82 100644 --- a/app/src/main/java/eu/llembas/android/wake/Wake.kt +++ b/app/src/main/java/eu/llembas/android/wake/Wake.kt @@ -9,31 +9,62 @@ import kotlinx.coroutines.flow.update import java.io.File import java.io.IOException import java.io.InputStream +import java.util.Locale + +/** One word of a wake phrase: its [id], how it is written for the person, and its spelling in the model's [pieces]. */ +data class WakeWord(val id: String, val words: String, val pieces: String) /** - * A wake word the engine ships: what the person says ([words]), the engine's spelling of it - * ([tokens], the model's BPE pieces, worked out once with its `bpe.model` -- the phone has no - * tokenizer), and the id Settings keeps. + * A wake phrase: a greeting and a name ("Hey Assistant"). What the person says ([words]), the + * engine's spelling of it ([tokens], the model's BPE pieces -- generated with its `bpe.model` by + * `scripts/gen-wake-phrases.py`, since the phone has no tokenizer), and the [id] Settings keeps. * - * Only phrases from this list can be chosen: an open-vocabulary spotter hears any phrase it can - * spell, but how well each one works was not measured, and a free text box would invite one that - * fires on every other sentence. English only: the model is trained on English speech. + * Only words from [WakeWords] can be chosen: an open-vocabulary spotter hears any phrase it can + * spell, but one it was never trained to hear (a made-up name) has to be repeated until it lands, + * and a free text box would invite one that fires on every other sentence. English only: the + * model is trained on English speech. */ -data class WakePhrase(val id: String, val words: String, val tokens: String) +data class WakePhrase(val greeting: WakeWord, val name: WakeWord) { + val id: String get() = "${greeting.id}_${name.id}" + val words: String get() = "${greeting.words} ${name.words}" + val tokens: String get() = "${greeting.pieces} ${name.pieces}" +} object WakePhrases { - val all = listOf( - WakePhrase("hey_lembas", "Hey Lembas", "▁HE Y ▁LE M B AS"), - WakePhrase("ok_lembas", "OK Lembas", "▁O K ▁LE M B AS"), - WakePhrase("hello_lembas", "Hello Lembas", "▁HE LL O ▁LE M B AS"), - WakePhrase("hey_assistant", "Hey Assistant", "▁HE Y ▁AS S IST ANT"), - ) + /** "Hey Assistant". */ + val default: WakePhrase = WakePhrase(WakeWords.greetings.first { it.id == "hey" }, WakeWords.names.first { it.id == "assistant" }) - val default: WakePhrase get() = all.first() + val all: List = WakeWords.greetings.flatMap { greeting -> WakeWords.names.map { WakePhrase(greeting, it) } } + /** + * The phrase Settings saved as [id] (`greeting_name`). An id that is no longer a phrase -- + * the "Lembas" ones of the first wake word, which the model could not hear -- is the default. + */ fun byId(id: String): WakePhrase = all.firstOrNull { it.id == id } ?: default } +/** + * How easily the phrase is taken as heard: Settings › Wake word › Sensitivity. + * + * The engine has two numbers per keyword (sherpa-onnx's keyword-spotting documentation): a + * boosting score that keeps the phrase's path alive in the search ([boost], larger is easier), + * and a trigger threshold, the least probability the heard pieces must reach ([threshold], 0 to + * 1, lower is easier). Normal is the engine's own default threshold with the boost its + * documentation uses for a two-word phrase; Low takes that documentation's stricter example + * (0.35), High goes as far below the default as Low goes above it. Starting values: nobody has + * measured them on a phone yet. + */ +enum class WakeSensitivity(val id: String, val boost: Float, val threshold: Float) { + Low("low", 1.0f, 0.35f), + Normal("normal", 1.5f, 0.25f), + High("high", 2.0f, 0.15f), + ; + + companion object { + fun byId(id: String): WakeSensitivity = entries.firstOrNull { it.id == id } ?: Normal + } +} + /** * The engine, as the service sees it: 16 kHz mono samples in, the phrase out when it was heard. * Everything happens on the phone; [accept] neither records nor sends anything. @@ -171,8 +202,21 @@ fun wakeLine(context: Context, state: WakeState): String? = when (state) { else -> null } -/** The engine's keywords file for [phrase]: its pieces, then `@` and the id the engine answers with. */ -fun wakeKeywords(phrase: WakePhrase): String = "${phrase.tokens} @${phrase.id}\n" +/** + * The engine's keywords file for [phrase]: its pieces, `:` the boosting score, `#` the trigger + * threshold, then `@` and the id the engine answers with (sherpa-onnx's syntax; no space after + * `:` or `#`). A phrase of fewer than five pieces is short enough to turn up inside other speech, + * so it has to be a little surer ([SHORT_PHRASE_STRICTER]). + */ +fun wakeKeywords(phrase: WakePhrase, sensitivity: WakeSensitivity = WakeSensitivity.Normal): String { + val short = phrase.tokens.split(' ').size < SHORT_PHRASE_PIECES + val threshold = sensitivity.threshold + if (short) SHORT_PHRASE_STRICTER else 0f + // Locale.ROOT: a decimal comma would not be a number to the engine. + return String.format(Locale.ROOT, "%s :%.1f #%.2f @%s\n", phrase.tokens, sensitivity.boost, threshold, phrase.id) +} + +private const val SHORT_PHRASE_PIECES = 5 +private const val SHORT_PHRASE_STRICTER = 0.05f /** * Every piece of [keywords] must be in the model's token table ([tokens], `tokens.txt`: a piece diff --git a/app/src/main/java/eu/llembas/android/wake/WakeWordService.kt b/app/src/main/java/eu/llembas/android/wake/WakeWordService.kt index 4e81639..5723215 100644 --- a/app/src/main/java/eu/llembas/android/wake/WakeWordService.kt +++ b/app/src/main/java/eu/llembas/android/wake/WakeWordService.kt @@ -145,7 +145,7 @@ class WakeWordService : LifecycleService() { null } else { val phrase = WakePhrases.byId(prefs.wakePhrase) - WakePlan(phrase, wakeKeywords(phrase), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic)) + WakePlan(phrase, wakeKeywords(phrase, WakeSensitivity.byId(prefs.wakeSensitivity)), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic)) } } val listener = WakeListener( diff --git a/app/src/main/java/eu/llembas/android/wake/WakeWords.kt b/app/src/main/java/eu/llembas/android/wake/WakeWords.kt new file mode 100644 index 0000000..9b3c31f --- /dev/null +++ b/app/src/main/java/eu/llembas/android/wake/WakeWords.kt @@ -0,0 +1,35 @@ +// 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. + * + * Left out, because the tokenizer can only spell them out letter by letter: + * Elizabeth (▁E LI Z A B E TH) + * Benjamin (▁BE N J A M IN) + */ +object WakeWords { + val greetings = listOf( + WakeWord("hey", "Hey", "▁HE Y"), + WakeWord("ok", "OK", "▁OKAY"), + WakeWord("hello", "Hello", "▁HE LL O"), + ) + + val names = listOf( + WakeWord("assistant", "Assistant", "▁AS S IST ANT"), + WakeWord("computer", "Computer", "▁COMP U TER"), + WakeWord("google", "Google", "▁GO O G LE"), + WakeWord("victoria", "Victoria", "▁VI C T OR IA"), + WakeWord("samantha", "Samantha", "▁SA MAN TH A"), + WakeWord("jessica", "Jessica", "▁JE S S IC A"), + WakeWord("amanda", "Amanda", "▁A MAN D A"), + WakeWord("olivia", "Olivia", "▁O LI VI A"), + WakeWord("oliver", "Oliver", "▁O LI VER"), + WakeWord("sebastian", "Sebastian", "▁SE B AS T IAN"), + WakeWord("jonathan", "Jonathan", "▁JO N A TH AN"), + WakeWord("alexander", "Alexander", "▁A LE X AN DER"), + WakeWord("christopher", "Christopher", "▁ CH R IST O PH ER"), + ) +} diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 0f07b7a..496dfea 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -401,6 +401,17 @@ Naslouchat budicímu slovu Ve výchozím stavu vypnuto. Řekněte frázi a asistent se otevře a poslouchá, nad jakoukoli aplikací na obrazovce. V tomto sestavení není. Sestavení pro F-Droid nemá modul pro budicí slovo, protože F-Droid sestavuje každou knihovnu ze zdrojů; sestavení z llembas.eu ho má. + Tohle říkáte. Anglicky, ať je aplikace v jakémkoli jazyce: modul zná jen anglickou řeč. + Oslovení + Jméno + Ozve se i telefon nebo reproduktor Google poblíž. + Citlivost + Nízká + Omylem se spustí nejméně často. Frázi možná budete muset říct zřetelněji nebo dvakrát. + Normální + Vlastní nastavení modulu. + Vysoká + Slyší vás nejsnáze, i z větší dálky. Omylem se spustí častěji. Jen při zapnuté obrazovce Vypnuto: poslouchá i při zhasnuté obrazovce, za cenu vyšší spotřeby baterie. Nechat běžet na pozadí diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index a9f53ce..319ce45 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -401,6 +401,17 @@ Auf ein Aktivierungswort hören Standardmäßig aus. Sag den Satz, und der Assistent öffnet sich zuhörend über der App auf dem Bildschirm. Nicht in diesem Build. Der F-Droid-Build hat keine Aktivierungswort-Engine, weil F-Droid jede Bibliothek aus dem Quellcode baut; der Build von llembas.eu hat eine. + Das sagst du. Auf Englisch, egal in welcher Sprache die App ist: Die Engine kennt nur englische Sprache. + Anrede + Name + Ein Google-Telefon oder -Lautsprecher in der Nähe antwortet ebenfalls. + Empfindlichkeit + Niedrig + Startet am seltensten versehentlich. Du musst den Satz vielleicht deutlicher oder zweimal sagen. + Normal + Die eigene Einstellung der Engine. + Hoch + Hört dich am leichtesten, auch aus größerer Entfernung. Startet öfter versehentlich. Nur bei eingeschaltetem Bildschirm Aus: Es hört auch bei ausgeschaltetem Bildschirm zu, was mehr Akku kostet. Im Hintergrund laufen lassen diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 9c636b3..6786782 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -401,6 +401,17 @@ Escuchar una palabra de activación Desactivado por defecto. Di la frase y el asistente se abre escuchando, sobre la app que esté en pantalla. No en esta versión. La versión de F-Droid no tiene motor de palabra de activación, porque F-Droid compila cada biblioteca desde el código fuente; la de llembas.eu sí lo tiene. + Lo que dices. En inglés, sea cual sea el idioma de la app: el motor solo conoce el habla inglesa. + Saludo + Nombre + Un teléfono o altavoz de Google cercano también responderá. + Sensibilidad + Baja + Es la que menos se activa por error. Puede que tengas que decir la frase con más claridad, o dos veces. + Normal + El ajuste propio del motor. + Alta + Te oye con más facilidad, también desde más lejos. Se activa por error más a menudo. Solo con la pantalla encendida Desactivado: también escucha con la pantalla apagada, con más gasto de batería. Dejar que funcione en segundo plano diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index c7152d9..a138fbb 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -401,6 +401,17 @@ Écouter un mot d’activation Désactivé par défaut. Dites la phrase et l’assistant s’ouvre en écoute, par-dessus l’app à l’écran. Pas dans cette version. La version F-Droid n’a pas de moteur de mot d’activation, car F-Droid compile chaque bibliothèque depuis les sources ; celle de llembas.eu en a un. + Ce que vous dites. En anglais, quelle que soit la langue de l’app : le moteur ne connaît que la parole anglaise. + Salutation + Nom + Un téléphone ou une enceinte Google à proximité répondra aussi. + Sensibilité + Faible + Se déclenche le moins souvent par erreur. Vous devrez peut-être dire la phrase plus distinctement, ou deux fois. + Normale + Le réglage propre au moteur. + Élevée + Vous entend le plus facilement, même de plus loin. Se déclenche plus souvent par erreur. Seulement écran allumé Désactivé : il écoute aussi écran éteint, au prix de plus de batterie. Le laisser tourner en arrière-plan diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index bbc813d..debd685 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -401,6 +401,17 @@ Ébresztőszó figyelése Alapból ki van kapcsolva. Mondd ki a kifejezést, és az asszisztens figyelve megnyílik a képernyőn lévő alkalmazás fölött. Ebben a változatban nincs. Az F-Droid-változatban nincs ébresztőszó-motor, mert az F-Droid minden könyvtárat forrásból fordít; a llembas.eu-s változatban van. + Ezt mondod. Angolul, bármilyen nyelvű is az alkalmazás: a motor csak az angol beszédet ismeri. + Megszólítás + Név + A közelben lévő Google-telefon vagy -hangszóró is válaszolni fog. + Érzékenység + Alacsony + A legritkábban indul el tévedésből. Lehet, hogy tisztábban vagy kétszer kell kimondanod a kifejezést. + Normál + A motor saját beállítása. + Magas + A legkönnyebben hall meg, távolabbról is. Gyakrabban indul el tévedésből. Csak bekapcsolt képernyőnél Kikapcsolva kikapcsolt képernyőnél is figyel, ami több akkumulátort fogyaszt. Futhasson a háttérben diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 4316f06..3d0fbb5 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -401,6 +401,17 @@ Ascolta una parola di attivazione Disattivata per impostazione predefinita. Di’ la frase e l’assistente si apre in ascolto, sopra l’app sullo schermo. Non in questa build. La build F-Droid non ha un motore per la parola di attivazione, perché F-Droid compila ogni libreria dal sorgente; la build di llembas.eu ce l’ha. + Quello che dici. In inglese, qualunque sia la lingua dell’app: il motore conosce solo il parlato inglese. + Saluto + Nome + Risponderà anche un telefono o un altoparlante Google nelle vicinanze. + Sensibilità + Bassa + È quella che si attiva per errore meno spesso. Potresti dover dire la frase più chiaramente, o due volte. + Normale + L’impostazione propria del motore. + Alta + Ti sente più facilmente, anche da più lontano. Si attiva per errore più spesso. Solo a schermo acceso Disattivato: ascolta anche a schermo spento, con più consumo di batteria. Lascialo funzionare in background diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 4d4951e..303ca38 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -401,6 +401,17 @@ Nasłuchuj słowa aktywującego Domyślnie wyłączone. Powiedz frazę, a asystent otworzy się i zacznie słuchać, nad aplikacją na ekranie. Nie w tej wersji. Wersja z F-Droid nie ma silnika słowa aktywującego, bo F-Droid buduje każdą bibliotekę ze źródeł; wersja z llembas.eu go ma. + To, co mówisz. Po angielsku, niezależnie od języka aplikacji: silnik zna tylko mowę angielską. + Powitanie + Imię + Odpowie też telefon lub głośnik Google w pobliżu. + Czułość + Niska + Najrzadziej uruchamia się przez pomyłkę. Być może trzeba będzie powiedzieć frazę wyraźniej albo dwa razy. + Normalna + Własne ustawienie silnika. + Wysoka + Słyszy Cię najłatwiej, także z większej odległości. Częściej uruchamia się przez pomyłkę. Tylko przy włączonym ekranie Wyłączone: słucha także przy wyłączonym ekranie, kosztem baterii. Pozwól działać w tle diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 7d06649..bf767d3 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -401,6 +401,17 @@ Počúvať budiace slovo Predvolene vypnuté. Povedzte frázu a asistent sa otvorí a počúva, nad akoukoľvek aplikáciou na obrazovke. V tomto zostavení nie je. Zostavenie pre F-Droid nemá modul pre budiace slovo, pretože F-Droid zostavuje každú knižnicu zo zdrojov; zostavenie z llembas.eu ho má. + Toto hovoríte. Po anglicky, nech je aplikácia v akomkoľvek jazyku: modul pozná len anglickú reč. + Oslovenie + Meno + Ozve sa aj telefón alebo reproduktor Google nablízku. + Citlivosť + Nízka + Omylom sa spustí najmenej často. Frázu možno budete musieť povedať zreteľnejšie alebo dvakrát. + Normálna + Vlastné nastavenie modulu. + Vysoká + Počuje vás najľahšie, aj z väčšej diaľky. Omylom sa spustí častejšie. Len pri zapnutej obrazovke Vypnuté: počúva aj pri zhasnutej obrazovke, za cenu vyššej spotreby batérie. Nechať bežať na pozadí diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 17f1d26..75de681 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -403,6 +403,17 @@ Listen for a wake word Off by default. Say the phrase and the assistant opens, listening, over whatever app is on screen. Not in this build. The F-Droid build has no wake-word engine, because F-Droid builds every library from source; the build from llembas.eu has one. + What you say. In English, whatever language the app is in: the engine only knows English speech. + Greeting + Name + A Google phone or speaker nearby will answer too. + Sensitivity + Low + Starts by mistake least often. You may have to say the phrase more clearly, or twice. + Normal + The engine\'s own setting. + High + Hears you most easily, also from further away. Starts by mistake more often. Only while the screen is on Off: it listens with the screen off too, at more cost to the battery. Let it run in the background diff --git a/app/src/test/java/eu/llembas/android/WakeListenerTest.kt b/app/src/test/java/eu/llembas/android/WakeListenerTest.kt index e35729b..fbd963c 100644 --- a/app/src/test/java/eu/llembas/android/WakeListenerTest.kt +++ b/app/src/test/java/eu/llembas/android/WakeListenerTest.kt @@ -206,7 +206,7 @@ class WakeListenerTest { ) val plans = MutableStateFlow(plan) val job = launch(Dispatchers.Default) { listener.follow(plans) } - val other = WakePhrases.all.first { it.id != assistant.id } + val other = WakePhrases.byId("ok_computer") repeat(5) { round -> val phrase = if (round % 2 == 0) other else assistant said(now, WakeState.Listening(if (round % 2 == 0) assistant.words else other.words)) diff --git a/app/src/test/java/eu/llembas/android/WakeTest.kt b/app/src/test/java/eu/llembas/android/WakeTest.kt index efce69e..878d3d8 100644 --- a/app/src/test/java/eu/llembas/android/WakeTest.kt +++ b/app/src/test/java/eu/llembas/android/WakeTest.kt @@ -1,9 +1,13 @@ package eu.llembas.android +import eu.llembas.android.api.LembasJson +import eu.llembas.android.auth.Prefs import eu.llembas.android.wake.WakeError import eu.llembas.android.wake.WakeFailure import eu.llembas.android.wake.WakePause import eu.llembas.android.wake.WakePhrases +import eu.llembas.android.wake.WakeSensitivity +import eu.llembas.android.wake.WakeWords import eu.llembas.android.wake.checkKeywords import eu.llembas.android.wake.unpackWakeModel import eu.llembas.android.wake.wakeBackoff @@ -19,6 +23,7 @@ import org.junit.rules.TemporaryFolder import java.io.File import java.io.FileNotFoundException import java.io.InputStream +import java.util.Locale class WakeTest { @get:Rule @@ -79,10 +84,47 @@ class WakeTest { } @Test - fun theKeywordsFileNamesThePhraseForTheEngine() { - val phrase = WakePhrases.byId("hey_assistant") - assertTrue(wakeKeywords(phrase).startsWith("▁HE Y ▁AS S IST ANT ")) - assertTrue(wakeKeywords(phrase).endsWith("@hey_assistant\n")) + fun theKeywordsFileCarriesBoostAndThresholdInTheEnginesSyntax() { + val assistant = WakePhrases.byId("hey_assistant") + assertEquals("▁HE Y ▁AS S IST ANT :1.5 #0.25 @hey_assistant\n", wakeKeywords(assistant)) + assertEquals("▁HE Y ▁AS S IST ANT :1.0 #0.35 @hey_assistant\n", wakeKeywords(assistant, WakeSensitivity.Low)) + assertEquals("▁HE Y ▁AS S IST ANT :2.0 #0.15 @hey_assistant\n", wakeKeywords(assistant, WakeSensitivity.High)) + // Four pieces: short enough to turn up inside other speech, so it must be a little surer. + assertEquals("▁OKAY ▁COMP U TER :1.5 #0.30 @ok_computer\n", wakeKeywords(WakePhrases.byId("ok_computer"))) + // A phone set to a language with a decimal comma still writes numbers the engine reads. + val phone = Locale.getDefault() + try { + Locale.setDefault(Locale.forLanguageTag("sk-SK")) + assertEquals("▁HE Y ▁AS S IST ANT :1.5 #0.25 @hey_assistant\n", wakeKeywords(assistant)) + } finally { + Locale.setDefault(phone) + } + assertEquals(WakeSensitivity.Normal, WakeSensitivity.byId("nonsense")) + } + + @Test + fun aPhraseIsAGreetingAndAName() { + assertEquals("Hey Assistant", WakePhrases.default.words) + assertEquals(WakeWords.greetings.size * WakeWords.names.size, WakePhrases.all.size) + assertEquals(WakePhrases.all.size, WakePhrases.all.map { it.id }.toSet().size) + assertEquals("OK Google", WakePhrases.byId("ok_google").words) + assertEquals("Hello Samantha", WakePhrases.byId("hello_samantha").words) + // Nothing the model cannot hear is offered. + assertFalse(WakePhrases.all.any { "lembas" in it.id }) + } + + @Test + fun aSavedPhraseThatIsGoneBecomesHeyAssistant() { + for (old in listOf("hey_lembas", "ok_lembas", "hello_lembas", "nonsense", "")) assertEquals("hey_assistant", WakePhrases.byId(old).id) + assertEquals("hey_assistant", WakePhrases.byId("hey_assistant").id) + // Settings as beta.7 saved them: the old phrase id, no sensitivity yet. + val saved = LembasJson.decodeFromString(Prefs.serializer(), """{"wakeWord":true,"wakePhrase":"hey_lembas","wakeScreenOnly":false}""") + assertTrue(saved.wakeWord) + assertFalse(saved.wakeScreenOnly) + assertEquals("Hey Assistant", WakePhrases.byId(saved.wakePhrase).words) + assertEquals(WakeSensitivity.Normal, WakeSensitivity.byId(saved.wakeSensitivity)) + // And a phone that never had the wake word starts on the same phrase. + assertEquals("hey_assistant", Prefs().wakePhrase) } @Test @@ -104,7 +146,6 @@ class WakeTest { @Test fun phrasesAreSpelledInTheModelsPieces() { - assertEquals("hey_lembas", WakePhrases.byId("nonsense").id) // Every piece of the spelling starts a word with ▁ or continues one; no spaces inside a word. for (phrase in WakePhrases.all) { assertTrue(phrase.tokens.startsWith("▁")) diff --git a/app/src/test/java/eu/llembas/android/WakeWordsTest.kt b/app/src/test/java/eu/llembas/android/WakeWordsTest.kt new file mode 100644 index 0000000..ee9b421 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/WakeWordsTest.kt @@ -0,0 +1,53 @@ +package eu.llembas.android + +import eu.llembas.android.wake.WakePhrases +import eu.llembas.android.wake.WakeSensitivity +import eu.llembas.android.wake.WakeWords +import eu.llembas.android.wake.checkKeywords +import eu.llembas.android.wake.wakeKeywords +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +/** + * The generated table (`wake/WakeWords.kt`, by `scripts/gen-wake-phrases.py`) against the model + * that will hear it: every piece of every phrase must be in the model's `tokens.txt` -- the + * engine ends the app on one that is not. The table is the model's, so the test reads the very + * file the build puts into the APK (`scripts/fetch-wakeword.py` fetches it before Gradle). + */ +class WakeWordsTest { + private val tokens: String by lazy { + val file = File("src/full/assets/wakeword/tokens.txt") + check(file.isFile) { "no ${file.path}: run scripts/fetch-wakeword.py before the tests" } + file.readText() + } + + @Test + fun everyPieceOfEveryPhraseIsInTheModel() { + val known = tokens.lineSequence().map { it.substringBeforeLast(' ') }.toSet() + assertTrue(known.size > 400) + for (word in WakeWords.greetings + WakeWords.names) { + for (piece in word.pieces.split(' ')) assertTrue("${word.words}: the model has no piece \"$piece\"", piece in known) + } + // And as the engine gets them: the whole keywords line of every phrase, at every sensitivity. + for (phrase in WakePhrases.all) { + for (sensitivity in WakeSensitivity.entries) checkKeywords(wakeKeywords(phrase, sensitivity), tokens) + } + } + + @Test + fun theTableIsWhatTheSettingsOffer() { + assertEquals(listOf("Hey", "OK", "Hello"), WakeWords.greetings.map { it.words }) + assertEquals(listOf("Assistant", "Computer", "Google"), WakeWords.names.take(3).map { it.words }) + // Ids are what Settings saves: lower case, one word, unique. + val ids = (WakeWords.greetings + WakeWords.names).map { it.id } + assertEquals(ids.size, ids.toSet().size) + assertTrue(ids.all { id -> id.isNotEmpty() && id.all { it in 'a'..'z' } }) + // Written as the model's speech was: capitals only, each word starting with the word mark. + for (word in WakeWords.greetings + WakeWords.names) { + assertTrue(word.pieces.startsWith("▁")) + assertTrue(word.pieces.all { it == '▁' || it == ' ' || it in 'A'..'Z' }) + } + } +} diff --git a/scripts/fetch-wakeword.py b/scripts/fetch-wakeword.py index 82b780b..7e19805 100755 --- a/scripts/fetch-wakeword.py +++ b/scripts/fetch-wakeword.py @@ -10,6 +10,10 @@ which the int8 encoder, decoder and joiner and the token table go into the APK's `version` file (a hash of the four pinned hashes): the app copies the model out of the APK once per version, so a new model replaces the old one on the phone. +The same archive carries the model's `bpe.model`, the tokenizer its token pieces come from. It +does not go into the APK (the phone has no tokenizer): it is written to `build/wakeword/`, where +`scripts/gen-wake-phrases.py` reads it to spell the wake phrases. + Neither file is in the repository: prebuilt binaries are not source. CI runs this before Gradle; an F-Droid build, which builds every library from source, uses the `fdroid` flavour, which has no engine (`app/src/fdroid/.../wake/Engine.kt`). Every download is checked against the SHA-256 @@ -42,6 +46,9 @@ FILES = { "joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx": ("joiner.int8.onnx", "eae9da0c7e1e6c6a3f4cc42d167899c388f6c6701b94cb96320e4f55df79624c"), "tokens.txt": ("tokens.txt", "fd2ded4050a55d2b1578870ba8697d02371980217806b7558bd0a5cc60f3ba53"), } +# The model's tokenizer, from the same archive: for scripts/gen-wake-phrases.py, not for the APK. +BPE = ROOT / "build/wakeword/bpe.model" +BPE_SHA = "c8a2a0129c4ab8e463164c142f82d25649661b122c8cd0b7aab5c9e80b90ad24" # What the app keys its copy of the model by: changes whenever a pinned file does. MODEL_VERSION = hashlib.sha256("".join(sorted(d for _, d in FILES.values())).encode()).hexdigest()[:16] @@ -71,6 +78,7 @@ def main() -> None: print(f"fetch-wakeword: {AAR.relative_to(ROOT)}") wanted = {ASSETS / name: digest for name, digest in FILES.values()} version = ASSETS / "version" + wanted[BPE] = BPE_SHA if all(p.exists() and sha(p.read_bytes()) == d for p, d in wanted.items()): version.write_text(MODEL_VERSION + "\n") print("fetch-wakeword: engine and model are in place") @@ -82,6 +90,11 @@ def main() -> None: if sha(data) != digest: sys.exit(f"fetch-wakeword: {source} in the archive is not the pinned file") (ASSETS / name).write_bytes(data) + bpe = archive.extractfile(f"{MODEL}/bpe.model").read() + if sha(bpe) != BPE_SHA: + sys.exit("fetch-wakeword: bpe.model in the archive is not the pinned file") + BPE.parent.mkdir(parents=True, exist_ok=True) + BPE.write_bytes(bpe) version.write_text(MODEL_VERSION + "\n") print(f"fetch-wakeword: {ASSETS.relative_to(ROOT)} ({len(FILES)} files)") diff --git a/scripts/gen-wake-phrases.py b/scripts/gen-wake-phrases.py new file mode 100755 index 0000000..49c3ad7 --- /dev/null +++ b/scripts/gen-wake-phrases.py @@ -0,0 +1,108 @@ +#!/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() diff --git a/scripts/strings.py b/scripts/strings.py index ad7ec08..c923725 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -428,6 +428,17 @@ STRINGS: dict[str, str] = { "wake_word_listen": "Listen for a wake word", "wake_word_line": "Off by default. Say the phrase and the assistant opens, listening, over whatever app is on screen.", "wake_word_unavailable": "Not in this build. The F-Droid build has no wake-word engine, because F-Droid builds every library from source; the build from llembas.eu has one.", + "wake_phrase_line": "What you say. In English, whatever language the app is in: the engine only knows English speech.", + "wake_greeting": "Greeting", + "wake_name": "Name", + "wake_name_google_line": "A Google phone or speaker nearby will answer too.", + "wake_sensitivity": "Sensitivity", + "wake_sensitivity_low": "Low", + "wake_sensitivity_low_line": "Starts by mistake least often. You may have to say the phrase more clearly, or twice.", + "wake_sensitivity_normal": "Normal", + "wake_sensitivity_normal_line": "The engine's own setting.", + "wake_sensitivity_high": "High", + "wake_sensitivity_high_line": "Hears you most easily, also from further away. Starts by mistake more often.", "wake_screen_only": "Only while the screen is on", "wake_screen_only_line": "Off: it listens with the screen off too, at more cost to the battery.", "wake_battery": "Let it run in the background", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index 306f28d..1f07381 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -274,8 +274,11 @@ "wake_failed_microphone": "Budicí slovo nefunguje: mikrofon se nespustil", "wake_failed_model": "Budicí slovo nefunguje: jeho model se v tomto telefonu nepodařilo rozbalit", "wake_failed_no_engine": "Budicí slovo nefunguje: toto sestavení nemá modul", + "wake_greeting": "Oslovení", "wake_heard": "Slyšel jsem vás. Klepněte a ptejte se.", "wake_listening_for": "Naslouchám frázi „%1$s“", + "wake_name": "Jméno", + "wake_name_google_line": "Ozve se i telefon nebo reproduktor Google poblíž.", "wake_notification_line": "Dokud ji neřeknete, nic neopustí telefon.", "wake_off": "Budicí slovo neposlouchá", "wake_paused_assistant": "Budicí slovo je pozastaveno, dokud je asistent otevřený", @@ -283,10 +286,18 @@ "wake_paused_microphone": "Budicí slovo pozastaveno: LLeMbas nemá povolený mikrofon", "wake_paused_screen": "Budicí slovo pozastaveno: obrazovka je zhasnutá", "wake_paused_silent": "Budicí slovo nic neslyší: mikrofon používá jiná aplikace, nebo je v telefonu vypnutý", + "wake_phrase_line": "Tohle říkáte. Anglicky, ať je aplikace v jakémkoli jazyce: modul zná jen anglickou řeč.", "wake_resume": "Znovu naslouchat budicímu slovu", "wake_resume_line": "Telefon se restartoval. Klepnutím znovu spustíte naslouchání.", "wake_screen_only": "Jen při zapnuté obrazovce", "wake_screen_only_line": "Vypnuto: poslouchá i při zhasnuté obrazovce, za cenu vyšší spotřeby baterie.", + "wake_sensitivity": "Citlivost", + "wake_sensitivity_high": "Vysoká", + "wake_sensitivity_high_line": "Slyší vás nejsnáze, i z větší dálky. Omylem se spustí častěji.", + "wake_sensitivity_low": "Nízká", + "wake_sensitivity_low_line": "Omylem se spustí nejméně často. Frázi možná budete muset říct zřetelněji nebo dvakrát.", + "wake_sensitivity_normal": "Normální", + "wake_sensitivity_normal_line": "Vlastní nastavení modulu.", "wake_starting": "Budicí slovo se spouští…", "wake_stop": "Přestat naslouchat", "wake_tap_to_start": "Klepnutím ho znovu spustíte. Pokud se Android zeptá, povolte mikrofon.", @@ -576,8 +587,11 @@ "wake_failed_microphone": "Aktivierungswort funktioniert nicht: Das Mikrofon ist nicht gestartet", "wake_failed_model": "Aktivierungswort funktioniert nicht: Sein Modell konnte auf diesem Telefon nicht entpackt werden", "wake_failed_no_engine": "Aktivierungswort funktioniert nicht: Dieser Build hat keine Engine", + "wake_greeting": "Anrede", "wake_heard": "Gehört. Tippe, um zu fragen.", "wake_listening_for": "Hört auf „%1$s“", + "wake_name": "Name", + "wake_name_google_line": "Ein Google-Telefon oder -Lautsprecher in der Nähe antwortet ebenfalls.", "wake_notification_line": "Bis du es sagst, verlässt nichts das Telefon.", "wake_off": "Das Aktivierungswort hört nicht zu", "wake_paused_assistant": "Aktivierungswort pausiert, solange der Assistent offen ist", @@ -585,10 +599,18 @@ "wake_paused_microphone": "Aktivierungswort pausiert: LLeMbas darf das Mikrofon nicht verwenden", "wake_paused_screen": "Aktivierungswort pausiert: Bildschirm aus", "wake_paused_silent": "Aktivierungswort hört nichts: Eine andere App hat das Mikrofon, oder das Mikrofon des Telefons ist ausgeschaltet", + "wake_phrase_line": "Das sagst du. Auf Englisch, egal in welcher Sprache die App ist: Die Engine kennt nur englische Sprache.", "wake_resume": "Wieder auf das Aktivierungswort hören", "wake_resume_line": "Das Telefon wurde neu gestartet. Tippe, um wieder zuzuhören.", "wake_screen_only": "Nur bei eingeschaltetem Bildschirm", "wake_screen_only_line": "Aus: Es hört auch bei ausgeschaltetem Bildschirm zu, was mehr Akku kostet.", + "wake_sensitivity": "Empfindlichkeit", + "wake_sensitivity_high": "Hoch", + "wake_sensitivity_high_line": "Hört dich am leichtesten, auch aus größerer Entfernung. Startet öfter versehentlich.", + "wake_sensitivity_low": "Niedrig", + "wake_sensitivity_low_line": "Startet am seltensten versehentlich. Du musst den Satz vielleicht deutlicher oder zweimal sagen.", + "wake_sensitivity_normal": "Normal", + "wake_sensitivity_normal_line": "Die eigene Einstellung der Engine.", "wake_starting": "Aktivierungswort wird gestartet…", "wake_stop": "Nicht mehr zuhören", "wake_tap_to_start": "Tippe, um es wieder zu starten. Wenn Android fragt, erlaube das Mikrofon.", @@ -877,8 +899,11 @@ "wake_failed_microphone": "La palabra de activación no funciona: el micrófono no se inició", "wake_failed_model": "La palabra de activación no funciona: no se pudo desempaquetar su modelo en este teléfono", "wake_failed_no_engine": "La palabra de activación no funciona: esta versión no tiene motor", + "wake_greeting": "Saludo", "wake_heard": "Te he oído. Toca para preguntar.", "wake_listening_for": "Escuchando «%1$s»", + "wake_name": "Nombre", + "wake_name_google_line": "Un teléfono o altavoz de Google cercano también responderá.", "wake_notification_line": "Nada sale del teléfono hasta que lo digas.", "wake_off": "La palabra de activación no está escuchando", "wake_paused_assistant": "Palabra de activación en pausa mientras el asistente está abierto", @@ -886,10 +911,18 @@ "wake_paused_microphone": "Palabra de activación en pausa: LLeMbas no tiene permiso para usar el micrófono", "wake_paused_screen": "Palabra de activación en pausa: la pantalla está apagada", "wake_paused_silent": "La palabra de activación no oye nada: otra app tiene el micrófono, o el micrófono del teléfono está apagado", + "wake_phrase_line": "Lo que dices. En inglés, sea cual sea el idioma de la app: el motor solo conoce el habla inglesa.", "wake_resume": "Volver a escuchar la palabra de activación", "wake_resume_line": "El teléfono se reinició. Toca para volver a escuchar.", "wake_screen_only": "Solo con la pantalla encendida", "wake_screen_only_line": "Desactivado: también escucha con la pantalla apagada, con más gasto de batería.", + "wake_sensitivity": "Sensibilidad", + "wake_sensitivity_high": "Alta", + "wake_sensitivity_high_line": "Te oye con más facilidad, también desde más lejos. Se activa por error más a menudo.", + "wake_sensitivity_low": "Baja", + "wake_sensitivity_low_line": "Es la que menos se activa por error. Puede que tengas que decir la frase con más claridad, o dos veces.", + "wake_sensitivity_normal": "Normal", + "wake_sensitivity_normal_line": "El ajuste propio del motor.", "wake_starting": "Iniciando la palabra de activación…", "wake_stop": "Dejar de escuchar", "wake_tap_to_start": "Toca para iniciarla de nuevo. Si Android pregunta, permite el micrófono.", @@ -1179,8 +1212,11 @@ "wake_failed_microphone": "Le mot d’activation ne fonctionne pas : le micro n’a pas démarré", "wake_failed_model": "Le mot d’activation ne fonctionne pas : son modèle n’a pas pu être décompressé sur ce téléphone", "wake_failed_no_engine": "Le mot d’activation ne fonctionne pas : cette version n’a pas de moteur", + "wake_greeting": "Salutation", "wake_heard": "Entendu. Touchez pour demander.", "wake_listening_for": "À l’écoute de « %1$s »", + "wake_name": "Nom", + "wake_name_google_line": "Un téléphone ou une enceinte Google à proximité répondra aussi.", "wake_notification_line": "Rien ne quitte le téléphone avant que vous le disiez.", "wake_off": "Le mot d’activation n’écoute pas", "wake_paused_assistant": "Mot d’activation en pause pendant que l’assistant est ouvert", @@ -1188,10 +1224,18 @@ "wake_paused_microphone": "Mot d’activation en pause : LLeMbas n’est pas autorisé à utiliser le micro", "wake_paused_screen": "Mot d’activation en pause : écran éteint", "wake_paused_silent": "Le mot d’activation n’entend rien : une autre app utilise le micro, ou le micro du téléphone est coupé", + "wake_phrase_line": "Ce que vous dites. En anglais, quelle que soit la langue de l’app : le moteur ne connaît que la parole anglaise.", "wake_resume": "Écouter à nouveau le mot d’activation", "wake_resume_line": "Le téléphone a redémarré. Touchez pour reprendre l’écoute.", "wake_screen_only": "Seulement écran allumé", "wake_screen_only_line": "Désactivé : il écoute aussi écran éteint, au prix de plus de batterie.", + "wake_sensitivity": "Sensibilité", + "wake_sensitivity_high": "Élevée", + "wake_sensitivity_high_line": "Vous entend le plus facilement, même de plus loin. Se déclenche plus souvent par erreur.", + "wake_sensitivity_low": "Faible", + "wake_sensitivity_low_line": "Se déclenche le moins souvent par erreur. Vous devrez peut-être dire la phrase plus distinctement, ou deux fois.", + "wake_sensitivity_normal": "Normale", + "wake_sensitivity_normal_line": "Le réglage propre au moteur.", "wake_starting": "Démarrage du mot d’activation…", "wake_stop": "Arrêter l’écoute", "wake_tap_to_start": "Touchez pour le relancer. Si Android le demande, autorisez le micro.", @@ -1481,8 +1525,11 @@ "wake_failed_microphone": "Az ébresztőszó nem működik: a mikrofon nem indult el", "wake_failed_model": "Az ébresztőszó nem működik: a modelljét nem sikerült kicsomagolni ezen a telefonon", "wake_failed_no_engine": "Az ébresztőszó nem működik: ebben a változatban nincs motor", + "wake_greeting": "Megszólítás", "wake_heard": "Hallottalak. Koppints a kérdezéshez.", "wake_listening_for": "Figyeli: „%1$s”", + "wake_name": "Név", + "wake_name_google_line": "A közelben lévő Google-telefon vagy -hangszóró is válaszolni fog.", "wake_notification_line": "Amíg ki nem mondod, semmi nem hagyja el a telefont.", "wake_off": "Az ébresztőszó nem figyel", "wake_paused_assistant": "Az ébresztőszó szünetel, amíg az asszisztens nyitva van", @@ -1490,10 +1537,18 @@ "wake_paused_microphone": "Ébresztőszó szünetel: a LLeMbas nem használhatja a mikrofont", "wake_paused_screen": "Ébresztőszó szünetel: a képernyő ki van kapcsolva", "wake_paused_silent": "Az ébresztőszó semmit nem hall: másik alkalmazás használja a mikrofont, vagy a telefon mikrofonja ki van kapcsolva", + "wake_phrase_line": "Ezt mondod. Angolul, bármilyen nyelvű is az alkalmazás: a motor csak az angol beszédet ismeri.", "wake_resume": "Ébresztőszó figyelése újra", "wake_resume_line": "A telefon újraindult. Koppints a figyelés folytatásához.", "wake_screen_only": "Csak bekapcsolt képernyőnél", "wake_screen_only_line": "Kikapcsolva kikapcsolt képernyőnél is figyel, ami több akkumulátort fogyaszt.", + "wake_sensitivity": "Érzékenység", + "wake_sensitivity_high": "Magas", + "wake_sensitivity_high_line": "A legkönnyebben hall meg, távolabbról is. Gyakrabban indul el tévedésből.", + "wake_sensitivity_low": "Alacsony", + "wake_sensitivity_low_line": "A legritkábban indul el tévedésből. Lehet, hogy tisztábban vagy kétszer kell kimondanod a kifejezést.", + "wake_sensitivity_normal": "Normál", + "wake_sensitivity_normal_line": "A motor saját beállítása.", "wake_starting": "Az ébresztőszó indul…", "wake_stop": "Figyelés leállítása", "wake_tap_to_start": "Koppints az újraindításához. Ha az Android rákérdez, engedélyezd a mikrofont.", @@ -1782,8 +1837,11 @@ "wake_failed_microphone": "La parola di attivazione non funziona: il microfono non si è avviato", "wake_failed_model": "La parola di attivazione non funziona: non è stato possibile estrarre il suo modello su questo telefono", "wake_failed_no_engine": "La parola di attivazione non funziona: questa build non ha un motore", + "wake_greeting": "Saluto", "wake_heard": "Ti ho sentito. Tocca per chiedere.", "wake_listening_for": "In ascolto di «%1$s»", + "wake_name": "Nome", + "wake_name_google_line": "Risponderà anche un telefono o un altoparlante Google nelle vicinanze.", "wake_notification_line": "Niente lascia il telefono finché non lo dici.", "wake_off": "La parola di attivazione non è in ascolto", "wake_paused_assistant": "Parola di attivazione in pausa mentre l’assistente è aperto", @@ -1791,10 +1849,18 @@ "wake_paused_microphone": "Parola di attivazione in pausa: LLeMbas non ha il permesso di usare il microfono", "wake_paused_screen": "Parola di attivazione in pausa: schermo spento", "wake_paused_silent": "La parola di attivazione non sente nulla: un’altra app sta usando il microfono, o il microfono del telefono è disattivato", + "wake_phrase_line": "Quello che dici. In inglese, qualunque sia la lingua dell’app: il motore conosce solo il parlato inglese.", "wake_resume": "Ascolta di nuovo la parola di attivazione", "wake_resume_line": "Il telefono si è riavviato. Tocca per ricominciare ad ascoltare.", "wake_screen_only": "Solo a schermo acceso", "wake_screen_only_line": "Disattivato: ascolta anche a schermo spento, con più consumo di batteria.", + "wake_sensitivity": "Sensibilità", + "wake_sensitivity_high": "Alta", + "wake_sensitivity_high_line": "Ti sente più facilmente, anche da più lontano. Si attiva per errore più spesso.", + "wake_sensitivity_low": "Bassa", + "wake_sensitivity_low_line": "È quella che si attiva per errore meno spesso. Potresti dover dire la frase più chiaramente, o due volte.", + "wake_sensitivity_normal": "Normale", + "wake_sensitivity_normal_line": "L’impostazione propria del motore.", "wake_starting": "Avvio della parola di attivazione…", "wake_stop": "Smetti di ascoltare", "wake_tap_to_start": "Tocca per riavviarla. Se Android lo chiede, consenti il microfono.", @@ -2083,8 +2149,11 @@ "wake_failed_microphone": "Słowo aktywujące nie działa: mikrofon się nie uruchomił", "wake_failed_model": "Słowo aktywujące nie działa: nie udało się rozpakować jego modelu na tym telefonie", "wake_failed_no_engine": "Słowo aktywujące nie działa: ta wersja nie ma silnika", + "wake_greeting": "Powitanie", "wake_heard": "Słyszę. Dotknij, aby zapytać.", "wake_listening_for": "Nasłuchuje „%1$s”", + "wake_name": "Imię", + "wake_name_google_line": "Odpowie też telefon lub głośnik Google w pobliżu.", "wake_notification_line": "Nic nie opuszcza telefonu, dopóki tego nie powiesz.", "wake_off": "Słowo aktywujące nie nasłuchuje", "wake_paused_assistant": "Słowo aktywujące wstrzymane, gdy asystent jest otwarty", @@ -2092,10 +2161,18 @@ "wake_paused_microphone": "Słowo aktywujące wstrzymane: LLeMbas nie ma zgody na używanie mikrofonu", "wake_paused_screen": "Słowo aktywujące wstrzymane: ekran jest wyłączony", "wake_paused_silent": "Słowo aktywujące nic nie słyszy: inna aplikacja używa mikrofonu albo mikrofon telefonu jest wyłączony", + "wake_phrase_line": "To, co mówisz. Po angielsku, niezależnie od języka aplikacji: silnik zna tylko mowę angielską.", "wake_resume": "Znów nasłuchuj słowa aktywującego", "wake_resume_line": "Telefon uruchomił się ponownie. Dotknij, aby znów słuchać.", "wake_screen_only": "Tylko przy włączonym ekranie", "wake_screen_only_line": "Wyłączone: słucha także przy wyłączonym ekranie, kosztem baterii.", + "wake_sensitivity": "Czułość", + "wake_sensitivity_high": "Wysoka", + "wake_sensitivity_high_line": "Słyszy Cię najłatwiej, także z większej odległości. Częściej uruchamia się przez pomyłkę.", + "wake_sensitivity_low": "Niska", + "wake_sensitivity_low_line": "Najrzadziej uruchamia się przez pomyłkę. Być może trzeba będzie powiedzieć frazę wyraźniej albo dwa razy.", + "wake_sensitivity_normal": "Normalna", + "wake_sensitivity_normal_line": "Własne ustawienie silnika.", "wake_starting": "Uruchamianie słowa aktywującego…", "wake_stop": "Przestań słuchać", "wake_tap_to_start": "Dotknij, aby uruchomić je ponownie. Jeśli Android zapyta, zezwól na mikrofon.", @@ -2384,8 +2461,11 @@ "wake_failed_microphone": "Budiace slovo nefunguje: mikrofón sa nespustil", "wake_failed_model": "Budiace slovo nefunguje: jeho model sa v tomto telefóne nepodarilo rozbaliť", "wake_failed_no_engine": "Budiace slovo nefunguje: toto zostavenie nemá modul", + "wake_greeting": "Oslovenie", "wake_heard": "Počul som vás. Ťuknite a pýtajte sa.", "wake_listening_for": "Počúvam frázu „%1$s“", + "wake_name": "Meno", + "wake_name_google_line": "Ozve sa aj telefón alebo reproduktor Google nablízku.", "wake_notification_line": "Kým ju nepoviete, nič neopustí telefón.", "wake_off": "Budiace slovo nepočúva", "wake_paused_assistant": "Budiace slovo je pozastavené, kým je asistent otvorený", @@ -2393,10 +2473,18 @@ "wake_paused_microphone": "Budiace slovo pozastavené: LLeMbas nemá povolený mikrofón", "wake_paused_screen": "Budiace slovo pozastavené: obrazovka je zhasnutá", "wake_paused_silent": "Budiace slovo nič nepočuje: mikrofón používa iná aplikácia alebo je v telefóne vypnutý", + "wake_phrase_line": "Toto hovoríte. Po anglicky, nech je aplikácia v akomkoľvek jazyku: modul pozná len anglickú reč.", "wake_resume": "Znova počúvať budiace slovo", "wake_resume_line": "Telefón sa reštartoval. Ťuknutím znova spustíte počúvanie.", "wake_screen_only": "Len pri zapnutej obrazovke", "wake_screen_only_line": "Vypnuté: počúva aj pri zhasnutej obrazovke, za cenu vyššej spotreby batérie.", + "wake_sensitivity": "Citlivosť", + "wake_sensitivity_high": "Vysoká", + "wake_sensitivity_high_line": "Počuje vás najľahšie, aj z väčšej diaľky. Omylom sa spustí častejšie.", + "wake_sensitivity_low": "Nízka", + "wake_sensitivity_low_line": "Omylom sa spustí najmenej často. Frázu možno budete musieť povedať zreteľnejšie alebo dvakrát.", + "wake_sensitivity_normal": "Normálna", + "wake_sensitivity_normal_line": "Vlastné nastavenie modulu.", "wake_starting": "Budiace slovo sa spúšťa…", "wake_stop": "Prestať počúvať", "wake_tap_to_start": "Ťuknutím ho znova spustíte. Ak sa Android opýta, povoľte mikrofón.", diff --git a/scripts/wake-requirements.txt b/scripts/wake-requirements.txt new file mode 100644 index 0000000..5d5d011 --- /dev/null +++ b/scripts/wake-requirements.txt @@ -0,0 +1,5 @@ +# For scripts/gen-wake-phrases.py only (never in the app): the tokenizer the model's bpe.model +# is read with. Hash-pinned; the two wheels are CPython 3.12 and 3.13 on x86-64 Linux. +sentencepiece==0.2.3 \ + --hash=sha256:cc3189b79c1ffda767f71b04238c27ac746f3b7abc263eab9a41c4cf46aee49e \ + --hash=sha256:4d82f2a0f704f5d0cf027bc8cc5ad49e23c11a9cc0b5bd08ca51985917963bf5