Wake word: the engine loads, and its state is one truth that is shown
CI / check (push) Canceled after 0s

The model was read from the APK with AssetManager.openFd, which throws for a
compressed asset; the assets were compressed, runCatching swallowed it, and
the engine never loaded on any phone.

- The model is copied out by stream, keyed by a version file the fetch
  script writes (a hash of the pinned model); onnx assets are stored.
- WakeState (Off, Starting, Listening, Paused, Failed) in one StateFlow that
  the service, its notification and Settings read. onStartCommand no longer
  posts the default phrase; the notification is written from the state only.
- WakeListener holds the loop apart from Android: an engine that does not
  load and a microphone that does not start or stops are Failed states with
  a reason, logged, retried with back-off; a new phrase cancels and joins the
  old loop before the engine is released.
- A keywords line is checked against tokens.txt before the engine sees it
  (the engine exits the process on an unknown piece).
- The service is not started without the microphone permission, and the app
  looks again each time it comes to the screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 09:44:49 +00:00
1 parent 2d38ccd321
commit 374574b9ce
24 files changed
+1154 -151

No files matched your search

+29
View File
@@ -3,6 +3,35 @@
What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app
is in alpha and releases come off `main`.
## [Unreleased] — for 1.0.0-beta.8
### Fixed
- **The wake word never started, on any phone.** The engine read its model out of the APK in a
way that only works for files stored uncompressed, and they were not; the failure was swallowed,
so the notification went on saying it listened. The model is now copied out by stream (once per
model version, so an update that brings a new model replaces the old one) and stored
uncompressed as well.
- **The wake word's notification told the default phrase, not yours**, each time the app was
opened. It is now written from one place, from what the wake word is really doing.
- A change of phrase could release the engine while the old listening loop was still using it.
The old loop is now stopped and waited for first.
- A microphone that failed to start, or stopped giving sound, was not noticed (and one kind of
failure kept a processor core busy for nothing). Both are failures that are shown now.
- Opening the app with the wake word on but the microphone permission taken away could close the
app. The service is no longer started without the permission; the state says what is missing.
### Changed
- **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
switched off), or not working and why (its model could not be unpacked, the engine did not
start, the microphone did not start) -- with the technical reason under it in Settings. A
failure is tried again by itself, after 2 s, 5 s, 15 s, a minute, then every five minutes.
- A microphone permission given or taken in the system's settings is noticed when the app comes
back to the screen.
## [1.0.0-beta.7] — 2026-11-10
For LLeMbas server 2.0 (2.0.0-beta.10 or later for phone actions).
+6
View File
@@ -91,6 +91,12 @@ android {
}
}
androidResources {
// The wake-word model is read as files the engine opens itself: stored as it is, never
// deflated a second time (it does not shrink, and nothing has to inflate it on the phone).
noCompress += "onnx"
}
buildFeatures {
compose = true
buildConfig = true
@@ -10,5 +10,5 @@ import android.content.Context
object WakeEngine {
const val AVAILABLE = false
fun create(context: Context, phrase: WakePhrase): WakeDetector? = null
fun create(context: Context, keywords: String): WakeDetector = throw WakeError(WakeFailure.NoEngine, message = "this build has no wake-word engine")
}
@@ -15,40 +15,49 @@ import java.io.File
* `scripts/fetch-wakeword.py`. It runs on the phone's CPU, one thread, on the 16 kHz samples the
* service hands it; nothing leaves the phone.
*
* The model's files are copied out of the APK's assets once, into the app's no-backup files, so
* the engine reads them as files beside a keywords file written for the chosen phrase.
* The model's files are copied out of the APK's assets into the app's no-backup files
* ([unpackWakeModel]: by stream, keyed by the model's version), so the engine reads them as files
* beside a keywords file written for the chosen phrase.
*/
object WakeEngine {
const val AVAILABLE = true
private val FILES = listOf("encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt")
fun create(context: Context, phrase: WakePhrase): WakeDetector? = runCatching {
val dir = File(context.noBackupFilesDir, "wakeword").apply { mkdirs() }
for (name in FILES) {
val target = File(dir, name)
val size = context.assets.openFd("wakeword/$name").use { it.length }
if (!target.exists() || (size >= 0 && target.length() != size)) {
context.assets.open("wakeword/$name").use { input -> target.outputStream().use { input.copyTo(it) } }
}
/**
* The engine for [keywords] (the keywords file's text). Throws a [WakeError] that says which
* half failed -- the model's files or the engine -- and never returns nothing.
*/
fun create(context: Context, keywords: String): WakeDetector {
val dir = File(context.noBackupFilesDir, "wakeword")
try {
unpackWakeModel({ context.assets.open("wakeword/$it") }, dir, FILES)
} catch (e: Exception) {
throw WakeError(WakeFailure.Model, e)
}
val keywords = File(dir, "keywords.txt").apply { writeText("${phrase.tokens} @${phrase.id}\n") }
val config = KeywordSpotterConfig(
featConfig = FeatureConfig(sampleRate = RATE, featureDim = 80),
modelConfig = OnlineModelConfig(
transducer = OnlineTransducerModelConfig(
encoder = File(dir, "encoder.int8.onnx").path,
decoder = File(dir, "decoder.int8.onnx").path,
joiner = File(dir, "joiner.int8.onnx").path,
checkKeywords(keywords, File(dir, "tokens.txt").readText())
try {
val file = File(dir, "keywords.txt").apply { writeText(keywords) }
val config = KeywordSpotterConfig(
featConfig = FeatureConfig(sampleRate = RATE, featureDim = 80),
modelConfig = OnlineModelConfig(
transducer = OnlineTransducerModelConfig(
encoder = File(dir, "encoder.int8.onnx").path,
decoder = File(dir, "decoder.int8.onnx").path,
joiner = File(dir, "joiner.int8.onnx").path,
),
tokens = File(dir, "tokens.txt").path,
modelType = "zipformer2",
numThreads = 1,
),
tokens = File(dir, "tokens.txt").path,
modelType = "zipformer2",
numThreads = 1,
),
keywordsFile = keywords.path,
)
SherpaDetector(KeywordSpotter(null, config))
}.getOrNull()
keywordsFile = file.path,
)
return SherpaDetector(KeywordSpotter(null, config))
} catch (e: Throwable) {
// UnsatisfiedLinkError included: a phone whose processor the library was not built for.
throw WakeError(WakeFailure.Engine, e)
}
}
private const val RATE = 16_000
@@ -78,10 +78,6 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
take(intent)
followLanguage()
// A wake word that is on, but whose service the phone stopped: it listens again.
lifecycleScope.launch {
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) runCatching { WakeWordService.start(this@MainActivity) }
}
// At most once a day, and only while Settings › About says so (update/ReleaseCheck.kt).
lifecycleScope.launch { runCatching { ReleaseCheck(this@MainActivity).daily() } }
if (Build.VERSION.SDK_INT >= 33 &&
@@ -97,6 +93,18 @@ class MainActivity : ComponentActivity() {
}
}
/**
* A wake word that is on, but whose service the phone stopped, listens again -- each time the
* app comes to the screen, which is also when a microphone permission given or taken in the
* system's settings is noticed ([WakeWordService.start] says which it is).
*/
override fun onStart() {
super.onStart()
lifecycleScope.launch {
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity)
}
}
/**
* Keep the app in the language Settings › Language says: the account's by default. A
* language chosen for the app in the system's own settings (Android 13+) since the app last
@@ -34,7 +34,9 @@ import androidx.compose.material.icons.filled.BatteryAlert
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.Forum
import androidx.compose.material.icons.filled.GraphicEq
import androidx.compose.material.icons.filled.Hearing
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Mic
@@ -102,8 +104,13 @@ import eu.llembas.android.update.Updater
import eu.llembas.android.update.checksUpdates
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.WakePhrases
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.WakeStatus
import eu.llembas.android.wake.WakeWordService
import eu.llembas.android.wake.wakeTitle
import kotlinx.coroutines.launch
/** What the settings page does; every action has a do-nothing default for the screenshots. */
@@ -154,6 +161,8 @@ data class SettingsState(
val phoneRecognizer: Boolean = false,
/** Whether this build has a wake-word engine (the F-Droid build has none). */
val wakeAvailable: Boolean = false,
/** What the wake word is doing right now (WakeStatus), said under its switch while it is on. */
val wakeState: WakeState = WakeState.Off,
/** Whether Android's notification access is given to LLeMbas. */
val notificationAccess: Boolean = false,
/** The navigation apps installed: NavApp ids. */
@@ -168,6 +177,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
val instances by store.instances.collectAsState(initial = emptyList())
val active by store.active.collectAsState(initial = null)
val prefs by store.prefs.collectAsState(initial = Prefs())
val wakeState by WakeStatus.state.collectAsState()
var pushNote by remember { mutableStateOf<String?>(null) }
var updateNote by remember { mutableStateOf<String?>(null) }
var updateFound by remember { mutableStateOf<UpdateOffer?>(null) }
@@ -344,6 +354,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
beta = beta,
phoneRecognizer = remember { PhoneRecognizer.available(context) },
wakeAvailable = WakeEngine.AVAILABLE,
wakeState = wakeState,
// Read again each time Settings is composed: the person comes back from the system's page.
notificationAccess = NotificationReader.granted(context),
navApps = remember { NavApp.installedApps(context).map { it.id } },
@@ -629,6 +640,27 @@ private fun WakeWordGroup(state: SettingsState, actions: SettingsActions) {
onClick = { actions.wakeWord(!on) },
trailing = { Switch(checked = on, enabled = state.wakeAvailable, onCheckedChange = actions::wakeWord) },
)
if (on) {
// The truth, not the setting: listening, paused and why, or failed and why. A tap
// tries again (and asks for the microphone when that is what is missing).
val wake = state.wakeState
val trouble = wake is WakeState.Failed || wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone)
Rule()
SettingRow(
if (trouble) Icons.Filled.ErrorOutline else Icons.Filled.GraphicEq,
wakeTitle(LocalContext.current, wake),
subtitle = when {
wake is WakeState.Failed && wake.why != WakeFailure.NoEngine ->
listOf(stringResource(R.string.wake_failed_line), wake.detail).filter { it.isNotBlank() }.joinToString("\n")
wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone) -> stringResource(R.string.wake_tap_to_start)
else -> null
},
tint = if (trouble) palette.warning else null,
onClick = { actions.wakeWord(true) },
)
}
if (state.wakeAvailable) {
WakePhrases.all.forEach { phrase ->
Rule()
@@ -1,9 +1,14 @@
package eu.llembas.android.wake
import android.content.Context
import eu.llembas.android.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import java.io.File
import java.io.IOException
import java.io.InputStream
/**
* A wake word the engine ships: what the person says ([words]), the engine's spelling of it
@@ -40,6 +45,14 @@ interface WakeDetector {
fun release()
}
/** The microphone, as the listener sees it: 16 kHz mono samples, already recording when it is made. */
interface WakeMicrophone {
/** Fill [into]; how many samples were read, or a negative number when the microphone failed. */
fun read(into: ShortArray): Int
fun close()
}
/**
* Whether the assistant's sheet is up -- the wake-word service lets go of the microphone while
* it is, and takes it back once the sheet is gone. Counted, since the session and the activity
@@ -54,8 +67,13 @@ object AssistPresence {
fun hidden() = _open.update { (it - 1).coerceAtLeast(0) }
}
/** Why listening for the wake word is paused, or [None]: what the notification and Settings say. */
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone }
/**
* Why listening for the wake word is paused, or [None]: what the notification and Settings say.
* [Silent] is the one the listener finds out itself: the microphone is open but gives no sound at
* all, which is what Android hands a background app while a call or another recorder has it, or
* while the phone's microphone switch is off.
*/
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone, Silent }
/**
* When the service listens, from what the phone is doing: never while the sheet is up (it has the
@@ -69,3 +87,129 @@ fun wakePause(screenOn: Boolean, screenOnly: Boolean, batterySaver: Boolean, she
screenOnly && !screenOn -> WakePause.ScreenOff
else -> WakePause.None
}
/** What went wrong: this build has no engine, the model's files, the engine itself, or the microphone. */
enum class WakeFailure { NoEngine, Model, Engine, Microphone }
/** A failure with its kind, so the notification and Settings can say it in plain words. */
class WakeError(val why: WakeFailure, cause: Throwable? = null, message: String? = cause?.message) : Exception(message, cause) {
/** The technical half, for Settings and the log: the exception's name and what it said. */
val detail: String
get() = listOfNotNull(cause?.javaClass?.simpleName, message?.takeIf { it.isNotBlank() }).joinToString(": ").take(DETAIL_MAX)
private companion object {
const val DETAIL_MAX = 200
}
}
/**
* What the wake word is doing, the one truth the service, its notification and Settings all read
* ([WakeStatus.state]). [Failed] carries the plain reason and the technical [Failed.detail];
* nothing here is ever a guess from the settings alone.
*/
sealed interface WakeState {
/** Not running: turned off, or the phone stopped the service. */
data object Off : WakeState
/** Running, loading the engine. */
data object Starting : WakeState
/** The microphone is open and the engine hears it, for these words. */
data class Listening(val phrase: String) : WakeState
data class Paused(val why: WakePause) : WakeState
data class Failed(val why: WakeFailure, val detail: String = "") : WakeState
}
/** The wake word's state for the whole process: written by the service, read by everything else. */
object WakeStatus {
private val _state = MutableStateFlow<WakeState>(WakeState.Off)
val state: StateFlow<WakeState> = _state.asStateFlow()
fun set(now: WakeState) {
_state.value = now
}
}
/**
* [state] in plain words: the notification's title and Settings' line. A failure names what
* failed and that it is tried again; it never claims to listen while it does not.
*/
fun wakeTitle(context: Context, state: WakeState): String = when (state) {
WakeState.Off -> context.getString(R.string.wake_off)
WakeState.Starting -> context.getString(R.string.wake_starting)
is WakeState.Listening -> context.getString(R.string.wake_listening_for, state.phrase)
is WakeState.Paused -> context.getString(
when (state.why) {
WakePause.None -> R.string.wake_starting
WakePause.ScreenOff -> R.string.wake_paused_screen
WakePause.BatterySaver -> R.string.wake_paused_battery
WakePause.Assistant -> R.string.wake_paused_assistant
WakePause.NoMicrophone -> R.string.wake_paused_microphone
WakePause.Silent -> R.string.wake_paused_silent
},
)
is WakeState.Failed -> context.getString(
when (state.why) {
WakeFailure.NoEngine -> R.string.wake_failed_no_engine
WakeFailure.Model -> R.string.wake_failed_model
WakeFailure.Engine -> R.string.wake_failed_engine
WakeFailure.Microphone -> R.string.wake_failed_microphone
},
)
}
/** The notification's second line: the promise while it listens, else nothing more to say. */
fun wakeLine(context: Context, state: WakeState): String? = when (state) {
is WakeState.Listening -> context.getString(R.string.wake_notification_line)
is WakeState.Failed -> if (state.why == WakeFailure.NoEngine) null else context.getString(R.string.wake_failed_line)
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"
/**
* Every piece of [keywords] must be in the model's token table ([tokens], `tokens.txt`: a piece
* and its number per line): the engine ends the whole app on a piece it does not know, so it is
* never handed one.
*/
fun checkKeywords(keywords: String, tokens: String) {
val known = tokens.lineSequence().map { it.substringBeforeLast(' ') }.toSet()
for (line in keywords.lineSequence().filter { it.isNotBlank() }) {
val unknown = line.split(' ').filter { it.isNotEmpty() && it[0] !in ":#@" }.firstOrNull { it !in known }
if (unknown != null) throw WakeError(WakeFailure.Engine, message = "the model has no piece \"$unknown\"")
}
}
/**
* The model's files, out of the APK's assets into [dir], where the engine reads them as files.
* Copied by stream ([open] is `AssetManager.open`), so it works however the APK stores them, and
* keyed by the assets' `version` (a hash of the pinned model, written by
* `scripts/fetch-wakeword.py`): a new model replaces the old one, and a copy that was cut short
* has no marker and is made again.
*/
fun unpackWakeModel(open: (String) -> InputStream, dir: File, files: List<String>) {
val version = open("version").use { it.readBytes().decodeToString().trim() }
val marker = File(dir, "version")
if (marker.isFile && marker.readText() == version && files.all { File(dir, it).length() > 0 }) return
if (!dir.isDirectory && !dir.mkdirs()) throw IOException("cannot make ${dir.name}")
marker.delete()
for (name in files) {
val part = File(dir, "$name.part")
open(name).use { input -> part.outputStream().use { input.copyTo(it) } }
if (part.length() == 0L) throw IOException("$name is empty")
val target = File(dir, name)
target.delete()
if (!part.renameTo(target)) throw IOException("cannot write $name")
}
marker.writeText(version)
}
/** How long to wait before the next try after the [attempt]-th failure in a row: 2 s, 5 s, 15 s, 1 min, then every 5 min. */
fun wakeBackoff(attempt: Int): Long = listOf(2_000L, 5_000L, 15_000L, 60_000L).getOrElse(attempt) { 300_000L }
@@ -0,0 +1,181 @@
package eu.llembas.android.wake
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** What the service wants right now: this phrase, spelled for the engine as [keywords], unless [pause]d. */
data class WakePlan(val phrase: WakePhrase, val keywords: String, val pause: WakePause)
/**
* The listening itself, apart from Android so it can be tested: follows the plans, keeps one
* engine and one microphone, and says every change of state through [say].
*
* Nothing fails silently. An engine that does not load, a microphone that does not start or
* stops giving samples: each is a [WakeState.Failed] with its reason, logged, and tried again
* after [backoff]. And the engine is never released while a loop may still be feeding it: a new
* plan first cancels the old loop and waits for it to end ([cancelAndJoin]), then the engine is
* swapped, on the one coroutine that owns it.
*/
class WakeListener(
private val say: (WakeState) -> Unit,
private val engine: (keywords: String) -> WakeDetector,
private val microphone: () -> WakeMicrophone,
private val heard: suspend (WakePhrase) -> Unit,
private val work: CoroutineDispatcher = Dispatchers.IO,
private val backoff: (attempt: Int) -> Long = ::wakeBackoff,
private val log: (String, Throwable) -> Unit = { _, _ -> },
) {
@Volatile private var detector: WakeDetector? = null
@Volatile private var detectorFor: String? = null
/** Listen as [plans] say, until the flow ends or this is cancelled; the engine is released on the way out. */
suspend fun follow(plans: Flow<WakePlan>) = coroutineScope {
var hearing: Job? = null
try {
plans.distinctUntilChanged().collect { plan ->
hearing?.cancelAndJoin()
hearing = null
if (plan.pause != WakePause.None) {
say(WakeState.Paused(plan.pause))
} else {
hearing = launch { hear(plan) }
}
}
} finally {
withContext(NonCancellable) {
hearing?.cancelAndJoin()
release()
}
}
}
private fun release() {
runCatching { detector?.release() }
detector = null
detectorFor = null
}
/** Listen for [plan]'s phrase until cancelled: after the word, again; after a failure, again later. */
private suspend fun hear(plan: WakePlan) {
var failures = 0
while (true) {
try {
listen(plan)
failures = 0
heard(plan.phrase)
// The sheet takes the microphone now (a new plan cancels this); otherwise listen again.
delay(HEARD_REST_MS)
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
log("wake word: ${e.why}: ${e.detail}", e)
say(WakeState.Failed(e.why, e.detail))
// A build without an engine does not grow one: nothing to try again.
if (e.why == WakeFailure.NoEngine) return
delay(backoff(failures++))
}
}
}
/** One stretch of listening: returns when the word was heard, throws a [WakeError] when something failed. */
private suspend fun listen(plan: WakePlan) {
val spotter = engineFor(plan)
try {
withContext(work) {
// Opened and closed on this one thread, so a cancellation cannot leave it open.
val mic = try {
microphone()
} catch (e: Exception) {
throw WakeError(WakeFailure.Microphone, e)
}
try {
say(WakeState.Listening(plan.phrase.words))
val chunk = ShortArray(CHUNK)
var empty = 0
var silent = 0
while (true) {
ensureActive()
val read = mic.read(chunk)
if (read < 0) throw WakeError(WakeFailure.Microphone, message = "the microphone stopped (error $read)")
if (read == 0) {
if (++empty > EMPTY_READS) throw WakeError(WakeFailure.Microphone, message = "the microphone gives no samples")
continue
}
empty = 0
val samples = FloatArray(read)
var sound = false
for (i in 0 until read) {
if (chunk[i] != 0.toShort()) sound = true
samples[i] = chunk[i] / 32768f
}
// Exact silence for seconds is not a quiet room: Android gives a background
// app zeros while another app has the microphone or its switch is off.
if (sound) {
if (silent >= SILENT_SAMPLES) say(WakeState.Listening(plan.phrase.words))
silent = 0
} else if (silent < SILENT_SAMPLES) {
silent += read
if (silent >= SILENT_SAMPLES) say(WakeState.Paused(WakePause.Silent))
}
if (spotter.accept(samples)) break
}
} finally {
runCatching { mic.close() }
}
}
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
throw e
} catch (e: Throwable) {
// The engine threw while hearing: it is not trusted again, a new one is made.
release()
throw WakeError(WakeFailure.Engine, e)
}
}
/** The engine for [plan]'s keywords: the one there is, or a new one once the old is released. */
private suspend fun engineFor(plan: WakePlan): WakeDetector {
detector?.takeIf { detectorFor == plan.keywords }?.let { return it }
release()
say(WakeState.Starting)
return try {
// Kept the moment it exists, so a cancellation while it loads cannot lose it unreleased.
withContext(work) {
engine(plan.keywords).also {
detector = it
detectorFor = plan.keywords
}
}
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
throw e
} catch (e: Throwable) {
// A missing native library is an Error, not an Exception: it is a failure to show all the same.
throw WakeError(WakeFailure.Engine, e)
}
}
companion object {
const val RATE = 16_000
/** A tenth of a second at a time. */
private const val CHUNK = RATE / 10
private const val EMPTY_READS = 50
private const val SILENT_SAMPLES = RATE * 5
private const val HEARD_REST_MS = 1_500L
}
}
@@ -16,6 +16,7 @@ import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
@@ -32,11 +33,10 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
@@ -55,15 +55,22 @@ import kotlinx.coroutines.withContext
class WakeWordService : LifecycleService() {
private val screenOn = MutableStateFlow(true)
private val batterySaver = MutableStateFlow(false)
private var listening: Job? = null
private var detector: WakeDetector? = null
private var phraseId: String? = null
private val mayRecord = MutableStateFlow(true)
private var following: Job? = null
/** Set when the service could not even start: the state then says why, and is not wiped on the way out. */
private var keepState = false
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_SCREEN_ON -> screenOn.value = true
Intent.ACTION_SCREEN_ON -> {
screenOn.value = true
mayRecord.value = micAllowed(this@WakeWordService)
}
Intent.ACTION_SCREEN_OFF -> screenOn.value = false
PowerManager.ACTION_POWER_SAVE_MODE_CHANGED -> batterySaver.value = power().isPowerSaveMode
}
}
@@ -95,69 +102,66 @@ class WakeWordService : LifecycleService() {
}
return START_NOT_STICKY
}
mayRecord.value = micAllowed(this)
// The notification first: Android stops a foreground service that is slow to show one.
ServiceCompat.startForeground(this, NOTIFICATION_ID, notification(null, WakePause.None), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
if (listening == null) follow()
// It says what is true now -- "starting" for a service that just began, and on every
// later start (the app opens) whatever the state already is; never a phrase by default.
val now = WakeStatus.state.value.takeUnless { following == null || it == WakeState.Off } ?: WakeState.Starting
try {
ServiceCompat.startForeground(this, NOTIFICATION_ID, wakeNotification(this, now), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
} catch (e: Exception) {
// Android refuses a microphone service without the permission, or from the background.
Log.w(TAG, "wake word: the service could not start", e)
keepState = true
WakeStatus.set(
if (mayRecord.value) {
WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail)
} else {
WakeState.Paused(WakePause.NoMicrophone)
},
)
stopSelf()
return START_NOT_STICKY
}
if (following == null) {
keepState = false
WakeStatus.set(now)
following = lifecycleScope.launch { follow() }
// The one place the notification is written: from the state, whenever it changes.
val manager = getSystemService(NotificationManager::class.java)
lifecycleScope.launch {
WakeStatus.state.collect { state ->
if (state != WakeState.Off) manager.notify(NOTIFICATION_ID, wakeNotification(this@WakeWordService, state))
}
}
}
return START_NOT_STICKY
}
/** Listen, or pause, as the phone and Settings change; stop when Settings turns it off. */
private fun follow() {
listening = lifecycleScope.launch {
combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open) { prefs, on, saver, open ->
if (!prefs.wakeWord) {
null
} else {
prefs.wakePhrase to wakePause(on, prefs.wakeScreenOnly, saver, open > 0, micAllowed())
}
}.distinctUntilChanged().collect { now ->
if (now == null) {
stopSelf()
return@collect
}
val (id, pause) = now
val phrase = WakePhrases.byId(id)
notify(phrase, pause)
hearing?.cancel()
hearing = if (pause == WakePause.None) launch { hear(phrase) } else null
private suspend fun follow() {
val plans = combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open, mayRecord) { prefs, on, saver, open, mic ->
if (!prefs.wakeWord) {
null
} else {
val phrase = WakePhrases.byId(prefs.wakePhrase)
WakePlan(phrase, wakeKeywords(phrase), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic))
}
}
}
private var hearing: Job? = null
@android.annotation.SuppressLint("MissingPermission")
private suspend fun hear(phrase: WakePhrase) {
val engine = withContext(Dispatchers.Default) {
if (phraseId != phrase.id) {
detector?.release()
detector = WakeEngine.create(this@WakeWordService, phrase)
phraseId = phrase.id
}
detector
} ?: return notify(phrase, WakePause.NoMicrophone)
val min = AudioRecord.getMinBufferSize(RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
val audio = runCatching {
AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, RATE))
}.getOrNull() ?: return
var heard = false
withContext(Dispatchers.IO) {
try {
audio.startRecording()
val chunk = ShortArray(RATE / 10)
val samples = FloatArray(chunk.size)
while (isActive && !heard) {
val read = audio.read(chunk, 0, chunk.size)
if (read <= 0) continue
for (i in 0 until read) samples[i] = chunk[i] / 32768f
heard = engine.accept(if (read == chunk.size) samples else samples.copyOf(read))
}
} finally {
runCatching { audio.stop() }
audio.release()
}
val listener = WakeListener(
say = WakeStatus::set,
engine = { keywords -> WakeEngine.create(this, keywords) },
microphone = { PhoneMicrophone() },
heard = { wake() },
log = { message, cause -> Log.w(TAG, message, cause) },
)
try {
listener.follow(plans.takeWhile { it != null }.filterNotNull())
} finally {
// After the loop has ended, so nothing it said on its way out is left standing.
if (!keepState) WakeStatus.set(WakeState.Off)
}
if (heard) wake()
stopSelf()
}
/**
@@ -190,44 +194,13 @@ class WakeWordService : LifecycleService() {
}
}
private fun notify(phrase: WakePhrase, pause: WakePause) {
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification(phrase, pause))
}
/** What the persistent notification says: the phrase it listens for, or why it is paused. Nothing from the account. */
private fun notification(phrase: WakePhrase?, pause: WakePause): Notification {
val title = when (pause) {
WakePause.None -> getString(R.string.wake_listening_for, (phrase ?: WakePhrases.default).words)
WakePause.ScreenOff -> getString(R.string.wake_paused_screen)
WakePause.BatterySaver -> getString(R.string.wake_paused_battery)
WakePause.Assistant -> getString(R.string.wake_paused_assistant)
WakePause.NoMicrophone -> getString(R.string.wake_paused_microphone)
}
val stop = PendingIntent.getService(this, 2, Intent(this, WakeWordService::class.java).setAction(ACTION_STOP), PendingIntent.FLAG_IMMUTABLE)
val open = PendingIntent.getActivity(this, 3, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(this, CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(getString(R.string.wake_notification_line))
.setOngoing(true)
.setSilent(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(open)
.addAction(0, getString(R.string.wake_stop), stop)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.build()
}
private fun micAllowed() = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
private fun power() = getSystemService(PowerManager::class.java)
override fun onDestroy() {
hearing?.cancel()
listening?.cancel()
runCatching { unregisterReceiver(receiver) }
detector?.release()
detector = null
// The scope ends with the service: the listener's loop is joined and its engine released
// on the way out (WakeListener.follow), not here under a loop that may still run.
if (!keepState) WakeStatus.set(WakeState.Off)
super.onDestroy()
}
@@ -235,19 +208,33 @@ class WakeWordService : LifecycleService() {
const val CHANNEL = "wake_word"
private const val NOTIFICATION_ID = 7001
private const val HEARD_ID = 7002
private const val RATE = 16_000
private const val SHEET_GRACE_MS = 3_000L
private const val TAG = "LLeMbasWake"
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
/** Start listening. Only from the app on screen: Android allows a microphone service from there. */
/**
* Start listening, or say why not. Only from the app on screen: Android allows a
* microphone service from there, and only with the microphone permission -- without it
* the service is not started at all, and the state says so.
*/
fun start(context: Context) {
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
if (!WakeEngine.AVAILABLE) return WakeStatus.set(WakeState.Failed(WakeFailure.NoEngine))
if (!micAllowed(context)) return WakeStatus.set(WakeState.Paused(WakePause.NoMicrophone))
try {
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
} catch (e: Exception) {
Log.w(TAG, "wake word: the service could not be started", e)
WakeStatus.set(WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail))
}
}
fun stop(context: Context) {
context.stopService(Intent(context, WakeWordService::class.java))
WakeStatus.set(WakeState.Off)
}
fun micAllowed(context: Context) = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
fun channel(context: Context) {
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
@@ -256,6 +243,63 @@ class WakeWordService : LifecycleService() {
}
}
/**
* The persistent notification, from [state] alone: what the wake word is doing in plain words
* (the phrase it listens for, why it is paused, what failed). Nothing from the account.
*/
fun wakeNotification(context: Context, state: WakeState): Notification {
val stop = PendingIntent.getService(
context,
2,
Intent(context, WakeWordService::class.java).setAction(WakeWordService.ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE,
)
val open = PendingIntent.getActivity(context, 3, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(context, WakeWordService.CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(wakeTitle(context, state))
.setContentText(wakeLine(context, state))
.setOngoing(true)
.setSilent(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(open)
.addAction(0, context.getString(R.string.wake_stop), stop)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.build()
}
/**
* The phone's microphone at 16 kHz, recording from the moment it is made -- or an exception that
* says what did not work. Android reports none of this by throwing: a recorder that could not be
* opened is merely "uninitialized", and one that did not start merely "stopped".
*/
@android.annotation.SuppressLint("MissingPermission")
private class PhoneMicrophone : WakeMicrophone {
private val audio: AudioRecord
init {
val rate = WakeListener.RATE
val min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
check(min > 0) { "the phone cannot record at 16 kHz" }
audio = AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, rate))
try {
check(audio.state == AudioRecord.STATE_INITIALIZED) { "the microphone could not be opened" }
audio.startRecording()
check(audio.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "recording did not start; another app may have the microphone" }
} catch (e: Exception) {
audio.release()
throw e
}
}
override fun read(into: ShortArray): Int = audio.read(into, 0, into.size)
override fun close() {
runCatching { audio.stop() }
audio.release()
}
}
/**
* After a restart: Android does not let a microphone service start at boot, so a wake word that
* was on says "tap to listen again" -- the tap opens the app, which starts it.
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">Před vyslovením slova nic neopustí telefon. Zvuk z mikrofonu jde jen do modulu pro budicí slovo v telefonu a neukládá se; po celou dobu naslouchání je vidět oznámení. Fráze jsou anglické; modul je sherpa-onnx (open source).</string>
<string name="wake_word_cost">Stojí to baterii: mikrofon zůstává zapnutý a procesor telefonu kontroluje každý okamžik zvuku, bez úsporného čipu, který používá vestavěný asistent. Pozastaví se v úsporném režimu, když je asistent otevřený, a pokud to nezměníte, i při zhasnuté obrazovce. Po restartu ho znovu spustíte klepnutím na oznámení.</string>
<string name="wake_listening_for">Naslouchám frázi „%1$s“</string>
<string name="wake_off">Budicí slovo neposlouchá</string>
<string name="wake_tap_to_start">Klepnutím ho znovu spustíte. Pokud se Android zeptá, povolte mikrofon.</string>
<string name="wake_starting">Budicí slovo se spouští…</string>
<string name="wake_paused_silent">Budicí slovo nic neslyší: mikrofon používá jiná aplikace, nebo je v telefonu vypnutý</string>
<string name="wake_failed_no_engine">Budicí slovo nefunguje: toto sestavení nemá modul</string>
<string name="wake_failed_model">Budicí slovo nefunguje: jeho model se v tomto telefonu nepodařilo rozbalit</string>
<string name="wake_failed_engine">Budicí slovo nefunguje: modul se nespustil</string>
<string name="wake_failed_microphone">Budicí slovo nefunguje: mikrofon se nespustil</string>
<string name="wake_failed_line">Neposlouchá. Zkusí to znovu samo.</string>
<string name="wake_notification_line">Dokud ji neřeknete, nic neopustí telefon.</string>
<string name="wake_paused_screen">Budicí slovo pozastaveno: obrazovka je zhasnutá</string>
<string name="wake_paused_battery">Budicí slovo pozastaveno: je zapnutý úsporný režim</string>
<string name="wake_paused_assistant">Budicí slovo je pozastaveno, dokud je asistent otevřený</string>
<string name="wake_paused_microphone">Budicí slovo pozastaveno: mikrofon nebo modul není k dispozici</string>
<string name="wake_paused_microphone">Budicí slovo pozastaveno: LLeMbas nemá povolený mikrofon</string>
<string name="wake_stop">Přestat naslouchat</string>
<string name="wake_heard">Slyšel jsem vás. Klepněte a ptejte se.</string>
<string name="wake_resume">Znovu naslouchat budicímu slovu</string>
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">Vor dem Wort verlässt nichts das Telefon. Der Ton des Mikrofons geht nur an die Aktivierungswort-Engine auf dem Telefon und wird nicht gespeichert; die Benachrichtigung bleibt sichtbar, solange es zuhört. Die Sätze sind englisch; die Engine ist sherpa-onnx (Open Source).</string>
<string name="wake_word_cost">Es kostet Akku: Das Mikrofon bleibt an, und der Prozessor des Telefons prüft jeden Moment Ton, ohne den Stromspar-Chip, den der eingebaute Assistent nutzt. Es pausiert im Energiesparmodus, während der Assistent offen ist und, wenn du es nicht änderst, bei ausgeschaltetem Bildschirm. Nach einem Neustart tippe auf seine Benachrichtigung, um es wieder zu starten.</string>
<string name="wake_listening_for">Hört auf „%1$s“</string>
<string name="wake_off">Das Aktivierungswort hört nicht zu</string>
<string name="wake_tap_to_start">Tippe, um es wieder zu starten. Wenn Android fragt, erlaube das Mikrofon.</string>
<string name="wake_starting">Aktivierungswort wird gestartet…</string>
<string name="wake_paused_silent">Aktivierungswort hört nichts: Eine andere App hat das Mikrofon, oder das Mikrofon des Telefons ist ausgeschaltet</string>
<string name="wake_failed_no_engine">Aktivierungswort funktioniert nicht: Dieser Build hat keine Engine</string>
<string name="wake_failed_model">Aktivierungswort funktioniert nicht: Sein Modell konnte auf diesem Telefon nicht entpackt werden</string>
<string name="wake_failed_engine">Aktivierungswort funktioniert nicht: Die Engine ist nicht gestartet</string>
<string name="wake_failed_microphone">Aktivierungswort funktioniert nicht: Das Mikrofon ist nicht gestartet</string>
<string name="wake_failed_line">Es hört nicht zu. Es versucht es von selbst erneut.</string>
<string name="wake_notification_line">Bis du es sagst, verlässt nichts das Telefon.</string>
<string name="wake_paused_screen">Aktivierungswort pausiert: Bildschirm aus</string>
<string name="wake_paused_battery">Aktivierungswort pausiert: Energiesparmodus ist an</string>
<string name="wake_paused_assistant">Aktivierungswort pausiert, solange der Assistent offen ist</string>
<string name="wake_paused_microphone">Aktivierungswort pausiert: Mikrofon oder Engine nicht verfügbar</string>
<string name="wake_paused_microphone">Aktivierungswort pausiert: LLeMbas darf das Mikrofon nicht verwenden</string>
<string name="wake_stop">Nicht mehr zuhören</string>
<string name="wake_heard">Gehört. Tippe, um zu fragen.</string>
<string name="wake_resume">Wieder auf das Aktivierungswort hören</string>
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">Nada sale del teléfono antes de la palabra. El sonido del micrófono va solo al motor de palabra de activación del teléfono y no se guarda; la notificación se mantiene mientras escucha. Las frases están en inglés; el motor es sherpa-onnx (código abierto).</string>
<string name="wake_word_cost">Gasta batería: el micrófono sigue encendido y el procesador del teléfono revisa cada instante de sonido, sin el chip de bajo consumo que usa el asistente integrado. Se pausa en ahorro de batería, mientras el asistente está abierto y, salvo que lo cambies, con la pantalla apagada. Tras reiniciar, toca su notificación para volver a iniciarlo.</string>
<string name="wake_listening_for">Escuchando «%1$s»</string>
<string name="wake_off">La palabra de activación no está escuchando</string>
<string name="wake_tap_to_start">Toca para iniciarla de nuevo. Si Android pregunta, permite el micrófono.</string>
<string name="wake_starting">Iniciando la palabra de activación…</string>
<string name="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</string>
<string name="wake_failed_no_engine">La palabra de activación no funciona: esta versión no tiene motor</string>
<string name="wake_failed_model">La palabra de activación no funciona: no se pudo desempaquetar su modelo en este teléfono</string>
<string name="wake_failed_engine">La palabra de activación no funciona: el motor no se inició</string>
<string name="wake_failed_microphone">La palabra de activación no funciona: el micrófono no se inició</string>
<string name="wake_failed_line">No está escuchando. Lo intenta de nuevo por sí sola.</string>
<string name="wake_notification_line">Nada sale del teléfono hasta que lo digas.</string>
<string name="wake_paused_screen">Palabra de activación en pausa: la pantalla está apagada</string>
<string name="wake_paused_battery">Palabra de activación en pausa: ahorro de batería activado</string>
<string name="wake_paused_assistant">Palabra de activación en pausa mientras el asistente está abierto</string>
<string name="wake_paused_microphone">Palabra de activación en pausa: el micrófono o el motor no están disponibles</string>
<string name="wake_paused_microphone">Palabra de activación en pausa: LLeMbas no tiene permiso para usar el micrófono</string>
<string name="wake_stop">Dejar de escuchar</string>
<string name="wake_heard">Te he oído. Toca para preguntar.</string>
<string name="wake_resume">Volver a escuchar la palabra de activación</string>
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">Rien ne quitte le téléphone avant le mot. Le son du micro ne va qu’au moteur de mot d’activation du téléphone et n’est pas conservé ; la notification reste affichée tant qu’il écoute. Les phrases sont en anglais ; le moteur est sherpa-onnx (open source).</string>
<string name="wake_word_cost">Cela consomme de la batterie : le micro reste allumé et le processeur du téléphone examine chaque instant de son, sans la puce basse consommation de l’assistant intégré. Il se met en pause en économie de batterie, quand l’assistant est ouvert et, sauf si vous le changez, écran éteint. Après un redémarrage, touchez sa notification pour le relancer.</string>
<string name="wake_listening_for">À l’écoute de « %1$s »</string>
<string name="wake_off">Le mot d’activation n’écoute pas</string>
<string name="wake_tap_to_start">Touchez pour le relancer. Si Android le demande, autorisez le micro.</string>
<string name="wake_starting">Démarrage du mot d’activation…</string>
<string name="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é</string>
<string name="wake_failed_no_engine">Le mot d’activation ne fonctionne pas : cette version n’a pas de moteur</string>
<string name="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</string>
<string name="wake_failed_engine">Le mot d’activation ne fonctionne pas : le moteur n’a pas démarré</string>
<string name="wake_failed_microphone">Le mot d’activation ne fonctionne pas : le micro n’a pas démarré</string>
<string name="wake_failed_line">Il n’écoute pas. Il réessaie de lui-même.</string>
<string name="wake_notification_line">Rien ne quitte le téléphone avant que vous le disiez.</string>
<string name="wake_paused_screen">Mot d’activation en pause : écran éteint</string>
<string name="wake_paused_battery">Mot d’activation en pause : économiseur de batterie activé</string>
<string name="wake_paused_assistant">Mot d’activation en pause pendant que l’assistant est ouvert</string>
<string name="wake_paused_microphone">Mot d’activation en pause : micro ou moteur indisponible</string>
<string name="wake_paused_microphone">Mot d’activation en pause : LLeMbas n’est pas autorisé à utiliser le micro</string>
<string name="wake_stop">Arrêter l’écoute</string>
<string name="wake_heard">Entendu. Touchez pour demander.</string>
<string name="wake_resume">Écouter à nouveau le mot d’activation</string>
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">A szó előtt semmi nem hagyja el a telefont. A mikrofon hangja csak a telefonon futó ébresztőszó-motorhoz jut, és nem tárolódik; amíg figyel, az értesítés végig látható. A kifejezések angolok; a motor a sherpa-onnx (nyílt forráskódú).</string>
<string name="wake_word_cost">Akkumulátorba kerül: a mikrofon bekapcsolva marad, és a telefon processzora minden hangpillanatot ellenőriz, a beépített asszisztens energiatakarékos chipje nélkül. Energiatakarékos módban, nyitott asszisztensnél és — ha nem változtatod meg — kikapcsolt képernyőnél szünetel. Újraindítás után koppints az értesítésére az újraindításhoz.</string>
<string name="wake_listening_for">Figyeli: „%1$s”</string>
<string name="wake_off">Az ébresztőszó nem figyel</string>
<string name="wake_tap_to_start">Koppints az újraindításához. Ha az Android rákérdez, engedélyezd a mikrofont.</string>
<string name="wake_starting">Az ébresztőszó indul…</string>
<string name="wake_paused_silent">Az ébresztőszó semmit nem hall: másik alkalmazás használja a mikrofont, vagy a telefon mikrofonja ki van kapcsolva</string>
<string name="wake_failed_no_engine">Az ébresztőszó nem működik: ebben a változatban nincs motor</string>
<string name="wake_failed_model">Az ébresztőszó nem működik: a modelljét nem sikerült kicsomagolni ezen a telefonon</string>
<string name="wake_failed_engine">Az ébresztőszó nem működik: a motor nem indult el</string>
<string name="wake_failed_microphone">Az ébresztőszó nem működik: a mikrofon nem indult el</string>
<string name="wake_failed_line">Nem figyel. Magától újrapróbálja.</string>
<string name="wake_notification_line">Amíg ki nem mondod, semmi nem hagyja el a telefont.</string>
<string name="wake_paused_screen">Ébresztőszó szünetel: a képernyő ki van kapcsolva</string>
<string name="wake_paused_battery">Ébresztőszó szünetel: be van kapcsolva az energiatakarékos mód</string>
<string name="wake_paused_assistant">Az ébresztőszó szünetel, amíg az asszisztens nyitva van</string>
<string name="wake_paused_microphone">Ébresztőszó szünetel: a mikrofon vagy a motor nem érhető el</string>
<string name="wake_paused_microphone">Ébresztőszó szünetel: a LLeMbas nem használhatja a mikrofont</string>
<string name="wake_stop">Figyelés leállítása</string>
<string name="wake_heard">Hallottalak. Koppints a kérdezéshez.</string>
<string name="wake_resume">Ébresztőszó figyelése újra</string>
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">Niente lascia il telefono prima della parola. Il suono del microfono va solo al motore della parola di attivazione sul telefono e non viene conservato; la notifica resta visibile finché ascolta. Le frasi sono in inglese; il motore è sherpa-onnx (open source).</string>
<string name="wake_word_cost">Consuma batteria: il microfono resta acceso e il processore del telefono esamina ogni istante di suono, senza il chip a basso consumo usato dall’assistente integrato. Si mette in pausa con il risparmio energetico, mentre l’assistente è aperto e, se non lo cambi, a schermo spento. Dopo un riavvio, tocca la sua notifica per riavviarlo.</string>
<string name="wake_listening_for">In ascolto di «%1$s»</string>
<string name="wake_off">La parola di attivazione non è in ascolto</string>
<string name="wake_tap_to_start">Tocca per riavviarla. Se Android lo chiede, consenti il microfono.</string>
<string name="wake_starting">Avvio della parola di attivazione…</string>
<string name="wake_paused_silent">La parola di attivazione non sente nulla: un’altra app sta usando il microfono, o il microfono del telefono è disattivato</string>
<string name="wake_failed_no_engine">La parola di attivazione non funziona: questa build non ha un motore</string>
<string name="wake_failed_model">La parola di attivazione non funziona: non è stato possibile estrarre il suo modello su questo telefono</string>
<string name="wake_failed_engine">La parola di attivazione non funziona: il motore non si è avviato</string>
<string name="wake_failed_microphone">La parola di attivazione non funziona: il microfono non si è avviato</string>
<string name="wake_failed_line">Non è in ascolto. Riprova da sola.</string>
<string name="wake_notification_line">Niente lascia il telefono finché non lo dici.</string>
<string name="wake_paused_screen">Parola di attivazione in pausa: schermo spento</string>
<string name="wake_paused_battery">Parola di attivazione in pausa: risparmio energetico attivo</string>
<string name="wake_paused_assistant">Parola di attivazione in pausa mentre l’assistente è aperto</string>
<string name="wake_paused_microphone">Parola di attivazione in pausa: microfono o motore non disponibili</string>
<string name="wake_paused_microphone">Parola di attivazione in pausa: LLeMbas non ha il permesso di usare il microfono</string>
<string name="wake_stop">Smetti di ascoltare</string>
<string name="wake_heard">Ti ho sentito. Tocca per chiedere.</string>
<string name="wake_resume">Ascolta di nuovo la parola di attivazione</string>
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">Nic nie opuszcza telefonu przed słowem. Dźwięk z mikrofonu trafia tylko do silnika słowa aktywującego w telefonie i nie jest zapisywany; powiadomienie jest widoczne przez cały czas nasłuchiwania. Frazy są po angielsku; silnik to sherpa-onnx (open source).</string>
<string name="wake_word_cost">Zużywa baterię: mikrofon pozostaje włączony, a procesor telefonu sprawdza każdą chwilę dźwięku, bez energooszczędnego układu, którego używa wbudowany asystent. Wstrzymuje się w trybie oszczędzania baterii, gdy asystent jest otwarty, i — jeśli tego nie zmienisz — przy wyłączonym ekranie. Po ponownym uruchomieniu dotknij jego powiadomienia, by znów zaczął.</string>
<string name="wake_listening_for">Nasłuchuje „%1$s”</string>
<string name="wake_off">Słowo aktywujące nie nasłuchuje</string>
<string name="wake_tap_to_start">Dotknij, aby uruchomić je ponownie. Jeśli Android zapyta, zezwól na mikrofon.</string>
<string name="wake_starting">Uruchamianie słowa aktywującego…</string>
<string name="wake_paused_silent">Słowo aktywujące nic nie słyszy: inna aplikacja używa mikrofonu albo mikrofon telefonu jest wyłączony</string>
<string name="wake_failed_no_engine">Słowo aktywujące nie działa: ta wersja nie ma silnika</string>
<string name="wake_failed_model">Słowo aktywujące nie działa: nie udało się rozpakować jego modelu na tym telefonie</string>
<string name="wake_failed_engine">Słowo aktywujące nie działa: silnik się nie uruchomił</string>
<string name="wake_failed_microphone">Słowo aktywujące nie działa: mikrofon się nie uruchomił</string>
<string name="wake_failed_line">Nie nasłuchuje. Spróbuje ponownie samo.</string>
<string name="wake_notification_line">Nic nie opuszcza telefonu, dopóki tego nie powiesz.</string>
<string name="wake_paused_screen">Słowo aktywujące wstrzymane: ekran jest wyłączony</string>
<string name="wake_paused_battery">Słowo aktywujące wstrzymane: oszczędzanie baterii jest włączone</string>
<string name="wake_paused_assistant">Słowo aktywujące wstrzymane, gdy asystent jest otwarty</string>
<string name="wake_paused_microphone">Słowo aktywujące wstrzymane: mikrofon lub silnik jest niedostępny</string>
<string name="wake_paused_microphone">Słowo aktywujące wstrzymane: LLeMbas nie ma zgody na używanie mikrofonu</string>
<string name="wake_stop">Przestań słuchać</string>
<string name="wake_heard">Słyszę. Dotknij, aby zapytać.</string>
<string name="wake_resume">Znów nasłuchuj słowa aktywującego</string>
+10 -1
View File
@@ -408,11 +408,20 @@
<string name="wake_word_privacy">Pred vyslovením slova nič neopustí telefón. Zvuk z mikrofónu ide len do modulu pre budiace slovo v telefóne a neukladá sa; počas celého počúvania je viditeľné oznámenie. Frázy sú anglické; modul je sherpa-onnx (open source).</string>
<string name="wake_word_cost">Stojí to batériu: mikrofón zostáva zapnutý a procesor telefónu kontroluje každý okamih zvuku, bez úsporného čipu, ktorý používa vstavaný asistent. Pozastaví sa v úspornom režime, keď je asistent otvorený, a ak to nezmeníte, aj pri zhasnutej obrazovke. Po reštarte ho znova spustíte ťuknutím na oznámenie.</string>
<string name="wake_listening_for">Počúvam frázu „%1$s“</string>
<string name="wake_off">Budiace slovo nepočúva</string>
<string name="wake_tap_to_start">Ťuknutím ho znova spustíte. Ak sa Android opýta, povoľte mikrofón.</string>
<string name="wake_starting">Budiace slovo sa spúšťa…</string>
<string name="wake_paused_silent">Budiace slovo nič nepočuje: mikrofón používa iná aplikácia alebo je v telefóne vypnutý</string>
<string name="wake_failed_no_engine">Budiace slovo nefunguje: toto zostavenie nemá modul</string>
<string name="wake_failed_model">Budiace slovo nefunguje: jeho model sa v tomto telefóne nepodarilo rozbaliť</string>
<string name="wake_failed_engine">Budiace slovo nefunguje: modul sa nespustil</string>
<string name="wake_failed_microphone">Budiace slovo nefunguje: mikrofón sa nespustil</string>
<string name="wake_failed_line">Nepočúva. Skúsi to znova samo.</string>
<string name="wake_notification_line">Kým ju nepoviete, nič neopustí telefón.</string>
<string name="wake_paused_screen">Budiace slovo pozastavené: obrazovka je zhasnutá</string>
<string name="wake_paused_battery">Budiace slovo pozastavené: je zapnutý úsporný režim</string>
<string name="wake_paused_assistant">Budiace slovo je pozastavené, kým je asistent otvorený</string>
<string name="wake_paused_microphone">Budiace slovo pozastavené: mikrofón alebo modul nie je k dispozícii</string>
<string name="wake_paused_microphone">Budiace slovo pozastavené: LLeMbas nemá povolený mikrofón</string>
<string name="wake_stop">Prestať počúvať</string>
<string name="wake_heard">Počul som vás. Ťuknite a pýtajte sa.</string>
<string name="wake_resume">Znova počúvať budiace slovo</string>
+10 -1
View File
@@ -410,11 +410,20 @@
<string name="wake_word_privacy">Nothing leaves the phone before the word. The microphone\'s sound goes only to the wake-word engine on the phone and is not kept, and the notification stays up the whole time it listens. The phrases are English; the engine is sherpa-onnx (open source).</string>
<string name="wake_word_cost">It costs battery: the microphone stays on and the phone\'s processor checks every moment of sound, without the low-power chip the built-in assistant uses. It pauses in battery saver, while the assistant is open and, unless you change it, with the screen off. After a restart, tap its notification to start it again.</string>
<string name="wake_listening_for">Listening for “%1$s”</string>
<string name="wake_off">The wake word is not listening</string>
<string name="wake_tap_to_start">Tap to start it again. If Android asks, allow the microphone.</string>
<string name="wake_starting">Starting the wake word…</string>
<string name="wake_paused_silent">Wake word hears nothing: another app has the microphone, or the phone\'s microphone is switched off</string>
<string name="wake_failed_no_engine">Wake word is not working: this build has no engine</string>
<string name="wake_failed_model">Wake word is not working: its model could not be unpacked on this phone</string>
<string name="wake_failed_engine">Wake word is not working: the engine did not start</string>
<string name="wake_failed_microphone">Wake word is not working: the microphone did not start</string>
<string name="wake_failed_line">It is not listening. It tries again by itself.</string>
<string name="wake_notification_line">Nothing leaves the phone until you say it.</string>
<string name="wake_paused_screen">Wake word paused: the screen is off</string>
<string name="wake_paused_battery">Wake word paused: battery saver is on</string>
<string name="wake_paused_assistant">Wake word paused while the assistant is open</string>
<string name="wake_paused_microphone">Wake word paused: the microphone or the engine is not available</string>
<string name="wake_paused_microphone">Wake word paused: LLeMbas is not allowed to use the microphone</string>
<string name="wake_stop">Stop listening</string>
<string name="wake_heard">Heard you. Tap to ask.</string>
<string name="wake_resume">Listen for the wake word again</string>
@@ -0,0 +1,221 @@
package eu.llembas.android
import eu.llembas.android.wake.WakeDetector
import eu.llembas.android.wake.WakeError
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakeListener
import eu.llembas.android.wake.WakeMicrophone
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.WakePlan
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.wakeKeywords
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Collections
/**
* The listening loop without a phone: an engine that does not load, a microphone that does not
* start or stops, silence, a pause and a change of phrase -- each must end in a state somebody
* can read, and the engine must never be released under a loop that still feeds it.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class WakeListenerTest {
/** Gives [script] one chunk at a time (true: sound, false: exact silence), then [after]: more sound, or an error code. */
private class Mic(private val script: List<Boolean> = emptyList(), private val after: Int = 0, private val pauseMs: Long = 0) : WakeMicrophone {
@Volatile var closed = false
private var reads = 0
override fun read(into: ShortArray): Int {
if (pauseMs > 0) Thread.sleep(pauseMs)
val sound = script.getOrNull(reads++) ?: if (after < 0) return after else true
into.fill(if (sound) 100 else 0)
return into.size
}
override fun close() {
closed = true
}
}
/** Hears the word on its [hearOn]-th chunk; notes a release that came while it was at work, or work after a release. */
private class Detector(private val hearOn: Int = Int.MAX_VALUE, private val workMs: Long = 0) : WakeDetector {
@Volatile var released = false
@Volatile var misused = false
@Volatile private var busy = false
private var accepts = 0
override fun accept(samples: FloatArray): Boolean {
if (released) misused = true
busy = true
if (workMs > 0) Thread.sleep(workMs)
busy = false
return ++accepts % hearOn == 0
}
override fun release() {
if (busy) misused = true
released = true
}
}
private val assistant = WakePhrases.byId("hey_assistant")
private val plan = WakePlan(assistant, wakeKeywords(assistant), WakePause.None)
private val states: MutableList<WakeState> = Collections.synchronizedList(mutableListOf())
private fun TestScope.listener(engine: (String) -> WakeDetector, microphone: () -> WakeMicrophone, heard: () -> Unit = {}) = WakeListener(
say = { states += it },
engine = engine,
microphone = microphone,
heard = { heard() },
work = StandardTestDispatcher(testScheduler),
)
@Test
fun anEngineThatDoesNotLoadIsShownAndTriedAgain() = runTest {
var tries = 0
var heard = 0
val detector = Detector(hearOn = 3)
val listener = listener(
engine = { if (++tries < 3) error("no such file") else detector },
microphone = { Mic() },
heard = { heard++ },
)
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(listOf(WakeState.Starting, WakeState.Failed(WakeFailure.Engine, "IllegalStateException: no such file")), states.toList())
advanceTimeBy(2_001) // the first wait
assertEquals(2, tries)
advanceTimeBy(5_001) // the second, longer
assertEquals(3, tries)
assertEquals(WakeState.Listening("Hey Assistant"), states.last())
assertEquals(1, heard)
job.cancelAndJoin()
assertTrue(detector.released)
}
@Test
fun aBuildWithoutAnEngineSaysSoOnce() = runTest {
var tries = 0
val listener = listener(engine = {
tries++
throw WakeError(WakeFailure.NoEngine, message = "this build has no wake-word engine")
}, microphone = { Mic() })
val job = launch { listener.follow(MutableStateFlow(plan)) }
advanceTimeBy(3_600_000)
assertEquals(1, tries)
assertEquals(WakeState.Failed(WakeFailure.NoEngine, "this build has no wake-word engine"), states.last())
job.cancelAndJoin()
}
@Test
fun aMicrophoneThatDoesNotStartIsAFailureNotASilentReturn() = runTest {
var opens = 0
val listener = listener(engine = { Detector() }, microphone = {
opens++
throw IllegalStateException("recording did not start")
})
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(WakeState.Failed(WakeFailure.Microphone, "IllegalStateException: recording did not start"), states.last())
advanceTimeBy(2_001)
assertEquals(2, opens)
job.cancelAndJoin()
}
@Test
fun aMicrophoneThatStopsIsAFailureAndIsClosed() = runTest {
val mic = Mic(script = listOf(true, true), after = -3)
val listener = listener(engine = { Detector() }, microphone = { mic })
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(WakeState.Failed(WakeFailure.Microphone, "the microphone stopped (error -3)"), states.last())
assertTrue(mic.closed)
job.cancelAndJoin()
}
@Test
fun exactSilenceForSecondsIsSaidAndSoIsSoundComingBack() = runTest {
// Six seconds of zeros (a tenth of a second a chunk), then sound; the word on the 70th chunk.
val listener = listener(engine = { Detector(hearOn = 70) }, microphone = { Mic(script = List(60) { false }) })
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
val listening = WakeState.Listening("Hey Assistant")
assertEquals(listOf(WakeState.Starting, listening, WakeState.Paused(WakePause.Silent), listening), states.toList())
job.cancelAndJoin()
}
/** With real threads: wait until the listener has said [state]. */
private suspend fun said(now: MutableStateFlow<WakeState>, state: WakeState) = withTimeout(10_000) { now.first { it == state } }
@Test
fun aPauseLetsGoOfTheMicrophoneAndKeepsTheEngine() = runBlocking {
val now = MutableStateFlow<WakeState>(WakeState.Off)
val mics = Collections.synchronizedList(mutableListOf<Mic>())
val detectors = Collections.synchronizedList(mutableListOf<Detector>())
val listener = WakeListener(
say = { now.value = it },
engine = { Detector().also { detectors += it } },
microphone = { Mic(pauseMs = 2).also { mics += it } },
heard = {},
)
val plans = MutableStateFlow(plan)
val job = launch(Dispatchers.Default) { listener.follow(plans) }
said(now, WakeState.Listening("Hey Assistant"))
plans.value = plan.copy(pause = WakePause.ScreenOff)
said(now, WakeState.Paused(WakePause.ScreenOff))
assertTrue(mics.single().closed)
assertFalse(detectors.single().released)
plans.value = plan
said(now, WakeState.Listening("Hey Assistant"))
assertEquals(1, detectors.size)
assertEquals(2, mics.size)
job.cancelAndJoin()
assertTrue(detectors.single().released)
assertTrue(mics.all { it.closed })
assertFalse(detectors.single().misused)
}
@Test
fun aNewPhraseWaitsForTheOldLoopBeforeItsEngineIsReleased() = runBlocking {
val now = MutableStateFlow<WakeState>(WakeState.Off)
val detectors = Collections.synchronizedList(mutableListOf<Detector>())
val listener = WakeListener(
say = { now.value = it },
// Slow at its work, so a release that did not wait would land in the middle of it.
engine = { Detector(workMs = 30).also { detectors += it } },
microphone = { Mic() },
heard = {},
)
val plans = MutableStateFlow(plan)
val job = launch(Dispatchers.Default) { listener.follow(plans) }
val other = WakePhrases.all.first { it.id != assistant.id }
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))
plans.value = WakePlan(phrase, wakeKeywords(phrase), WakePause.None)
}
said(now, WakeState.Listening(other.words))
job.cancelAndJoin()
assertEquals(6, detectors.size)
assertTrue(detectors.all { it.released })
assertFalse(detectors.any { it.misused })
}
}
@@ -0,0 +1,78 @@
package eu.llembas.android
import android.app.Application
import android.app.Notification
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.wakeNotification
import eu.llembas.android.wake.wakeTitle
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/**
* What the wake word's notification says, from its state alone: the phrase only while it really
* listens for it, a pause with its reason, a failure with what failed -- and nothing else, ever.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35], qualifiers = "en")
class WakeNotificationTest {
private val app: Application get() = RuntimeEnvironment.getApplication()
private fun title(state: WakeState) = wakeNotification(app, state).extras.getCharSequence(Notification.EXTRA_TITLE).toString()
private fun line(state: WakeState) = wakeNotification(app, state).extras.getCharSequence(Notification.EXTRA_TEXT)?.toString()
@Test
fun itNamesThePhraseOnlyWhileItListensForIt() {
assertEquals("Listening for “Hey Assistant”", title(WakeState.Listening("Hey Assistant")))
assertEquals("Nothing leaves the phone until you say it.", line(WakeState.Listening("Hey Assistant")))
// A service that has just started knows no phrase yet, and names none.
assertEquals("Starting the wake word…", title(WakeState.Starting))
assertNull(line(WakeState.Starting))
}
@Test
fun aPauseSaysWhy() {
assertEquals("Wake word paused: the screen is off", title(WakeState.Paused(WakePause.ScreenOff)))
assertEquals("Wake word paused: battery saver is on", title(WakeState.Paused(WakePause.BatterySaver)))
assertEquals("Wake word paused while the assistant is open", title(WakeState.Paused(WakePause.Assistant)))
assertEquals("Wake word paused: LLeMbas is not allowed to use the microphone", title(WakeState.Paused(WakePause.NoMicrophone)))
assertEquals(
"Wake word hears nothing: another app has the microphone, or the phone's microphone is switched off",
title(WakeState.Paused(WakePause.Silent)),
)
}
@Test
fun aFailureSaysWhatFailedAndNeverThatItListens() {
val failures = mapOf(
WakeFailure.Engine to "Wake word is not working: the engine did not start",
WakeFailure.Model to "Wake word is not working: its model could not be unpacked on this phone",
WakeFailure.Microphone to "Wake word is not working: the microphone did not start",
)
for ((why, words) in failures) {
val state = WakeState.Failed(why, "IOException: no space left")
assertEquals(words, title(state))
assertEquals("It is not listening. It tries again by itself.", line(state))
assertFalse(title(state).contains("Listening"))
}
assertEquals("Wake word is not working: this build has no engine", title(WakeState.Failed(WakeFailure.NoEngine)))
assertNull(line(WakeState.Failed(WakeFailure.NoEngine)))
assertEquals("The wake word is not listening", wakeTitle(app, WakeState.Off))
}
@Test
fun itShowsNothingOfTheAccountAndCannotBeSwipedAway() {
val notification = wakeNotification(app, WakeState.Listening("Hey Assistant"))
assertEquals(Notification.VISIBILITY_PUBLIC, notification.visibility)
assertEquals(Notification.FLAG_ONGOING_EVENT, notification.flags and Notification.FLAG_ONGOING_EVENT)
assertEquals(1, notification.actions.size)
}
}
@@ -1,13 +1,95 @@
package eu.llembas.android
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.checkKeywords
import eu.llembas.android.wake.unpackWakeModel
import eu.llembas.android.wake.wakeBackoff
import eu.llembas.android.wake.wakeKeywords
import eu.llembas.android.wake.wakePause
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
class WakeTest {
@get:Rule
val folder = TemporaryFolder()
private val files = listOf("encoder.int8.onnx", "tokens.txt")
/** The APK's assets as [unpackWakeModel] opens them: by stream, counted. */
private class Assets(private val content: Map<String, String>) : (String) -> InputStream {
var opened = 0
override fun invoke(name: String): InputStream {
if (name != "version") opened++
return content[name]?.byteInputStream() ?: throw FileNotFoundException(name)
}
}
@Test
fun theModelIsCopiedOncePerVersion() {
val dir = File(folder.root, "wakeword")
val first = Assets(mapOf("version" to "aaaa\n", "encoder.int8.onnx" to "model one", "tokens.txt" to "A 1"))
unpackWakeModel(first, dir, files)
assertEquals("model one", File(dir, "encoder.int8.onnx").readText())
assertEquals(2, first.opened)
// The same version again: nothing is copied.
unpackWakeModel(first, dir, files)
assertEquals(2, first.opened)
// An update brings another model: it replaces the old one, though the file names are the same.
val second = Assets(mapOf("version" to "bbbb\n", "encoder.int8.onnx" to "model two, longer", "tokens.txt" to "A 1"))
unpackWakeModel(second, dir, files)
assertEquals("model two, longer", File(dir, "encoder.int8.onnx").readText())
assertFalse(File(dir, "encoder.int8.onnx.part").exists())
}
@Test
fun aCopyThatWasCutShortIsMadeAgain() {
val dir = File(folder.root, "wakeword")
// The second file is not in the APK: the copy fails, loudly, and leaves no marker.
val broken = Assets(mapOf("version" to "aaaa", "encoder.int8.onnx" to "model"))
assertThrows(FileNotFoundException::class.java) { unpackWakeModel(broken, dir, files) }
assertFalse(File(dir, "version").exists())
val whole = Assets(mapOf("version" to "aaaa", "encoder.int8.onnx" to "model", "tokens.txt" to "A 1"))
unpackWakeModel(whole, dir, files)
assertEquals(2, whole.opened)
// A file that went missing afterwards (storage cleared in part) is noticed too.
File(dir, "tokens.txt").delete()
unpackWakeModel(whole, dir, files)
assertEquals(4, whole.opened)
}
@Test
fun aPieceTheModelDoesNotKnowNeverReachesTheEngine() {
val tokens = "<blk> 0\n▁HE 5\nY 6\n▁AS 7\nS 3\nIST 8\nANT 9\n"
checkKeywords("▁HE Y ▁AS S IST ANT :1.5 #0.25 @hey_assistant\n", tokens)
val refused = assertThrows(WakeError::class.java) { checkKeywords("▁HE Y ▁LE M B AS @hey_lembas\n", tokens) }
assertEquals(WakeFailure.Engine, refused.why)
assertTrue(refused.detail.contains("▁LE"))
}
@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"))
}
@Test
fun retriesBackOff() {
assertEquals(listOf(2_000L, 5_000L, 15_000L, 60_000L, 300_000L, 300_000L), (0..5).map(::wakeBackoff))
}
@Test
fun itListensOnlyWhenNothingStandsInTheWay() {
assertEquals(WakePause.None, wakePause(screenOn = true, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = true))
+8 -1
View File
@@ -6,7 +6,9 @@
The engine is sherpa-onnx (Apache-2.0, k2-fsa): its Android library, as the project publishes it
on its GitHub releases (onnxruntime inside, MIT). The model is its English keyword spotter,
`sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01` (Apache-2.0, trained with icefall), of
which the int8 encoder, decoder and joiner and the token table go into the APK's assets.
which the int8 encoder, decoder and joiner and the token table go into the APK's assets, beside a
`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.
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
@@ -40,6 +42,8 @@ FILES = {
"joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx": ("joiner.int8.onnx", "eae9da0c7e1e6c6a3f4cc42d167899c388f6c6701b94cb96320e4f55df79624c"),
"tokens.txt": ("tokens.txt", "fd2ded4050a55d2b1578870ba8697d02371980217806b7558bd0a5cc60f3ba53"),
}
# 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]
def sha(data: bytes) -> str:
@@ -66,7 +70,9 @@ def main() -> None:
AAR.write_bytes(download(AAR_URL, AAR_SHA))
print(f"fetch-wakeword: {AAR.relative_to(ROOT)}")
wanted = {ASSETS / name: digest for name, digest in FILES.values()}
version = ASSETS / "version"
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")
return
archive = tarfile.open(fileobj=io.BytesIO(download(MODEL_URL, MODEL_SHA)), mode="r:bz2")
@@ -76,6 +82,7 @@ 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)
version.write_text(MODEL_VERSION + "\n")
print(f"fetch-wakeword: {ASSETS.relative_to(ROOT)} ({len(FILES)} files)")
+10 -1
View File
@@ -435,11 +435,20 @@ STRINGS: dict[str, str] = {
"wake_word_privacy": "Nothing leaves the phone before the word. The microphone's sound goes only to the wake-word engine on the phone and is not kept, and the notification stays up the whole time it listens. The phrases are English; the engine is sherpa-onnx (open source).",
"wake_word_cost": "It costs battery: the microphone stays on and the phone's processor checks every moment of sound, without the low-power chip the built-in assistant uses. It pauses in battery saver, while the assistant is open and, unless you change it, with the screen off. After a restart, tap its notification to start it again.",
"wake_listening_for": "Listening for “%1$s”",
"wake_off": "The wake word is not listening",
"wake_tap_to_start": "Tap to start it again. If Android asks, allow the microphone.",
"wake_starting": "Starting the wake word…",
"wake_paused_silent": "Wake word hears nothing: another app has the microphone, or the phone's microphone is switched off",
"wake_failed_no_engine": "Wake word is not working: this build has no engine",
"wake_failed_model": "Wake word is not working: its model could not be unpacked on this phone",
"wake_failed_engine": "Wake word is not working: the engine did not start",
"wake_failed_microphone": "Wake word is not working: the microphone did not start",
"wake_failed_line": "It is not listening. It tries again by itself.",
"wake_notification_line": "Nothing leaves the phone until you say it.",
"wake_paused_screen": "Wake word paused: the screen is off",
"wake_paused_battery": "Wake word paused: battery saver is on",
"wake_paused_assistant": "Wake word paused while the assistant is open",
"wake_paused_microphone": "Wake word paused: the microphone or the engine is not available",
"wake_paused_microphone": "Wake word paused: LLeMbas is not allowed to use the microphone",
"wake_stop": "Stop listening",
"wake_heard": "Heard you. Tap to ask.",
"wake_resume": "Listen for the wake word again",
+80 -8
View File
@@ -269,18 +269,27 @@
"voice_input_phone_none": "Tento telefon nemá vlastní rozpoznávání řeči.",
"wake_battery": "Nechat běžet na pozadí",
"wake_battery_line": "Některé telefony (Samsung, Xiaomi, Huawei, OnePlus a další) kvůli baterii zastavují aplikace na pozadí, a s nimi i budicí slovo. Zde vyjměte LLeMbas z optimalizace baterie; dontkillmyapp.com vysvětluje nastavení vašeho telefonu.",
"wake_failed_engine": "Budicí slovo nefunguje: modul se nespustil",
"wake_failed_line": "Neposlouchá. Zkusí to znovu samo.",
"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_heard": "Slyšel jsem vás. Klepněte a ptejte se.",
"wake_listening_for": "Naslouchám frázi „%1$s“",
"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ý",
"wake_paused_battery": "Budicí slovo pozastaveno: je zapnutý úsporný režim",
"wake_paused_microphone": "Budicí slovo pozastaveno: mikrofon nebo modul není k dispozici",
"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_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_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.",
"wake_word": "Budicí slovo",
"wake_word_cost": "Stojí to baterii: mikrofon zůstává zapnutý a procesor telefonu kontroluje každý okamžik zvuku, bez úsporného čipu, který používá vestavěný asistent. Pozastaví se v úsporném režimu, když je asistent otevřený, a pokud to nezměníte, i při zhasnuté obrazovce. Po restartu ho znovu spustíte klepnutím na oznámení.",
"wake_word_line": "Ve výchozím stavu vypnuto. Řekněte frázi a asistent se otevře a poslouchá, nad jakoukoli aplikací na obrazovce.",
@@ -562,18 +571,27 @@
"voice_input_phone_none": "Dieses Telefon hat keine eigene Spracherkennung.",
"wake_battery": "Im Hintergrund laufen lassen",
"wake_battery_line": "Manche Telefone (Samsung, Xiaomi, Huawei, OnePlus und andere) beenden Hintergrund-Apps, um Akku zu sparen, und damit auch das Aktivierungswort. Nimm LLeMbas hier von der Akku-Optimierung aus; dontkillmyapp.com erklärt die Einstellungen deines Telefons.",
"wake_failed_engine": "Aktivierungswort funktioniert nicht: Die Engine ist nicht gestartet",
"wake_failed_line": "Es hört nicht zu. Es versucht es von selbst erneut.",
"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_heard": "Gehört. Tippe, um zu fragen.",
"wake_listening_for": "Hört auf „%1$s“",
"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",
"wake_paused_battery": "Aktivierungswort pausiert: Energiesparmodus ist an",
"wake_paused_microphone": "Aktivierungswort pausiert: Mikrofon oder Engine nicht verfügbar",
"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_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_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.",
"wake_word": "Aktivierungswort",
"wake_word_cost": "Es kostet Akku: Das Mikrofon bleibt an, und der Prozessor des Telefons prüft jeden Moment Ton, ohne den Stromspar-Chip, den der eingebaute Assistent nutzt. Es pausiert im Energiesparmodus, während der Assistent offen ist und, wenn du es nicht änderst, bei ausgeschaltetem Bildschirm. Nach einem Neustart tippe auf seine Benachrichtigung, um es wieder zu starten.",
"wake_word_line": "Standardmäßig aus. Sag den Satz, und der Assistent öffnet sich zuhörend über der App auf dem Bildschirm.",
@@ -854,18 +872,27 @@
"voice_input_phone_none": "Este teléfono no tiene reconocimiento de voz propio.",
"wake_battery": "Dejar que funcione en segundo plano",
"wake_battery_line": "Algunos teléfonos (Samsung, Xiaomi, Huawei, OnePlus y otros) detienen las apps en segundo plano para ahorrar batería, y con ellas la palabra de activación. Excluye aquí a LLeMbas de la optimización de batería; dontkillmyapp.com explica los ajustes de tu teléfono.",
"wake_failed_engine": "La palabra de activación no funciona: el motor no se inició",
"wake_failed_line": "No está escuchando. Lo intenta de nuevo por sí sola.",
"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_heard": "Te he oído. Toca para preguntar.",
"wake_listening_for": "Escuchando «%1$s»",
"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",
"wake_paused_battery": "Palabra de activación en pausa: ahorro de batería activado",
"wake_paused_microphone": "Palabra de activación en pausa: el micrófono o el motor no están disponibles",
"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_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_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.",
"wake_word": "Palabra de activación",
"wake_word_cost": "Gasta batería: el micrófono sigue encendido y el procesador del teléfono revisa cada instante de sonido, sin el chip de bajo consumo que usa el asistente integrado. Se pausa en ahorro de batería, mientras el asistente está abierto y, salvo que lo cambies, con la pantalla apagada. Tras reiniciar, toca su notificación para volver a iniciarlo.",
"wake_word_line": "Desactivado por defecto. Di la frase y el asistente se abre escuchando, sobre la app que esté en pantalla.",
@@ -1147,18 +1174,27 @@
"voice_input_phone_none": "Ce téléphone n’a pas de reconnaissance vocale propre.",
"wake_battery": "Le laisser tourner en arrière-plan",
"wake_battery_line": "Certains téléphones (Samsung, Xiaomi, Huawei, OnePlus et d’autres) arrêtent les apps en arrière-plan pour économiser la batterie, et le mot d’activation avec. Exemptez ici LLeMbas de l’optimisation de la batterie ; dontkillmyapp.com explique les réglages de votre téléphone.",
"wake_failed_engine": "Le mot d’activation ne fonctionne pas : le moteur n’a pas démarré",
"wake_failed_line": "Il n’écoute pas. Il réessaie de lui-même.",
"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_heard": "Entendu. Touchez pour demander.",
"wake_listening_for": "À l’écoute de « %1$s »",
"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",
"wake_paused_battery": "Mot d’activation en pause : économiseur de batterie activé",
"wake_paused_microphone": "Mot d’activation en pause : micro ou moteur indisponible",
"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_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_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.",
"wake_word": "Mot d’activation",
"wake_word_cost": "Cela consomme de la batterie : le micro reste allumé et le processeur du téléphone examine chaque instant de son, sans la puce basse consommation de l’assistant intégré. Il se met en pause en économie de batterie, quand l’assistant est ouvert et, sauf si vous le changez, écran éteint. Après un redémarrage, touchez sa notification pour le relancer.",
"wake_word_line": "Désactivé par défaut. Dites la phrase et l’assistant s’ouvre en écoute, par-dessus l’app à l’écran.",
@@ -1440,18 +1476,27 @@
"voice_input_phone_none": "Ennek a telefonnak nincs saját beszédfelismerője.",
"wake_battery": "Futhasson a háttérben",
"wake_battery_line": "Egyes telefonok (Samsung, Xiaomi, Huawei, OnePlus és mások) az akkumulátor kímélése miatt leállítják a háttéralkalmazásokat, és velük az ébresztőszót is. Itt vedd ki a LLeMbast az akkumulátor-optimalizálásból; a dontkillmyapp.com elmagyarázza a telefonod beállításait.",
"wake_failed_engine": "Az ébresztőszó nem működik: a motor nem indult el",
"wake_failed_line": "Nem figyel. Magától újrapróbálja.",
"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_heard": "Hallottalak. Koppints a kérdezéshez.",
"wake_listening_for": "Figyeli: „%1$s”",
"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",
"wake_paused_battery": "Ébresztőszó szünetel: be van kapcsolva az energiatakarékos mód",
"wake_paused_microphone": "Ébresztőszó szünetel: a mikrofon vagy a motor nem érhető el",
"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_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_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.",
"wake_word": "Ébresztőszó",
"wake_word_cost": "Akkumulátorba kerül: a mikrofon bekapcsolva marad, és a telefon processzora minden hangpillanatot ellenőriz, a beépített asszisztens energiatakarékos chipje nélkül. Energiatakarékos módban, nyitott asszisztensnél és — ha nem változtatod meg — kikapcsolt képernyőnél szünetel. Újraindítás után koppints az értesítésére az újraindításhoz.",
"wake_word_line": "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.",
@@ -1732,18 +1777,27 @@
"voice_input_phone_none": "Questo telefono non ha un riconoscimento vocale proprio.",
"wake_battery": "Lascialo funzionare in background",
"wake_battery_line": "Alcuni telefoni (Samsung, Xiaomi, Huawei, OnePlus e altri) fermano le app in background per risparmiare batteria, e con loro la parola di attivazione. Escludi qui LLeMbas dall’ottimizzazione della batteria; dontkillmyapp.com spiega le impostazioni del tuo telefono.",
"wake_failed_engine": "La parola di attivazione non funziona: il motore non si è avviato",
"wake_failed_line": "Non è in ascolto. Riprova da sola.",
"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_heard": "Ti ho sentito. Tocca per chiedere.",
"wake_listening_for": "In ascolto di «%1$s»",
"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",
"wake_paused_battery": "Parola di attivazione in pausa: risparmio energetico attivo",
"wake_paused_microphone": "Parola di attivazione in pausa: microfono o motore non disponibili",
"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_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_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.",
"wake_word": "Parola di attivazione",
"wake_word_cost": "Consuma batteria: il microfono resta acceso e il processore del telefono esamina ogni istante di suono, senza il chip a basso consumo usato dall’assistente integrato. Si mette in pausa con il risparmio energetico, mentre l’assistente è aperto e, se non lo cambi, a schermo spento. Dopo un riavvio, tocca la sua notifica per riavviarlo.",
"wake_word_line": "Disattivata per impostazione predefinita. Di’ la frase e l’assistente si apre in ascolto, sopra l’app sullo schermo.",
@@ -2024,18 +2078,27 @@
"voice_input_phone_none": "Ten telefon nie ma własnego rozpoznawania mowy.",
"wake_battery": "Pozwól działać w tle",
"wake_battery_line": "Niektóre telefony (Samsung, Xiaomi, Huawei, OnePlus i inne) zatrzymują aplikacje w tle, by oszczędzać baterię, a z nimi słowo aktywujące. Wyłącz tu LLeMbas z optymalizacji baterii; dontkillmyapp.com wyjaśnia ustawienia Twojego telefonu.",
"wake_failed_engine": "Słowo aktywujące nie działa: silnik się nie uruchomił",
"wake_failed_line": "Nie nasłuchuje. Spróbuje ponownie samo.",
"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_heard": "Słyszę. Dotknij, aby zapytać.",
"wake_listening_for": "Nasłuchuje „%1$s”",
"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",
"wake_paused_battery": "Słowo aktywujące wstrzymane: oszczędzanie baterii jest włączone",
"wake_paused_microphone": "Słowo aktywujące wstrzymane: mikrofon lub silnik jest niedostępny",
"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_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_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.",
"wake_word": "Słowo aktywujące",
"wake_word_cost": "Zużywa baterię: mikrofon pozostaje włączony, a procesor telefonu sprawdza każdą chwilę dźwięku, bez energooszczędnego układu, którego używa wbudowany asystent. Wstrzymuje się w trybie oszczędzania baterii, gdy asystent jest otwarty, i — jeśli tego nie zmienisz — przy wyłączonym ekranie. Po ponownym uruchomieniu dotknij jego powiadomienia, by znów zaczął.",
"wake_word_line": "Domyślnie wyłączone. Powiedz frazę, a asystent otworzy się i zacznie słuchać, nad aplikacją na ekranie.",
@@ -2316,18 +2379,27 @@
"voice_input_phone_none": "Tento telefón nemá vlastné rozpoznávanie reči.",
"wake_battery": "Nechať bežať na pozadí",
"wake_battery_line": "Niektoré telefóny (Samsung, Xiaomi, Huawei, OnePlus a ďalšie) kvôli batérii zastavujú aplikácie na pozadí, a s nimi aj budiace slovo. Tu vyjmite LLeMbas z optimalizácie batérie; dontkillmyapp.com vysvetľuje nastavenia vášho telefónu.",
"wake_failed_engine": "Budiace slovo nefunguje: modul sa nespustil",
"wake_failed_line": "Nepočúva. Skúsi to znova samo.",
"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_heard": "Počul som vás. Ťuknite a pýtajte sa.",
"wake_listening_for": "Počúvam frázu „%1$s“",
"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ý",
"wake_paused_battery": "Budiace slovo pozastavené: je zapnutý úsporný režim",
"wake_paused_microphone": "Budiace slovo pozastavené: mikrofón alebo modul nie je k dispozícii",
"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_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_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.",
"wake_word": "Budiace slovo",
"wake_word_cost": "Stojí to batériu: mikrofón zostáva zapnutý a procesor telefónu kontroluje každý okamih zvuku, bez úsporného čipu, ktorý používa vstavaný asistent. Pozastaví sa v úspornom režime, keď je asistent otvorený, a ak to nezmeníte, aj pri zhasnutej obrazovke. Po reštarte ho znova spustíte ťuknutím na oznámenie.",
"wake_word_line": "Predvolene vypnuté. Povedzte frázu a asistent sa otvorí a počúva, nad akoukoľvek aplikáciou na obrazovke.",