diff --git a/CHANGELOG.md b/CHANGELOG.md index b90154f..f540f24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,29 @@ is in alpha and releases come off `main`. one line each, side by side. With no computer linked, Agent chat is still there and says how to link one -- install the LLeMbas CLI, `lembas login` to this instance, allow remote work and start the service, each command with Copy -- with **Check again**. +- **The assistant is a sheet over the app you are in**, not a full screen. Holding the power + button raises it to half the height, with the app still in sight under it; drag its handle up + for the full height, down (or Back, or a tap outside) to close it. + - **The microphone first**: it opens listening, and the words appear as you say them. A pause + sends them; tap the microphone to send at once, or the keyboard to type instead. (Settings › + Assistant can turn the listening off.) + - **The model and the connection** at the top: the model's picture and name, the instance and + a dot that says whether it answers; a tap picks another model, which the assistant keeps. + - **Use screen**: when Android hands the assistant the screen (its text, a screenshot, or + both), one tap sends it with your next question -- never without the tap. Quick actions do + it in one go: **Summarise this**, **Translate this**, **Explain this**. + - **Continue the last chat** the assistant made, from where it stopped; and every question in + the sheet carries on the same chat, until **New chat**. + - **Voice reply**: a spoken question is answered aloud through your instance's text-to-speech + (switch it off at the top), and **Read aloud** reads any answer. + - **Open in app** carries on the same chat in the app. + - Why there is no wake word is said where you look for one: on stock Android only the + assistant built into the phone may listen for one. +- **Settings › Voice input** says what each choice is: **LLeMbas** is your instance's + speech-to-text, through the server -- the recording goes to your instance and nowhere else; + **Phone (Google or the system's)** is the phone's own recogniser -- words appear as you speak, + and the recording goes wherever that recogniser sends it. No Google library is in the app: it + uses whichever recogniser the phone has, and says so when it has none. ## [1.0.0-beta.4] — 2026-11-09 diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3466712..cd87e0f 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -11,6 +11,10 @@ + + + + if (granted) controller.listen() } @@ -46,13 +42,16 @@ class AssistActivity : ComponentActivity() { setShowWhenLocked(true) controller = AssistController(this, lifecycleScope) val keyguard = getSystemService(KeyguardManager::class.java) + locked.value = keyguard.isKeyguardLocked val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty() + val wantsMic = intent.getBooleanExtra(EXTRA_LISTEN, false) if (keyguard.isKeyguardLocked) { keyguard.requestDismissKeyguard( this, object : KeyguardManager.KeyguardDismissCallback() { override fun onDismissSucceeded() { - if (waiting.isNotBlank()) controller.ask(waiting) + locked.value = false + if (waiting.isNotBlank()) controller.ask(waiting) else controller.opened(locked = false) } override fun onDismissCancelled() = finish() @@ -62,38 +61,35 @@ class AssistActivity : ComponentActivity() { ) } else if (waiting.isNotBlank()) { controller.ask(waiting) + } else if (wantsMic && !controller.micAllowed()) { + mic.launch(Manifest.permission.RECORD_AUDIO) + } else { + controller.opened(locked = false) } setContent { val prefs by lembas.instances.prefs.collectAsState(initial = Prefs()) LembasTheme(prefs.theme) { - Box( - Modifier - .fillMaxSize() - .background(Color.Black.copy(alpha = 0.4f)) - .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { finish() } - .imePadding(), - contentAlignment = Alignment.BottomCenter, - ) { - Box(Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}) { - AssistPanel( - controller = controller, - locked = keyguard.isKeyguardLocked, - onUnlockAndAsk = { text -> - keyguard.requestDismissKeyguard( - this@AssistActivity, - object : KeyguardManager.KeyguardDismissCallback() { - override fun onDismissSucceeded() = controller.ask(text) - }, - ) + AssistPanel( + controller = controller, + locked = locked.value, + onUnlockAndAsk = { text -> + keyguard.requestDismissKeyguard( + this@AssistActivity, + object : KeyguardManager.KeyguardDismissCallback() { + override fun onDismissSucceeded() { + locked.value = false + if (text.isBlank()) controller.opened(locked = false) else controller.ask(text) + } }, - onOpenApp = { - startActivity(controller.appIntent()) - finish() - }, - onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) }, ) - } - } + }, + onOpenApp = { + startActivity(controller.appIntent()) + finish() + }, + onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) }, + onDismiss = { finish() }, + ) } } } @@ -105,5 +101,8 @@ class AssistActivity : ComponentActivity() { companion object { const val EXTRA_QUESTION = "eu.llembas.android.QUESTION" + + /** Handed over by the session: ask for the microphone, then listen. */ + const val EXTRA_LISTEN = "eu.llembas.android.LISTEN" } } diff --git a/app/src/main/java/eu/llembas/android/assist/AssistController.kt b/app/src/main/java/eu/llembas/android/assist/AssistController.kt index e9ac13f..7548b73 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistController.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistController.kt @@ -1,120 +1,385 @@ package eu.llembas.android.assist +import android.Manifest import android.content.Context import android.content.Intent +import android.content.pm.PackageManager import android.graphics.Bitmap +import android.speech.SpeechRecognizer +import androidx.core.content.ContextCompat import eu.llembas.android.MainActivity +import eu.llembas.android.R +import eu.llembas.android.api.ApiException import eu.llembas.android.api.LiveReply +import eu.llembas.android.api.ModelInfo +import eu.llembas.android.api.Step import eu.llembas.android.api.StreamClient +import eu.llembas.android.auth.Prefs import eu.llembas.android.lembas import eu.llembas.android.push.Notifications import eu.llembas.android.ui.explain import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive import java.io.ByteArrayOutputStream +/** One question asked in the sheet and its answer: written now ([reply]), or read back ([earlier]). */ +data class AssistTurn(val question: String, val reply: LiveReply? = null, val earlier: List = emptyList()) { + val steps: List get() = reply?.finished?.steps ?: reply?.shown ?: earlier + val writing: Boolean get() = reply != null && reply.finished == null && !reply.closed +} + +/** Whether the instance answers: being asked, yes, or no (and why). */ +enum class Connection { Checking, Online, Offline } + +/** The last chat the assistant made, offered to be continued. */ +data class LastAssist(val chatId: String, val title: String, val at: Long) + data class AssistUiState( val signedIn: Boolean = true, + val instanceName: String = "", + val connection: Connection = Connection.Checking, + val models: List = emptyList(), + val modelId: String? = null, val listening: Boolean = false, + /** The words heard so far, while listening and while the last of them is written down. */ + val heard: String = "", + /** How loud the microphone hears it, 0..1. */ + val level: Float = 0f, val busy: Boolean = false, - val asked: String? = null, + val turns: List = emptyList(), val chatId: String? = null, - val reply: LiveReply? = null, val error: String? = null, /** Whether the screen goes with the question. Off until the person turns it on, every time. */ val includeScreen: Boolean = false, - val screenAvailable: Boolean = false, -) + val screenText: Boolean = false, + val screenshot: Bitmap? = null, + val last: LastAssist? = null, + /** Whether a spoken question is answered aloud too. */ + val voiceReply: Boolean = true, + /** Whether the instance can read aloud (its text-to-speech, for this account). */ + val canSpeak: Boolean = false, + val speaking: Boolean = false, + /** Whether anything can turn speech into words: the instance's speech-to-text, or the phone's. */ + val canListen: Boolean = true, +) { + val screenAvailable: Boolean get() = screenText || screenshot != null + val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId } + val empty: Boolean get() = turns.isEmpty() +} /** - * The assistant's one job: take a question -- typed or spoken -- start a chat with it on the - * instance, and stream the answer back into the sheet. Shared by the voice-interaction session - * (power button, assist gesture) and [AssistActivity] (the tile, the shortcut, the lock screen - * path), so both behave the same. - * - * The chat is an ordinary one: it is in the list on the phone and on the web afterwards. The - * Settings switch "assistant chats are temporary" makes them temporary instead. + * What the sheet can do. Every method does nothing by default, so the screenshot tests can draw + * the sheet with no controller behind it. */ -class AssistController(private val context: Context, private val scope: CoroutineScope) { +interface AssistActions { + fun listen() {} + fun heard() {} + fun type() {} + fun ask(question: String) {} + fun includeScreen(on: Boolean) {} + fun quick(prompt: String) {} + fun continueLast() {} + fun newChat() {} + fun pickModel(id: String) {} + fun voiceReply(on: Boolean) {} + fun readAloud() {} + fun stopReading() {} +} + +/** + * The assistant: take a question -- spoken or typed -- start a chat with it on the instance (or + * carry on the one this sheet is in), and stream the answer back into the sheet. Shared by the + * voice-interaction session (power button, assist gesture) and [AssistActivity] (the tile, the + * shortcut, the lock-screen path), so both behave the same. + * + * A chat it makes is an ordinary one: in the list on the phone and on the web afterwards, and + * "Open in app" continues it there. Settings' "assistant chats are temporary" makes them + * temporary instead. + * + * Speech in is Settings › Voice input: the instance's speech-to-text (the words are written down + * a moment behind, from the recording so far, and a pause in speech sends it), or the phone's + * own recogniser (the words as they are said). Speech out is the instance's text-to-speech. + */ +class AssistController(private val context: Context, private val scope: CoroutineScope) : AssistActions { private val _state = MutableStateFlow(AssistUiState()) val state = _state.asStateFlow() private val recorder = Recorder(scope) + private val phone = PhoneRecognizer(context) private val speaker = Speaker(context) private var following: Job? = null + private var hearing: Job? = null + private var usingPhone = false private var screenText: String? = null - private var screenshot: Bitmap? = null + private var stt: Boolean? = null + private val ready: Job init { - scope.launch { _state.update { it.copy(signedIn = context.lembas.instances.current() != null) } } + ready = scope.launch { load() } + scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } } } + /** The instance, its models and what it offers this account; the choices kept in Settings. */ + private suspend fun load() { + val store = context.lembas.instances + val instance = store.current() + val prefs = store.prefs.first() + _state.update { + it.copy( + signedIn = instance != null, + instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(), + voiceReply = prefs.readAloudSpoken, + last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary } + ?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) }, + ) + } + val api = instance?.let { store.clientFor(it) } ?: return + try { + val me = api.me() + val models = api.models() + stt = me.services["stt"] + val chosen = prefs.assistantModel.takeIf { id -> models.any { it.id == id } } + ?: me.defaultModel?.takeIf { id -> models.any { it.id == id } } + ?: models.firstOrNull { it.default }?.id + ?: models.firstOrNull()?.id + _state.update { + it.copy( + connection = Connection.Online, + models = models, + modelId = it.modelId ?: chosen, + canSpeak = me.services["tts"] == true, + canListen = me.services["stt"] == true || PhoneRecognizer.available(context), + ) + } + } catch (e: Exception) { + _state.update { it.copy(connection = Connection.Offline, error = context.explain(e)) } + } + } + + /** + * The sheet came up. It starts listening at once -- the microphone first, as an assistant + * opens -- unless Settings says not to, the phone is locked (nothing is sent from the lock + * screen), or the microphone is not allowed yet (that needs an activity to ask). + */ + fun opened(locked: Boolean) { + scope.launch { + ready.join() + val prefs = context.lembas.instances.prefs.first() + val s = _state.value + if (s.signedIn && !locked && prefs.assistantListens && s.canListen && s.empty && !s.listening && micAllowed()) listen() + } + } + + fun micAllowed(): Boolean = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + fun offerScreen(text: String?, image: Bitmap?) { if (!text.isNullOrBlank()) screenText = text.take(MAX_SCREEN_CHARS) - if (image != null) screenshot = image - _state.update { it.copy(screenAvailable = screenText != null || screenshot != null) } + _state.update { it.copy(screenText = screenText != null, screenshot = image ?: it.screenshot) } } - fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) } + override fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) } + + // --- Speech in --------------------------------------------------------------------------- + + /** Which recogniser: the one Settings names, else whichever this phone and instance have. */ + private suspend fun phoneEngine(): Boolean { + val wanted = context.lembas.instances.prefs.first().voiceInput + val phoneHas = PhoneRecognizer.available(context) + return when { + wanted == Prefs.VOICE_PHONE && phoneHas -> true + stt == false && phoneHas -> true + else -> false + } + } @android.annotation.SuppressLint("MissingPermission") - fun listen() { + override fun listen() { + if (_state.value.listening || !micAllowed()) return speaker.stop() - recorder.start() - _state.update { it.copy(listening = true, error = null) } - } - - /** Stop listening, write down what was said, and ask it. */ - fun heard() { - scope.launch { - val wav = recorder.stop() - _state.update { it.copy(listening = false) } - if (wav.isEmpty()) return@launch - try { - _state.update { it.copy(busy = true) } - val text = context.lembas.instances.client()?.transcribe(wav).orEmpty() - _state.update { it.copy(busy = false) } - if (text.isNotBlank()) ask(text, spoken = true) - } catch (e: Exception) { - _state.update { it.copy(busy = false, error = context.explain(e)) } + hearing?.cancel() + _state.update { it.copy(listening = true, heard = "", level = 0f, error = null) } + hearing = scope.launch { + usingPhone = phoneEngine() + if (usingPhone) { + phone.start( + onPartial = { words -> _state.update { it.copy(heard = words) } }, + onLevel = { l -> _state.update { it.copy(level = l) } }, + onResult = { words -> + _state.update { it.copy(listening = false, level = 0f, heard = "") } + if (words.isNotBlank()) ask(words, spoken = true) + }, + onFail = { code -> + val quiet = code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT + _state.update { + it.copy( + listening = false, + level = 0f, + error = if (quiet) null else context.getString(R.string.assist_recogniser_failed), + ) + } + }, + ) + } else { + recorder.start() + launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } } + launch { writeDownAsSaid() } + // Nothing said is nothing sent: a speech-to-text model asked to write down + // silence tends to invent a sentence. + if (untilQuiet()) heard() else type() } } } - fun ask(question: String, spoken: Boolean = false) { + /** + * The instance's speech-to-text takes a whole recording, so words "as they are said" are the + * recording so far, written down again every moment -- one request at a time, only when half + * a second more has been said, and not past the first minute. + */ + private suspend fun writeDownAsSaid() { + val api = context.lembas.instances.client() ?: return + var sent = 0f + while (scope.isActive) { + delay(PARTIAL_EVERY_MS) + val seconds = recorder.seconds + if (seconds - sent < 0.5f || seconds > 60f) continue + sent = seconds + val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull() + if (!words.isNullOrBlank() && _state.value.listening) _state.update { it.copy(heard = words) } + } + } + + /** Wait for a pause after speech (true) -- or for nothing said at all, which gives up (false). */ + private suspend fun untilQuiet(): Boolean { + var spoke = false + var quietFor = 0L + var waited = 0L + // The words written down so far are the second ear, for a quiet microphone: words the + // instance heard mean speech, and the same words for a while mean it ended. + var words = "" + var sameWordsFor = 0L + while (true) { + delay(TICK_MS) + waited += TICK_MS + val level = recorder.level.value + if (level >= SPEAKING) { + spoke = true + quietFor = 0 + } else if (level < QUIET) { + quietFor += TICK_MS + } + val heard = _state.value.heard + if (heard.isNotBlank()) spoke = true + if (heard != words) { + words = heard + sameWordsFor = 0 + } else if (heard.isNotBlank()) { + sameWordsFor += TICK_MS + } + if (spoke && quietFor >= PAUSE_MS) return true + if (sameWordsFor >= SAME_WORDS_MS) return true + if (!spoke && waited >= NOTHING_SAID_MS) return false + if (waited >= LONGEST_MS) return spoke + } + } + + /** Stop listening, write down what was said, and ask it. */ + override fun heard() { + if (!_state.value.listening) return + if (usingPhone) { + phone.finish() + return + } + hearing?.cancel() + hearing = null + scope.launch { + val wav = recorder.stop() + _state.update { it.copy(listening = false, level = 0f) } + if (wav.size <= 44 + Recorder.RATE / 2) { + _state.update { it.copy(heard = "") } + return@launch + } + try { + _state.update { it.copy(busy = true) } + val text = context.lembas.instances.client()?.transcribe(wav).orEmpty() + _state.update { it.copy(busy = false, heard = "") } + if (text.isNotBlank()) ask(text, spoken = true) + } catch (e: Exception) { + _state.update { it.copy(busy = false, heard = "", error = context.explain(e)) } + } + } + } + + /** Stop listening and keep nothing: the person would rather type. */ + override fun type() { + hearing?.cancel() + hearing = null + phone.stop() + scope.launch { recorder.stop() } + _state.update { it.copy(listening = false, heard = "", level = 0f) } + } + + // --- Asking ------------------------------------------------------------------------------ + + override fun ask(question: String) = ask(question, spoken = false) + + override fun quick(prompt: String) { + _state.update { it.copy(includeScreen = true) } + ask(prompt, spoken = false) + } + + fun ask(question: String, spoken: Boolean) { if (question.isBlank()) return + if (_state.value.listening) type() following?.cancel() following = scope.launch { - _state.update { it.copy(busy = true, asked = question, reply = null, error = null) } + val turn = AssistTurn(question) + _state.update { it.copy(busy = true, turns = it.turns + turn, error = null) } try { - val api = context.lembas.instances.client() ?: error("Not signed in.") - val prefs = context.lembas.instances.prefs.first() - val withScreen = _state.value.includeScreen + val store = context.lembas.instances + val api = store.client() ?: throw ApiException(401, "Not signed in.") + val prefs = store.prefs.first() + val now = _state.value + val withScreen = now.includeScreen val attachments = buildList { - if (withScreen) { - screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot)).id) } - } + if (withScreen) now.screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot), now.chatId).id) } } val text = if (withScreen && screenText != null) "$question\n\n---\nOn my screen:\n\n$screenText" else question - val made = api.createChat(text, attachments, temporary = prefs.assistantTemporary) - _state.update { it.copy(chatId = made.chat.id) } - val reply = made.reply ?: return@launch - var live = LiveReply(reply.id) - StreamClient(api).follow(made.chat.id, reply.id).collect { frame -> + // The screen goes with one question, not every one after it. + _state.update { it.copy(includeScreen = false) } + val chatId = now.chatId + val replyId: String + val inChat: String + if (chatId != null) { + val sent = api.sendMessage(chatId, text, attachments) + inChat = chatId + replyId = sent.reply?.id ?: return@launch + } else { + val made = api.createChat(text, attachments, model = now.modelId, temporary = prefs.assistantTemporary) + inChat = made.chat.id + replyId = made.reply?.id ?: return@launch + _state.update { it.copy(chatId = inChat) } + if (!prefs.assistantTemporary) { + store.savePrefs { + it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis()) + } + } + } + var live = LiveReply(replyId) + StreamClient(api).follow(inChat, replyId).collect { frame -> live = live.apply(frame.event, frame.data) - _state.update { it.copy(reply = live, busy = live.finished == null) } - } - val finished = live.finished - if (spoken && prefs.readAloudSpoken && finished != null) { - val words = finished.steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() } - if (words.isNotBlank()) speaker.play(api.speech(plain(words))) + _state.update { s -> s.copy(turns = s.turns.dropLast(1) + turn.copy(reply = live), busy = live.finished == null) } } + if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null) speak(spokenWords(live.finished?.steps.orEmpty())) } catch (e: Exception) { _state.update { it.copy(error = context.explain(e)) } } finally { @@ -123,6 +388,74 @@ class AssistController(private val context: Context, private val scope: Coroutin } } + /** Carry on the last chat the assistant made: its last exchange shown, the next question sent to it. */ + override fun continueLast() { + val last = _state.value.last ?: return + scope.launch { + _state.update { it.copy(busy = true, error = null) } + try { + val api = context.lembas.instances.client() ?: return@launch + val detail = api.chat(last.chatId) + val question = detail.messages.lastOrNull { it.isUser } + val answer = detail.messages.lastOrNull { !it.isUser } + val turns = if (question != null) listOf(AssistTurn(question.text.orEmpty(), earlier = answer?.steps.orEmpty())) else emptyList() + _state.update { it.copy(chatId = last.chatId, turns = turns, modelId = detail.chat.model.ifBlank { null } ?: it.modelId, last = null) } + } catch (e: Exception) { + // A chat deleted since is simply not offered again. + if (e is ApiException && e.status == 404) { + context.lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) } + _state.update { it.copy(last = null) } + } else { + _state.update { it.copy(error = context.explain(e)) } + } + } finally { + _state.update { it.copy(busy = false) } + } + } + } + + override fun newChat() { + following?.cancel() + speaker.stop() + _state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false) } + } + + /** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */ + override fun pickModel(id: String) { + _state.update { it.copy(modelId = id) } + scope.launch { + context.lembas.instances.savePrefs { it.copy(assistantModel = id) } + val chat = _state.value.chatId ?: return@launch + runCatching { context.lembas.instances.client()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) } + .onFailure { e -> _state.update { it.copy(error = context.explain(e)) } } + } + } + + // --- Speech out -------------------------------------------------------------------------- + + override fun voiceReply(on: Boolean) { + if (!on) speaker.stop() + _state.update { it.copy(voiceReply = on) } + scope.launch { context.lembas.instances.savePrefs { it.copy(readAloudSpoken = on) } } + } + + override fun readAloud() { + val steps = _state.value.turns.lastOrNull()?.steps ?: return + scope.launch { speak(spokenWords(steps)) } + } + + override fun stopReading() = speaker.stop() + + private suspend fun speak(words: String) { + if (words.isBlank()) return + try { + val api = context.lembas.instances.client() ?: return + speaker.play(api.speech(words)) + } catch (e: Exception) { + _state.update { it.copy(error = context.explain(e)) } + } + } + /** Carry on in the app, at this chat. The caller starts it: a session and an activity * start activities differently. */ fun appIntent(): Intent = Intent(context, MainActivity::class.java) @@ -131,7 +464,9 @@ class AssistController(private val context: Context, private val scope: Coroutin fun close() { following?.cancel() + hearing?.cancel() speaker.stop() + phone.stop() scope.launch { recorder.stop() } } @@ -145,6 +480,21 @@ class AssistController(private val context: Context, private val scope: Coroutin companion object { const val MAX_SCREEN_CHARS = 8_000 + // Listening, for the instance's speech-to-text (the phone's recogniser finds the end of + // speech itself). Levels are the RMS of 16-bit samples, 0..1: a room is under 0.01, + // a voice near the phone 0.02 and up. Not tuned on many phones: the stop button always works. + private const val TICK_MS = 100L + private const val SPEAKING = 0.02f + private const val QUIET = 0.01f + private const val PAUSE_MS = 1_800L + private const val SAME_WORDS_MS = 4_500L + private const val NOTHING_SAID_MS = 8_000L + private const val LONGEST_MS = 120_000L + private const val PARTIAL_EVERY_MS = 1_200L + + /** A reply's words, for a voice: its text steps, without the markup. */ + fun spokenWords(steps: List): String = plain(steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() }) + /** Markdown as something a voice can read: no fences, marks or link targets. */ fun plain(markdown: String): String = markdown .replace(Regex("```[\\s\\S]*?```"), " ") diff --git a/app/src/main/java/eu/llembas/android/assist/AssistPanel.kt b/app/src/main/java/eu/llembas/android/assist/AssistPanel.kt index 8b6ea73..73ac5c9 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistPanel.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistPanel.kt @@ -1,120 +1,40 @@ -@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) - package eu.llembas.android.assist -import android.Manifest -import android.content.pm.PackageManager -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.Send -import androidx.compose.material.icons.filled.Mic -import androidx.compose.material.icons.filled.Stop -import androidx.compose.material3.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LinearProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TextField import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import androidx.core.content.ContextCompat -import eu.llembas.android.R -import eu.llembas.android.ui.chat.Steps /** - * The assistant's sheet: a question box, the microphone, "Include screen", and the answer as it - * is written. Nothing from the account -- no chat list, no history -- is on it, which is what - * lets it open over the lock screen (sending from there asks to unlock first: [locked]). + * The assistant's sheet with its [controller] behind it: [AssistSheetFrame] over the current app, + * [AssistSheetContent] in it. The session and [AssistActivity] differ only in what the four + * callbacks do: over the lock screen nothing is sent before Android unlocks ([onUnlockAndAsk]); + * the microphone's permission prompt needs an activity ([onNeedMic]). */ @Composable -fun AssistPanel(controller: AssistController, locked: Boolean, onUnlockAndAsk: (String) -> Unit, onOpenApp: () -> Unit, onNeedMic: () -> Unit) { +fun AssistPanel( + controller: AssistController, + locked: Boolean, + onUnlockAndAsk: (String) -> Unit, + onOpenApp: () -> Unit, + onNeedMic: () -> Unit, + onDismiss: () -> Unit, +) { val state by controller.state.collectAsState() - val context = LocalContext.current - var text by remember { mutableStateOf("") } - val focus = remember { FocusRequester() } - LaunchedEffect(Unit) { runCatching { focus.requestFocus() } } - - Surface( - shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp), - tonalElevation = 3.dp, - modifier = Modifier.fillMaxWidth(), - ) { - Column(Modifier.padding(16.dp).navigationBarsPadding(), verticalArrangement = Arrangement.spacedBy(10.dp)) { - if (!state.signedIn) { - Text(stringResource(R.string.assist_signed_out)) - TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_app)) } - return@Column - } - state.asked?.let { Text(it, style = MaterialTheme.typography.titleSmall) } - if (state.busy) LinearProgressIndicator(Modifier.fillMaxWidth()) - state.reply?.let { reply -> - Column(Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState())) { - Steps(reply.finished?.steps ?: reply.shown) + AssistSheetFrame(onDismiss = onDismiss) { handle, _ -> + AssistSheetContent( + state = state, + actions = controller, + locked = locked, + handle = handle, + onOpenApp = onOpenApp, + onSend = { text -> if (locked) onUnlockAndAsk(text) else controller.ask(text) }, + onMic = { + when { + locked -> onUnlockAndAsk("") + controller.micAllowed() -> controller.listen() + else -> onNeedMic() } - } - state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) } - if (state.screenAvailable && !locked) { - FilterChip( - selected = state.includeScreen, - onClick = { controller.includeScreen(!state.includeScreen) }, - label = { Text(stringResource(R.string.assist_include_screen)) }, - ) - } - Row(verticalAlignment = Alignment.CenterVertically) { - TextField( - value = text, - onValueChange = { text = it }, - placeholder = { Text(stringResource(if (state.listening) R.string.listening else R.string.assist_hint)) }, - modifier = Modifier.weight(1f).focusRequester(focus), - ) - IconButton(onClick = { - when { - locked -> onUnlockAndAsk(text) - - state.listening -> controller.heard() - - ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == - PackageManager.PERMISSION_GRANTED -> controller.listen() - - else -> onNeedMic() - } - }) { - Icon(if (state.listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate)) - } - IconButton(enabled = text.isNotBlank() && !state.busy, onClick = { - if (locked) onUnlockAndAsk(text) else controller.ask(text) - text = "" - }) { - Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) - } - } - if (state.chatId != null) { - TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_in_app)) } - } - } + }, + ) } } diff --git a/app/src/main/java/eu/llembas/android/assist/AssistService.kt b/app/src/main/java/eu/llembas/android/assist/AssistService.kt index 1a53984..5541fc4 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistService.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistService.kt @@ -5,13 +5,17 @@ import android.app.assist.AssistStructure import android.content.Context import android.content.Intent import android.graphics.Bitmap +import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.service.voice.VoiceInteractionService import android.service.voice.VoiceInteractionSession import android.service.voice.VoiceInteractionSessionService import android.view.View +import android.view.WindowManager +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.core.view.WindowCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry @@ -55,6 +59,7 @@ class LembasAssistSession(context: Context) : private val saved = SavedStateRegistryController.create(this) private var scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private var controller = AssistController(context, scope) + private val current = mutableStateOf(controller) override val lifecycle: Lifecycle get() = registry override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry @@ -63,6 +68,15 @@ class LembasAssistSession(context: Context) : super.onCreate() saved.performRestore(null) registry.currentState = Lifecycle.State.CREATED + // A see-through window over the whole screen: the sheet draws its own dim and sits at + // the bottom, the app underneath stays in sight, and the sheet moves with the keyboard. + window.window?.let { w -> + w.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT)) + w.setDimAmount(0f) + WindowCompat.setDecorFitsSystemWindows(w, false) + @Suppress("DEPRECATION") + w.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE) + } } override fun onCreateContentView(): View { @@ -74,15 +88,18 @@ class LembasAssistSession(context: Context) : setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow) setContent { LembasTheme(theme) { + // The controller is made again for each showing: read it from state, so the + // sheet follows the new one. AssistPanel( - controller = controller, + controller = current.value, locked = locked(), onUnlockAndAsk = { text -> handOff(text) }, onOpenApp = { - startAssistantActivity(controller.appIntent()) + startAssistantActivity(current.value.appIntent()) hide() }, - onNeedMic = { handOff("") }, + onNeedMic = { handOff("", listen = true) }, + onDismiss = { hide() }, ) } } @@ -91,16 +108,22 @@ class LembasAssistSession(context: Context) : override fun onShow(args: Bundle?, showFlags: Int) { super.onShow(args, showFlags) - if (!scope.isActiveScope()) { - scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) - controller = AssistController(context, scope) - } registry.currentState = Lifecycle.State.RESUMED + controller.opened(locked()) } + /** + * Each showing starts fresh -- a new question, the screen not included, listening first -- + * so a new controller is made as this one hides: ready for the screen the next invocation + * hands over, which may come before or after its `onShow`. + */ override fun onHide() { super.onHide() controller.close() + scope.cancel() + scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + controller = AssistController(context, scope) + current.value = controller registry.currentState = Lifecycle.State.CREATED } @@ -121,7 +144,7 @@ class LembasAssistSession(context: Context) : controller.offerScreen(text, null) } - /** And a picture of it, if allowed ("Use screenshot"). Sent only when "Include screen" is on. */ + /** And a picture of it, if allowed ("Use screenshot"). Sent only when "Use screen" is on. */ override fun onHandleScreenshot(screenshot: Bitmap?) { super.onHandleScreenshot(screenshot) controller.offerScreen(null, screenshot) @@ -140,14 +163,13 @@ class LembasAssistSession(context: Context) : * which asks Android to unlock first and only then sends it. The microphone's permission * prompt needs an activity too. */ - private fun handOff(text: String) { + private fun handOff(text: String, listen: Boolean = false) { startAssistantActivity( Intent(context, AssistActivity::class.java) .putExtra(AssistActivity.EXTRA_QUESTION, text) + .putExtra(AssistActivity.EXTRA_LISTEN, listen) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), ) hide() } - - private fun CoroutineScope.isActiveScope(): Boolean = coroutineContext[kotlinx.coroutines.Job]?.isActive == true } diff --git a/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt new file mode 100644 index 0000000..4ba1cae --- /dev/null +++ b/app/src/main/java/eu/llembas/android/assist/AssistSheet.kt @@ -0,0 +1,564 @@ +package eu.llembas.android.assist + +import android.text.format.DateUtils +import androidx.compose.animation.core.Animatable +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.draggable +import androidx.compose.foundation.gestures.rememberDraggableState +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBars +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.OpenInNew +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.automirrored.filled.VolumeOff +import androidx.compose.material.icons.automirrored.filled.VolumeUp +import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material.icons.filled.EditNote +import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.Keyboard +import androidx.compose.material.icons.filled.Lightbulb +import androidx.compose.material.icons.filled.Mic +import androidx.compose.material.icons.filled.ScreenshotMonitor +import androidx.compose.material.icons.filled.Stop +import androidx.compose.material.icons.filled.Summarize +import androidx.compose.material.icons.filled.Translate +import androidx.compose.material3.AssistChip +import androidx.compose.material3.AssistChipDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.scale +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalInspectionMode +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import eu.llembas.android.R +import eu.llembas.android.ui.ModelAvatar +import eu.llembas.android.ui.chat.Steps +import eu.llembas.android.ui.theme.LocalPalette +import kotlinx.coroutines.launch + +/** Where a let-go drag leaves the sheet. */ +enum class SheetStop { Half, Full, Gone } + +/** + * Where the sheet goes when a drag of its handle ends at [height] px moving at [velocity] px/s + * (positive is down), between [half] and [full]: a fling decides by its direction, a slow + * release by the nearest stop -- and below most of the half, it goes. + */ +fun settle(height: Float, half: Float, full: Float, velocity: Float): SheetStop = when { + velocity > FLING -> if (height < half + 1f) SheetStop.Gone else SheetStop.Half + velocity < -FLING -> SheetStop.Full + height < half * 0.6f -> SheetStop.Gone + height > (half + full) / 2f -> SheetStop.Full + else -> SheetStop.Half +} + +private const val FLING = 1_200f + +/** + * The assistant's window: the app it opened over stays in sight under a dim, and the sheet rises + * from the bottom to about half the height. Its handle drags it to the full height or down and + * away; a tap on the dim, or Back, closes it too. With the keyboard up, the sheet's stops are + * measured above the keyboard. + */ +@Composable +fun AssistSheetFrame(onDismiss: () -> Unit, content: @Composable ColumnScope.(handle: Modifier, expanded: Boolean) -> Unit) { + val palette = LocalPalette.current + val inspection = LocalInspectionMode.current + val scope = rememberCoroutineScope() + val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + Box( + Modifier + .fillMaxSize() + .background(Color.Black.copy(alpha = 0.32f)) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss) + .imePadding(), + ) { + BoxWithConstraints(Modifier.fillMaxSize()) { + val density = LocalDensity.current + val full = with(density) { (maxHeight - top - 8.dp).toPx() }.coerceAtLeast(0f) + val half = (full * 0.56f).coerceAtLeast(minOf(full, with(density) { 360.dp.toPx() })) + var expanded by remember { mutableStateOf(false) } + val target = if (expanded) full else half + val height = remember { Animatable(if (inspection) target else 0f) } + LaunchedEffect(target) { height.animateTo(target) } + val drag = rememberDraggableState { delta -> scope.launch { height.snapTo((height.value - delta).coerceIn(0f, full)) } } + val handle = Modifier.draggable( + drag, + Orientation.Vertical, + onDragStopped = { velocity -> + when (settle(height.value, half, full, velocity)) { + SheetStop.Gone -> { + height.animateTo(0f) + onDismiss() + } + + SheetStop.Full -> { + expanded = true + height.animateTo(full) + } + + SheetStop.Half -> { + expanded = false + height.animateTo(half) + } + } + }, + ) + Surface( + color = palette.surface, + contentColor = palette.ink, + shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp), + tonalElevation = 2.dp, + shadowElevation = 8.dp, + modifier = Modifier + .align(Alignment.BottomCenter) + .fillMaxWidth() + .height(with(density) { height.value.toDp() }) + // Taps inside the sheet are the sheet's, not the dim's. + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}, + ) { + Column(Modifier.fillMaxSize().navigationBarsPadding()) { content(handle, expanded) } + } + } + } +} + +/** + * The sheet's contents, from [state] alone (what the screenshot tests draw): + * + * - **the top**: the drag handle, the model and connection chip (the model's picture, its name, + * the instance and whether it answers; a tap picks another model), voice reply on or off, and + * Open in app, which carries on this same chat in the app; + * - **the middle**: before anything is asked, the last assistant chat to continue, the quick + * actions (the screen's, when the system handed one over), and how to open the assistant -- + * and that there is no wake word; then the questions and answers, the answers as they are + * written; + * - **the foot**: Use screen, then the microphone first -- while listening, the words as they are + * heard and how loud -- or the words typed, and Send. + * + * Nothing from the account is on it while the phone is [locked]: no model list, no last chat. + */ +@Composable +fun ColumnScope.AssistSheetContent( + state: AssistUiState, + actions: AssistActions, + locked: Boolean, + handle: Modifier = Modifier, + onOpenApp: () -> Unit = {}, + onSend: (String) -> Unit = actions::ask, + onMic: () -> Unit = actions::listen, +) { + val palette = LocalPalette.current + var text by remember { mutableStateOf("") } + val scroll = rememberScrollState() + val growth = state.turns.lastOrNull()?.steps?.sumOf { (it.markdown?.length ?: 0) + (it.text?.length ?: 0) } ?: 0 + LaunchedEffect(state.turns.size, growth) { if (state.turns.isNotEmpty()) scroll.animateScrollTo(scroll.maxValue) } + + // The top: the handle and the bar. Both drag the sheet. + Column(handle.fillMaxWidth()) { + Box(Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 6.dp), contentAlignment = Alignment.Center) { + Box(Modifier.size(width = 36.dp, height = 4.dp).background(palette.inkFaint, RoundedCornerShape(2.dp))) + } + Row(Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) { + val showChip = state.signedIn && !locked + Box(Modifier.weight(1f)) { + if (showChip) { + ModelChip(state, actions) + } else { + Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(8.dp)) + } + } + if (state.canSpeak && !locked) { + IconButton(onClick = { actions.voiceReply(!state.voiceReply) }) { + Icon( + if (state.voiceReply) Icons.AutoMirrored.Filled.VolumeUp else Icons.AutoMirrored.Filled.VolumeOff, + contentDescription = stringResource(if (state.voiceReply) R.string.assist_voice_reply_on else R.string.assist_voice_reply_off), + tint = if (state.voiceReply) palette.accent else palette.inkMuted, + ) + } + } + if (state.signedIn) { + IconButton(onClick = onOpenApp) { + Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = stringResource(R.string.assist_open_in_app), tint = palette.inkMuted) + } + } + } + if (state.busy) { + LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(2.dp)) + } else { + Spacer(Modifier.height(2.dp)) + } + } + + if (!state.signedIn) { + Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), verticalArrangement = Arrangement.Center) { + Text(stringResource(R.string.assist_signed_out), style = MaterialTheme.typography.bodyLarge) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_app)) } + } + return + } + + // The middle. + Column( + Modifier.weight(1f).fillMaxWidth().verticalScroll(scroll).padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + if (state.empty) { + Starting(state, actions, locked) + } else { + state.turns.forEachIndexed { i, turn -> + Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp) + } + } + state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) } + } + + // The foot. + Column(Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, top = 4.dp, bottom = 12.dp)) { + if (state.screenAvailable && !locked) ScreenToggle(state, actions) + if (state.listening) { + Listening(state, onDone = actions::heard, onType = actions::type) + } else { + val focus = remember { FocusRequester() } + Row(verticalAlignment = Alignment.CenterVertically) { + TextField( + value = text, + onValueChange = { text = it }, + placeholder = { Text(stringResource(if (state.busy && state.heard.isNotBlank()) R.string.assist_writing_down else R.string.assist_hint)) }, + shape = RoundedCornerShape(24.dp), + colors = TextFieldDefaults.colors( + focusedContainerColor = palette.surfaceRaised, + unfocusedContainerColor = palette.surfaceRaised, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + ), + maxLines = 4, + modifier = Modifier.weight(1f).heightIn(min = 52.dp).focusRequester(focus), + ) + Spacer(Modifier.width(8.dp)) + // One slot of fixed size: the microphone, or Send once there are words. + Box(Modifier.size(52.dp), contentAlignment = Alignment.Center) { + if (text.isBlank()) { + if (state.canListen) { + Surface( + onClick = onMic, + shape = CircleShape, + color = palette.accent, + contentColor = palette.accentInk, + modifier = Modifier.size(52.dp), + ) { + Box(contentAlignment = Alignment.Center) { Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate)) } + } + } + } else { + Surface( + onClick = { + onSend(text) + text = "" + }, + enabled = !state.busy || locked, + shape = CircleShape, + color = palette.accent, + contentColor = palette.accentInk, + modifier = Modifier.size(52.dp), + ) { + Box(contentAlignment = Alignment.Center) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) + } + } + } + } + } + if (state.heard.isNotBlank()) { + Text(state.heard, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, modifier = Modifier.padding(start = 16.dp, top = 6.dp)) + } + } + } +} + +/** The model and the connection: its picture, its name, the instance and a dot that says whether it answers. */ +@Composable +private fun ModelChip(state: AssistUiState, actions: AssistActions) { + val palette = LocalPalette.current + var open by remember { mutableStateOf(false) } + val dot = when (state.connection) { + Connection.Online -> palette.success + Connection.Offline -> palette.danger + Connection.Checking -> palette.inkFaint + } + val where = when (state.connection) { + Connection.Online -> state.instanceName + Connection.Offline -> stringResource(R.string.assist_offline, state.instanceName) + Connection.Checking -> stringResource(R.string.assist_connecting) + } + Box { + Surface( + onClick = { if (state.models.isNotEmpty()) open = true }, + shape = RoundedCornerShape(24.dp), + color = palette.surfaceRaised, + border = BorderStroke(1.dp, palette.border), + modifier = Modifier.widthIn(max = 320.dp).heightIn(min = 48.dp), + ) { + Row(Modifier.padding(start = 6.dp, end = 4.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) { + Box { + ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 32.dp) + // The connection's dot, ringed in the chip's colour so it reads over any picture. + val ring = Modifier.align(Alignment.BottomEnd).size(10.dp).clip(CircleShape).background(palette.surfaceRaised) + Box(ring.padding(2.dp).clip(CircleShape).background(dot)) + } + Spacer(Modifier.width(10.dp)) + Column(Modifier.weight(1f, fill = false)) { + Text( + state.modelInfo?.name?.ifBlank { null } ?: state.modelId ?: stringResource(R.string.assist_no_model), + style = MaterialTheme.typography.titleSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text(where, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Icon(Icons.Filled.ArrowDropDown, contentDescription = null, tint = palette.inkMuted) + } + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + state.models.forEach { model -> + DropdownMenuItem( + leadingIcon = { ModelAvatar(model, model.id, size = 24.dp) }, + text = { Text(model.name.ifBlank { model.id }, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + trailingIcon = if (model.id == state.modelId) { + { Box(Modifier.size(8.dp).clip(CircleShape).background(palette.accent)) } + } else { + null + }, + onClick = { + open = false + actions.pickModel(model.id) + }, + ) + } + } + } +} + +/** Before anything is asked: the last chat to continue, the quick actions, and how to open this. */ +@Composable +private fun Starting(state: AssistUiState, actions: AssistActions, locked: Boolean) { + val palette = LocalPalette.current + if (!locked) { + state.last?.let { last -> + Surface( + onClick = actions::continueLast, + shape = RoundedCornerShape(20.dp), + color = palette.surfaceRaised, + border = BorderStroke(1.dp, palette.border), + modifier = Modifier.fillMaxWidth(), + ) { + Row(Modifier.padding(horizontal = 16.dp, vertical = 12.dp).heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Filled.History, contentDescription = null, tint = palette.accent) + Spacer(Modifier.width(16.dp)) + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.assist_continue), style = MaterialTheme.typography.titleSmall) + Text( + listOf(last.title, if (last.at > 0) DateUtils.getRelativeTimeSpanString(last.at).toString() else "") + .filter { it.isNotBlank() }.joinToString(" · "), + style = MaterialTheme.typography.bodyMedium, + color = palette.inkMuted, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + } + if (state.screenAvailable && !locked) { + val summarise = stringResource(R.string.assist_quick_summarise_prompt) + val translate = stringResource(R.string.assist_quick_translate_prompt) + val explain = stringResource(R.string.assist_quick_explain_prompt) + Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + QuickAction(Icons.Filled.Summarize, stringResource(R.string.assist_quick_summarise)) { actions.quick(summarise) } + QuickAction(Icons.Filled.Translate, stringResource(R.string.assist_quick_translate)) { actions.quick(translate) } + QuickAction(Icons.Filled.Lightbulb, stringResource(R.string.assist_quick_explain)) { actions.quick(explain) } + } + } + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(stringResource(R.string.assist_help), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint) + Text(stringResource(R.string.assist_no_wake_word), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint) + } +} + +@Composable +private fun QuickAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, onClick: () -> Unit) { + val palette = LocalPalette.current + AssistChip( + onClick = onClick, + label = { Text(label) }, + leadingIcon = { Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp)) }, + colors = AssistChipDefaults.assistChipColors(containerColor = palette.surfaceRaised, leadingIconContentColor = palette.accent), + border = BorderStroke(1.dp, palette.border), + modifier = Modifier.heightIn(min = 40.dp), + ) +} + +/** One question, as a bubble on the right, and its answer at full width -- as in the app's chats. */ +@Composable +private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions: AssistActions, onOpenApp: () -> Unit) { + val palette = LocalPalette.current + Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) { + Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) { + Text(turn.question, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) + } + } + if (turn.steps.isNotEmpty()) Steps(turn.steps) + val reply = turn.reply + when { + reply != null && reply.cards.isNotEmpty() -> TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_answer_in_app)) } + + turn.writing && reply?.status?.isNotBlank() == true -> Text(reply.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint) + + last && !turn.writing && turn.steps.isNotEmpty() -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (state.canSpeak) { + if (state.speaking) { + AssistChip(onClick = actions::stopReading, label = { Text(stringResource(R.string.assist_stop_reading)) }, leadingIcon = { + Icon(Icons.Filled.Stop, contentDescription = null, modifier = Modifier.size(18.dp)) + }) + } else { + AssistChip(onClick = actions::readAloud, label = { Text(stringResource(R.string.assist_read_aloud)) }, leadingIcon = { + Icon(Icons.AutoMirrored.Filled.VolumeUp, contentDescription = null, modifier = Modifier.size(18.dp)) + }) + } + } + AssistChip(onClick = actions::newChat, label = { Text(stringResource(R.string.new_chat)) }, leadingIcon = { + Icon(Icons.Filled.EditNote, contentDescription = null, modifier = Modifier.size(18.dp)) + }) + } + } + } +} + +/** Use screen: off every time the sheet opens; on, the screen goes with the next question only. */ +@Composable +private fun ScreenToggle(state: AssistUiState, actions: AssistActions) { + val palette = LocalPalette.current + Row(Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) { + FilterChip( + selected = state.includeScreen, + onClick = { actions.includeScreen(!state.includeScreen) }, + label = { Text(stringResource(R.string.assist_use_screen)) }, + leadingIcon = { Icon(Icons.Filled.ScreenshotMonitor, contentDescription = null, modifier = Modifier.size(18.dp)) }, + colors = FilterChipDefaults.filterChipColors(selectedContainerColor = palette.accentSoft, selectedLeadingIconColor = palette.accent), + modifier = Modifier.heightIn(min = 40.dp), + ) + if (state.includeScreen) { + Spacer(Modifier.width(10.dp)) + state.screenshot?.let { shot -> + Image( + shot.asImageBitmap(), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.size(width = 24.dp, height = 40.dp).clip(RoundedCornerShape(4.dp)).background(palette.bgSunken), + ) + Spacer(Modifier.width(8.dp)) + } + Text( + stringResource( + when { + state.screenText && state.screenshot != null -> R.string.assist_screen_both + state.screenText -> R.string.assist_screen_text + else -> R.string.assist_screen_shot + }, + ), + style = MaterialTheme.typography.bodySmall, + color = palette.inkMuted, + modifier = Modifier.weight(1f), + ) + } + } +} + +/** + * Listening: the microphone, grown by how loud it hears you (a tap sends what was said), the + * words so far, and the keyboard to type instead. The row's parts keep their sizes; the words + * give. + */ +@Composable +private fun Listening(state: AssistUiState, onDone: () -> Unit, onType: () -> Unit) { + val palette = LocalPalette.current + Row(Modifier.fillMaxWidth().heightIn(min = 72.dp), verticalAlignment = Alignment.CenterVertically) { + Box(Modifier.size(64.dp), contentAlignment = Alignment.Center) { + Box(Modifier.size(64.dp).scale(0.8f + 0.2f * (state.level * 3f).coerceAtMost(1f)).clip(CircleShape).background(palette.accentSoft)) + Surface(onClick = onDone, shape = CircleShape, color = palette.accent, contentColor = palette.accentInk, modifier = Modifier.size(52.dp)) { + Box(contentAlignment = Alignment.Center) { Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.assist_send_now)) } + } + } + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.listening), style = MaterialTheme.typography.labelLarge, color = palette.accent) + Text( + state.heard.ifBlank { stringResource(R.string.assist_say_it) }, + style = MaterialTheme.typography.bodyLarge, + color = if (state.heard.isBlank()) palette.inkFaint else palette.ink, + maxLines = 4, + overflow = TextOverflow.Ellipsis, + ) + } + IconButton(onClick = onType) { Icon(Icons.Filled.Keyboard, contentDescription = stringResource(R.string.assist_type), tint = palette.inkMuted) } + } +} diff --git a/app/src/main/java/eu/llembas/android/assist/Voice.kt b/app/src/main/java/eu/llembas/android/assist/Voice.kt index ab5ecbc..9abc116 100644 --- a/app/src/main/java/eu/llembas/android/assist/Voice.kt +++ b/app/src/main/java/eu/llembas/android/assist/Voice.kt @@ -1,16 +1,27 @@ package eu.llembas.android.assist import android.Manifest +import android.content.ComponentName import android.content.Context +import android.content.Intent import android.media.AudioAttributes import android.media.AudioFormat import android.media.AudioRecord import android.media.MediaPlayer import android.media.MediaRecorder +import android.os.Build +import android.os.Bundle +import android.speech.RecognitionListener +import android.speech.RecognitionService +import android.speech.RecognizerIntent +import android.speech.SpeechRecognizer import androidx.annotation.RequiresPermission import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -31,9 +42,19 @@ class Recorder(private val scope: CoroutineScope) { private var record: AudioRecord? = null private var job: Job? = null private val pcm = ByteArrayOutputStream() + private val _level = MutableStateFlow(0f) + + /** How loud the last moment was, 0..1 (RMS of the samples): the sheet's meter and its ear for silence. */ + val level: StateFlow = _level.asStateFlow() val recording: Boolean get() = record != null + /** What has been said so far, as a WAV file, without stopping: for words shown as they come. */ + fun snapshot(): ByteArray = pcm.toByteArray().let { if (it.isEmpty()) it else wav(it) } + + /** How many seconds have been recorded. */ + val seconds: Float get() = pcm.size() / (RATE * 2f) + @RequiresPermission(Manifest.permission.RECORD_AUDIO) fun start() { if (record != null) return @@ -54,6 +75,7 @@ class Recorder(private val scope: CoroutineScope) { val read = audio.read(buffer, 0, buffer.size) if (read > 0) { pcm.write(buffer, 0, read) + _level.value = rms(buffer, read) } else if (read < 0) { break } @@ -71,6 +93,7 @@ class Recorder(private val scope: CoroutineScope) { job?.cancel() job?.join() audio.release() + _level.value = 0f val body = pcm.toByteArray() pcm.reset() return if (body.isEmpty()) body else wav(body) @@ -80,6 +103,18 @@ class Recorder(private val scope: CoroutineScope) { const val RATE = 16_000 private const val MAX_BYTES = RATE * 2 * 120 // two minutes + /** The loudness of [length] bytes of 16-bit little-endian samples, 0..1. */ + fun rms(buffer: ByteArray, length: Int): Float { + val samples = length / 2 + if (samples == 0) return 0f + var sum = 0.0 + for (i in 0 until samples) { + val sample = ((buffer[i * 2 + 1].toInt() shl 8) or (buffer[i * 2].toInt() and 0xFF)).toShort() / 32768.0 + sum += sample * sample + } + return kotlin.math.sqrt(sum / samples).toFloat().coerceIn(0f, 1f) + } + fun wav(pcm: ByteArray): ByteArray { val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply { put("RIFF".toByteArray()) @@ -101,9 +136,11 @@ class Recorder(private val scope: CoroutineScope) { } } -/** Speech out: the instance's text-to-speech, played once. */ +/** Speech out: the instance's text-to-speech, played once. [playing] is true while it speaks. */ class Speaker(private val context: Context) { private var player: MediaPlayer? = null + private val _playing = MutableStateFlow(false) + val playing: StateFlow = _playing.asStateFlow() suspend fun play(mp3: ByteArray) { stop() @@ -120,10 +157,12 @@ class Speaker(private val context: Context) { it.release() file.delete() player = null + _playing.value = false } prepare() start() } + _playing.value = true } fun stop() { @@ -132,5 +171,109 @@ class Speaker(private val context: Context) { release() } player = null + _playing.value = false + } +} + +/** + * Speech in through the phone's own recogniser, for Settings › Voice input › Phone: words as + * they are said ([start]'s `onPartial`), and the end of speech found by the recogniser. + * + * While LLeMbas is the digital assistant the *system's* default recogniser is LLeMbas's own + * ([LembasRecognitionService]), so this never asks for the default: it takes the on-device + * recogniser (Android 12+), else another installed app's. No Google library is linked; a + * phone without any recogniser simply has none to offer ([available]). + */ +class PhoneRecognizer(private val context: Context) { + private var recognizer: SpeechRecognizer? = null + + fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) { + stop() + startWith(onDevice(context), onPartial, onLevel, onResult, onFail) + } + + // `onFail`, not `onError`: inside the listener below that name is the listener's own method. + private fun startWith(onDevice: Boolean, onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) { + val other = component(context) + val made = when { + onDevice && Build.VERSION.SDK_INT >= 31 -> SpeechRecognizer.createOnDeviceSpeechRecognizer(context) + other != null -> SpeechRecognizer.createSpeechRecognizer(context, other) + else -> return onFail(SpeechRecognizer.ERROR_CLIENT) + } + recognizer = made + made.setRecognitionListener( + object : RecognitionListener { + override fun onReadyForSpeech(params: Bundle?) {} + + override fun onBeginningOfSpeech() {} + + // About -2 dB in silence to 10 dB speaking: the meter's 0..1. + override fun onRmsChanged(rmsdB: Float) = onLevel(((rmsdB + 2f) / 12f).coerceIn(0f, 1f)) + + override fun onBufferReceived(buffer: ByteArray?) {} + + override fun onEndOfSpeech() = onLevel(0f) + + override fun onError(error: Int) { + // The on-device recogniser lacks this language: another app's may have it. + if (onDevice && other != null && (error == LANGUAGE_NOT_SUPPORTED || error == LANGUAGE_UNAVAILABLE)) { + stop() + startWith(false, onPartial, onLevel, onResult, onFail) + return + } + stop() + onFail(error) + } + + override fun onResults(results: Bundle?) { + val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty() + stop() + onResult(text) + } + + override fun onPartialResults(partialResults: Bundle?) { + partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull() + ?.takeIf { it.isNotBlank() }?.let(onPartial) + } + + override fun onEvent(eventType: Int, params: Bundle?) {} + }, + ) + made.startListening( + Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) + .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) + .putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true) + .putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName), + ) + } + + /** Stop listening now; what was heard comes to `onResult`. */ + fun finish() { + recognizer?.stopListening() + } + + fun stop() { + recognizer?.runCatching { + cancel() + destroy() + } + recognizer = null + } + + companion object { + // SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED and ERROR_LANGUAGE_UNAVAILABLE (API 31). + private const val LANGUAGE_NOT_SUPPORTED = 12 + private const val LANGUAGE_UNAVAILABLE = 13 + + private fun onDevice(context: Context): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context) + + /** Another app's recogniser -- never LLeMbas's own, which would send it back to the instance. */ + fun component(context: Context): ComponentName? = context.packageManager + .queryIntentServices(Intent(RecognitionService.SERVICE_INTERFACE), 0) + .map { ComponentName(it.serviceInfo.packageName, it.serviceInfo.name) } + .firstOrNull { it.packageName != context.packageName } + + /** Whether this phone has a recogniser of its own to offer. */ + fun available(context: Context): Boolean = onDevice(context) || component(context) != null } } diff --git a/app/src/main/java/eu/llembas/android/auth/Instances.kt b/app/src/main/java/eu/llembas/android/auth/Instances.kt index 0677641..365e121 100644 --- a/app/src/main/java/eu/llembas/android/auth/Instances.kt +++ b/app/src/main/java/eu/llembas/android/auth/Instances.kt @@ -70,6 +70,11 @@ private val PREFS = stringPreferencesKey("prefs") * What the person chose in Settings, for this phone. [language]: "" the account's language (the * default), "system" the phone's, or a language's code -- see [eu.llembas.android.AppLanguage]. * [accountLanguage] is the account's language as the instance in use last said it. + * + * The assistant's: [voiceInput] `lembas` (the instance's speech-to-text) or `phone` (the phone's + * recogniser); [assistantListens] whether it opens listening; [assistantModel] the model it + * starts chats on ("" the account's default); and the last chat it made, which its sheet + * offers to continue ([lastAssistChat], its first question, when). */ @Serializable data class Prefs( @@ -78,7 +83,18 @@ data class Prefs( val readAloudSpoken: Boolean = true, val language: String = "", val accountLanguage: String = "", -) + val voiceInput: String = VOICE_LEMBAS, + val assistantListens: Boolean = true, + val assistantModel: String = "", + val lastAssistChat: String = "", + val lastAssistTitle: String = "", + val lastAssistAt: Long = 0, +) { + companion object { + const val VOICE_LEMBAS = "lembas" + const val VOICE_PHONE = "phone" + } +} class InstanceStore(private val context: Context) { private val listSerializer = ListSerializer(Instance.serializer()) diff --git a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt index bd17068..328f178 100644 --- a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt @@ -27,10 +27,13 @@ import androidx.compose.material.icons.automirrored.filled.Logout import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Assistant import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.Dns import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.Mic import androidx.compose.material.icons.filled.Notifications import androidx.compose.material.icons.filled.NotificationsActive import androidx.compose.material.icons.filled.Palette +import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.RecordVoiceOver import androidx.compose.material.icons.filled.SystemUpdate import androidx.compose.material.icons.filled.Timer @@ -68,6 +71,7 @@ import androidx.compose.ui.unit.dp import eu.llembas.android.AppLanguage import eu.llembas.android.BuildConfig import eu.llembas.android.R +import eu.llembas.android.assist.PhoneRecognizer import eu.llembas.android.auth.Instance import eu.llembas.android.auth.Prefs import eu.llembas.android.lembas @@ -87,6 +91,8 @@ interface SettingsActions { fun notificationSettings() {} fun assistantSettings() {} fun assistantTemporary(on: Boolean) {} + fun voiceInput(value: String) {} + fun assistantListens(on: Boolean) {} fun readAloud(on: Boolean) {} fun checkUpdate() {} } @@ -101,6 +107,8 @@ data class SettingsState( val updateNote: String? = null, val version: String = "", val selfUpdate: Boolean = false, + /** Whether the phone has a speech recogniser of its own (Settings › Voice input › Phone). */ + val phoneRecognizer: Boolean = false, ) @Composable @@ -161,6 +169,14 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) { scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } } } + override fun voiceInput(value: String) { + scope.launch { store.savePrefs { it.copy(voiceInput = value) } } + } + + override fun assistantListens(on: Boolean) { + scope.launch { store.savePrefs { it.copy(assistantListens = on) } } + } + override fun readAloud(on: Boolean) { scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } } } @@ -180,6 +196,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) { updateNote = updateNote, version = BuildConfig.VERSION_NAME, selfUpdate = BuildConfig.SELF_UPDATE, + phoneRecognizer = remember { PhoneRecognizer.available(context) }, ), actions, onBack, @@ -325,6 +342,13 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () - trailing = { Switch(checked = state.prefs.assistantTemporary, onCheckedChange = actions::assistantTemporary) }, ) Rule() + SettingRow( + Icons.Filled.Mic, + stringResource(R.string.assistant_listens), + onClick = { actions.assistantListens(!state.prefs.assistantListens) }, + trailing = { Switch(checked = state.prefs.assistantListens, onCheckedChange = actions::assistantListens) }, + ) + Rule() SettingRow( Icons.Filled.RecordVoiceOver, stringResource(R.string.assistant_read_aloud), @@ -333,7 +357,43 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () - ) } Text( - stringResource(R.string.assistant_samsung), + stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word), + style = MaterialTheme.typography.bodySmall, + color = palette.inkFaint, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + item { + // Which recogniser turns speech into words: the instance's or the phone's -- what + // each one is, and where the recording goes, said in the row itself. + Group(stringResource(R.string.voice_input)) { + SettingRow( + Icons.Filled.Dns, + stringResource(R.string.voice_input_lembas), + subtitle = stringResource(R.string.voice_input_lembas_line), + onClick = { actions.voiceInput(Prefs.VOICE_LEMBAS) }, + trailing = { + RadioButton(selected = state.prefs.voiceInput != Prefs.VOICE_PHONE, onClick = { actions.voiceInput(Prefs.VOICE_LEMBAS) }) + }, + ) + Rule() + SettingRow( + Icons.Filled.PhoneAndroid, + stringResource(R.string.voice_input_phone), + subtitle = stringResource(if (state.phoneRecognizer) R.string.voice_input_phone_line else R.string.voice_input_phone_none), + enabled = state.phoneRecognizer, + onClick = { actions.voiceInput(Prefs.VOICE_PHONE) }, + trailing = { + RadioButton( + selected = state.prefs.voiceInput == Prefs.VOICE_PHONE, + enabled = state.phoneRecognizer, + onClick = { actions.voiceInput(Prefs.VOICE_PHONE) }, + ) + }, + ) + } + Text( + stringResource(R.string.voice_input_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 1b296aa..9656729 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -276,10 +276,43 @@ Stažený soubor neodpovídal verzi a byl zahozen. Instaluje se %1$s… Zeptejte se na cokoli - Zahrnout obrazovku Nejprve se v aplikaci přihlaste k instanci LLeMbas. Otevřít aplikaci Pokračovat v aplikaci + Použít obrazovku + S vaší další otázkou půjde text obrazovky a snímek obrazovky. + S vaší další otázkou půjde text obrazovky. + S vaší další otázkou půjde snímek obrazovky. + Shrnout + Shrň, co je na mé obrazovce. + Přeložit + Přelož, co je na mé obrazovce, do češtiny. + Vysvětlit + Vysvětli, co je na mé obrazovce. + Pokračovat v poslední konverzaci + Podržením tlačítka napájení otevřete asistenta nad libovolnou aplikací; nebo použijte dlaždici v Rychlém nastavení. + Budicí slovo není: na běžném Androidu je naslouchání budicímu slovu vyhrazeno asistentovi zabudovanému v telefonu. + Připojování… + %1$s není dostupná + Žádný model + Hlasová odpověď je zapnutá + Hlasová odpověď je vypnutá + Přečíst nahlas + Přestat číst + Tato odpověď čeká na vaše rozhodnutí: otevřete ji v aplikaci. + Odeslat, co jsem řekl + Řekněte to a odmlčte se + Raději psát + Zapisuji, co jste řekli… + Rozpoznávání řeči v telefonu se zastavilo. Zkuste to znovu nebo zvolte LLeMbas v Nastavení › Hlasový vstup. + Začít poslouchat, když se asistent otevře + Hlasový vstup + LLeMbas + Převod řeči na text vaší instance, přes server. Nahrávka jde na vaši instanci a nikam jinam. + Telefon (Google nebo systémový) + Vlastní rozpoznávání řeči v telefonu. Slova se objevují, jak mluvíte; nahrávka jde tam, kam ji to rozpoznávání pošle. + Tento telefon nemá vlastní rozpoznávání řeči. + Používá ho asistent. S LLeMbas se slova objevují s malým zpožděním a pauza je odešle; s rozpoznáváním v telefonu se objevují, jak mluvíte. Odesílá se do LLeMbas… Podívejte se na tohle. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 8daba94..cdc5ba0 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -276,10 +276,43 @@ Der Download stimmte nicht mit der Version überein und wurde verworfen. %1$s wird installiert… Fragen Sie irgendetwas - Bildschirm einbeziehen Melden Sie sich zuerst in der App bei einer LLeMbas-Instanz an. App öffnen In der App fortsetzen + Bildschirm verwenden + Der Text des Bildschirms und ein Screenshot gehen mit Ihrer nächsten Frage mit. + Der Text des Bildschirms geht mit Ihrer nächsten Frage mit. + Ein Screenshot geht mit Ihrer nächsten Frage mit. + Zusammenfassen + Fasse zusammen, was auf meinem Bildschirm ist. + Übersetzen + Übersetze, was auf meinem Bildschirm ist, ins Deutsche. + Erklären + Erkläre, was auf meinem Bildschirm ist. + Letzten Chat fortsetzen + Halten Sie die Ein-/Aus-Taste, um den Assistenten über jeder App zu öffnen, oder nutzen Sie die Kachel in den Schnelleinstellungen. + Es gibt kein Aktivierungswort: Auf normalem Android ist das Lauschen darauf dem im Telefon eingebauten Assistenten vorbehalten. + Verbinden… + %1$s ist nicht erreichbar + Kein Modell + Sprachantwort ist an + Sprachantwort ist aus + Vorlesen + Vorlesen beenden + Diese Antwort wartet auf Ihre Entscheidung: öffnen Sie sie in der App. + Gesagtes senden + Sprechen Sie, dann kurz Pause + Lieber tippen + Ihr Gesagtes wird aufgeschrieben… + Die Spracherkennung des Telefons hat angehalten. Versuchen Sie es erneut oder wählen Sie LLeMbas unter Einstellungen › Spracheingabe. + Beim Öffnen des Assistenten zuhören + Spracheingabe + LLeMbas + Die Spracherkennung Ihrer Instanz, über den Server. Die Aufnahme geht an Ihre Instanz und nirgendwo sonst hin. + Telefon (Google oder das System) + Die eigene Spracherkennung des Telefons. Die Wörter erscheinen beim Sprechen; die Aufnahme geht dorthin, wohin diese Erkennung sie schickt. + Dieses Telefon hat keine eigene Spracherkennung. + Wird vom Assistenten genutzt. Mit LLeMbas erscheinen die Wörter einen Moment später, und eine Pause sendet sie; mit der Erkennung des Telefons erscheinen sie beim Sprechen. Wird an LLeMbas gesendet… Schauen Sie sich das an. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 6b91ca7..613d0ff 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -276,10 +276,43 @@ La descarga no coincidía con la versión y se descartó. Instalando %1$s… Pregunte lo que quiera - Incluir pantalla Primero inicie sesión en una instancia de LLeMbas en la aplicación. Abrir la aplicación Continuar en la aplicación + Usar la pantalla + El texto de la pantalla y una captura irán con su próxima pregunta. + El texto de la pantalla irá con su próxima pregunta. + Una captura de pantalla irá con su próxima pregunta. + Resumir + Resume lo que hay en mi pantalla. + Traducir + Traduce al español lo que hay en mi pantalla. + Explicar + Explica lo que hay en mi pantalla. + Continuar el último chat + Mantenga pulsado el botón de encendido para abrir el asistente sobre cualquier app, o use el mosaico de Ajustes rápidos. + No hay palabra de activación: en Android estándar, escucharla está reservado al asistente integrado en el teléfono. + Conectando… + No se puede contactar con %1$s + Sin modelo + Respuesta por voz activada + Respuesta por voz desactivada + Leer en voz alta + Dejar de leer + Esta respuesta espera su decisión: ábrala en la app. + Enviar lo que he dicho + Dígalo y haga una pausa + Escribir en su lugar + Escribiendo lo que ha dicho… + El reconocimiento de voz del teléfono se detuvo. Inténtelo de nuevo o elija LLeMbas en Ajustes › Entrada de voz. + Empezar a escuchar al abrir el asistente + Entrada de voz + LLeMbas + La conversión de voz a texto de su instancia, a través del servidor. La grabación va a su instancia y a ningún otro sitio. + Teléfono (Google o el del sistema) + El reconocimiento de voz del propio teléfono. Las palabras aparecen mientras habla; la grabación va adonde ese reconocimiento la envíe. + Este teléfono no tiene reconocimiento de voz propio. + La usa el asistente. Con LLeMbas las palabras aparecen un momento después y una pausa las envía; con el reconocimiento del teléfono aparecen mientras habla. Enviando a LLeMbas… Échele un vistazo a esto. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index d5ad4ef..1bc642a 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -276,10 +276,43 @@ Le téléchargement ne correspondait pas à la version et a été rejeté. Installation de %1$s… Demandez n\'importe quoi - Inclure l\'écran Connectez-vous d\'abord à une instance LLeMbas dans l\'application. Ouvrir l\'application Continuer dans l\'application + Utiliser l’écran + Le texte de l’écran et une capture accompagneront votre prochaine question. + Le texte de l’écran accompagnera votre prochaine question. + Une capture d’écran accompagnera votre prochaine question. + Résumer + Résume ce qui est sur mon écran. + Traduire + Traduis en français ce qui est sur mon écran. + Expliquer + Explique ce qui est sur mon écran. + Reprendre la dernière conversation + Maintenez le bouton marche/arrêt pour ouvrir l’assistant par-dessus n’importe quelle app, ou utilisez la tuile des Réglages rapides. + Pas de mot d’activation : sur Android standard, l’écoute d’un tel mot est réservée à l’assistant intégré au téléphone. + Connexion… + %1$s est injoignable + Aucun modèle + Réponse vocale activée + Réponse vocale désactivée + Lire à voix haute + Arrêter la lecture + Cette réponse attend votre décision : ouvrez-la dans l’app. + Envoyer ce que j’ai dit + Dites-le, puis marquez une pause + Taper plutôt + Transcription de ce que vous avez dit… + La reconnaissance vocale du téléphone s’est arrêtée. Réessayez, ou choisissez LLeMbas dans Réglages › Saisie vocale. + Écouter dès l’ouverture de l’assistant + Saisie vocale + LLeMbas + La transcription de votre instance, via le serveur. L’enregistrement va à votre instance et nulle part ailleurs. + Téléphone (Google ou celui du système) + La reconnaissance vocale du téléphone. Les mots apparaissent pendant que vous parlez ; l’enregistrement va là où cette reconnaissance l’envoie. + Ce téléphone n’a pas de reconnaissance vocale propre. + Utilisée par l’assistant. Avec LLeMbas, les mots apparaissent avec un léger décalage et une pause les envoie ; avec la reconnaissance du téléphone, ils apparaissent pendant que vous parlez. Envoi à LLeMbas… Jetez un œil à ceci. diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index d140efb..dd9094f 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -276,10 +276,43 @@ A letöltés nem egyezett a verzióval, és el lett dobva. %1$s telepítése… Kérdezzen bármit - Képernyő hozzáadása Először jelentkezzen be egy LLeMbas példányba az alkalmazásban. Alkalmazás megnyitása Folytatás az alkalmazásban + Képernyő használata + A képernyő szövege és egy képernyőkép a következő kérdésével megy. + A képernyő szövege a következő kérdésével megy. + Egy képernyőkép a következő kérdésével megy. + Összefoglalás + Foglald össze, mi van a képernyőmön. + Fordítás + Fordítsd le magyarra, ami a képernyőmön van. + Magyarázat + Magyarázd el, mi van a képernyőmön. + Az utolsó csevegés folytatása + Tartsa lenyomva a bekapcsológombot, hogy bármely alkalmazás fölött megnyissa az asszisztenst, vagy használja a Gyorsbeállítások csempét. + Ébresztőszó nincs: a gyári Androidon az ébresztőszó figyelése a telefonba épített asszisztensé. + Csatlakozás… + %1$s nem érhető el + Nincs modell + A hangos válasz be van kapcsolva + A hangos válasz ki van kapcsolva + Felolvasás + Felolvasás leállítása + Ez a válasz az Ön döntésére vár: nyissa meg az alkalmazásban. + Amit mondtam, küldés + Mondja, aztán tartson szünetet + Inkább gépelés + Lejegyzem, amit mondott… + A telefon beszédfelismerője leállt. Próbálja újra, vagy válassza a LLeMbast a Beállítások › Hangbevitel alatt. + Hallgatás indítása az asszisztens megnyitásakor + Hangbevitel + LLeMbas + A példánya beszédfelismerése, a szerveren át. A felvétel a példányához megy, máshová nem. + Telefon (Google vagy a rendszeré) + A telefon saját beszédfelismerője. A szavak beszéd közben jelennek meg; a felvétel oda megy, ahová az a felismerő küldi. + Ennek a telefonnak nincs saját beszédfelismerője. + Az asszisztens használja. LLeMbasszal a szavak kis késéssel jelennek meg, és egy szünet elküldi őket; a telefon felismerőjével beszéd közben jelennek meg. Küldés az LLeMbas-nak… Nézze meg ezt. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index c490c1e..3c0b56a 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -276,10 +276,43 @@ Il download non corrispondeva alla versione ed è stato scartato. Installazione di %1$s… Chiedi qualsiasi cosa - Includi lo schermo Accedi prima a un\'istanza LLeMbas nell\'app. Apri l\'app Continua nell\'app + Usa lo schermo + Il testo dello schermo e uno screenshot accompagnano la sua prossima domanda. + Il testo dello schermo accompagna la sua prossima domanda. + Uno screenshot accompagna la sua prossima domanda. + Riassumi + Riassumi cosa c’è sul mio schermo. + Traduci + Traduci in italiano cosa c’è sul mio schermo. + Spiega + Spiega cosa c’è sul mio schermo. + Continua l’ultima chat + Tenga premuto il tasto di accensione per aprire l’assistente sopra qualsiasi app, oppure usi il riquadro delle Impostazioni rapide. + Non c’è una parola di attivazione: su Android standard, l’ascolto di una tale parola è riservato all’assistente integrato nel telefono. + Connessione… + %1$s non è raggiungibile + Nessun modello + Risposta vocale attiva + Risposta vocale disattivata + Leggi ad alta voce + Interrompi la lettura + Questa risposta attende una sua decisione: la apra nell’app. + Invia ciò che ho detto + Lo dica, poi faccia una pausa + Scrivi invece + Trascrivo ciò che ha detto… + Il riconoscimento vocale del telefono si è fermato. Riprovi, oppure scelga LLeMbas in Impostazioni › Input vocale. + Inizia ad ascoltare all’apertura dell’assistente + Input vocale + LLeMbas + La trascrizione della sua istanza, tramite il server. La registrazione va alla sua istanza e da nessun’altra parte. + Telefono (Google o quello di sistema) + Il riconoscimento vocale del telefono. Le parole appaiono mentre parla; la registrazione va dove la manda quel riconoscimento. + Questo telefono non ha un riconoscimento vocale proprio. + La usa l’assistente. Con LLeMbas le parole appaiono con un attimo di ritardo e una pausa le invia; con il riconoscimento del telefono appaiono mentre parla. Invio a LLeMbas… Dai un\'occhiata a questo. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a330ace..4ac9f93 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -276,10 +276,43 @@ Pobrany plik nie zgadzał się z wersją i został odrzucony. Instalowanie %1$s… Zapytaj o cokolwiek - Dołącz ekran Najpierw zaloguj się do instancji LLeMbas w aplikacji. Otwórz aplikację Kontynuuj w aplikacji + Użyj ekranu + Tekst z ekranu i zrzut ekranu zostaną wysłane z następnym pytaniem. + Tekst z ekranu zostanie wysłany z następnym pytaniem. + Zrzut ekranu zostanie wysłany z następnym pytaniem. + Podsumuj + Podsumuj, co jest na moim ekranie. + Przetłumacz + Przetłumacz na polski to, co jest na moim ekranie. + Wyjaśnij + Wyjaśnij, co jest na moim ekranie. + Kontynuuj ostatni czat + Przytrzymaj przycisk zasilania, aby otworzyć asystenta nad dowolną aplikacją, albo użyj kafelka w Szybkich ustawieniach. + Nie ma słowa wybudzającego: w zwykłym Androidzie nasłuchiwanie go jest zarezerwowane dla asystenta wbudowanego w telefon. + Łączenie… + %1$s jest nieosiągalna + Brak modelu + Odpowiedź głosowa włączona + Odpowiedź głosowa wyłączona + Przeczytaj na głos + Przestań czytać + Ta odpowiedź czeka na Twoją decyzję: otwórz ją w aplikacji. + Wyślij, co powiedziałem + Powiedz to i zrób pauzę + Zamiast tego pisz + Zapisuję, co powiedziałeś… + Rozpoznawanie mowy w telefonie przestało działać. Spróbuj ponownie albo wybierz LLeMbas w Ustawienia › Wprowadzanie głosowe. + Zacznij słuchać po otwarciu asystenta + Wprowadzanie głosowe + LLeMbas + Zamiana mowy na tekst Twojej instancji, przez serwer. Nagranie trafia do Twojej instancji i nigdzie indziej. + Telefon (Google lub systemowy) + Własne rozpoznawanie mowy telefonu. Słowa pojawiają się w trakcie mówienia; nagranie trafia tam, dokąd wyśle je to rozpoznawanie. + Ten telefon nie ma własnego rozpoznawania mowy. + Używa go asystent. Z LLeMbas słowa pojawiają się z lekkim opóźnieniem, a pauza je wysyła; z rozpoznawaniem telefonu pojawiają się w trakcie mówienia. Wysyłanie do LLeMbas… Zobacz to. diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 94af294..5a4e2da 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -276,10 +276,43 @@ Stiahnutý súbor nezodpovedal verzii a bol zahodený. Inštaluje sa %1$s… Spýtajte sa na čokoľvek - Zahrnúť obrazovku Najprv sa v aplikácii prihláste do inštancie LLeMbas. Otvoriť aplikáciu Pokračovať v aplikácii + Použiť obrazovku + S vašou ďalšou otázkou pôjde text obrazovky a snímka obrazovky. + S vašou ďalšou otázkou pôjde text obrazovky. + S vašou ďalšou otázkou pôjde snímka obrazovky. + Zhrnúť + Zhrň, čo je na mojej obrazovke. + Preložiť + Prelož do slovenčiny, čo je na mojej obrazovke. + Vysvetliť + Vysvetli, čo je na mojej obrazovke. + Pokračovať v poslednej konverzácii + Podržaním tlačidla napájania otvoríte asistenta nad ľubovoľnou aplikáciou; alebo použite dlaždicu v Rýchlych nastaveniach. + Budiace slovo nie je: na bežnom Androide je počúvanie budiaceho slova vyhradené asistentovi zabudovanému v telefóne. + Pripája sa… + %1$s je nedostupná + Žiadny model + Hlasová odpoveď je zapnutá + Hlasová odpoveď je vypnutá + Prečítať nahlas + Prestať čítať + Táto odpoveď čaká na vaše rozhodnutie: otvorte ju v aplikácii. + Odoslať, čo som povedal + Povedzte to a odmlčte sa + Radšej písať + Zapisujem, čo ste povedali… + Rozpoznávanie reči v telefóne sa zastavilo. Skúste to znova alebo zvoľte LLeMbas v Nastaveniach › Hlasový vstup. + Začať počúvať, keď sa asistent otvorí + Hlasový vstup + LLeMbas + Prevod reči na text vašej inštancie, cez server. Nahrávka ide na vašu inštanciu a nikam inam. + Telefón (Google alebo systémový) + Vlastné rozpoznávanie reči v telefóne. Slová sa objavujú, ako hovoríte; nahrávka ide tam, kam ju to rozpoznávanie pošle. + Tento telefón nemá vlastné rozpoznávanie reči. + Používa ho asistent. S LLeMbas sa slová objavujú s malým oneskorením a pauza ich odošle; s rozpoznávaním v telefóne sa objavujú, ako hovoríte. Odosiela sa do LLeMbas… Pozrite sa na toto. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 290eaf1..413f9eb 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -277,10 +277,43 @@ The download did not match the release and was discarded. Installing %1$s… Ask anything - Include screen Sign in to a LLeMbas instance in the app first. Open the app Continue in the app + Use screen + The screen\'s text and a screenshot go with your next question. + The screen\'s text goes with your next question. + A screenshot goes with your next question. + Summarise this + Summarise what is on my screen. + Translate this + Translate what is on my screen into English. + Explain this + Explain what is on my screen. + Continue the last chat + Hold the power button to open the assistant over any app, or use the Quick Settings tile. + There is no wake word: on stock Android, listening for one is kept for the assistant built into the phone. + Connecting… + %1$s cannot be reached + No model + Voice reply is on + Voice reply is off + Read aloud + Stop reading + This reply is waiting for your answer: open it in the app. + Send what I said + Say it, then pause + Type instead + Writing down what you said… + The phone\'s speech recogniser stopped. Try again, or choose LLeMbas under Settings › Voice input. + Start listening when the assistant opens + Voice input + LLeMbas + Your instance\'s speech-to-text, through the server. The recording goes to your instance and nowhere else. + Phone (Google or the system\'s) + The phone\'s own recogniser. The words appear as you speak; the recording goes wherever that recogniser sends it. + This phone has no speech recogniser of its own. + Used by the assistant. With LLeMbas the words appear a moment behind you, and a pause sends them; with the phone\'s recogniser they appear as you speak. Sending to LLeMbas… Have a look at this. diff --git a/app/src/test/java/eu/llembas/android/AssistTest.kt b/app/src/test/java/eu/llembas/android/AssistTest.kt new file mode 100644 index 0000000..296ae2b --- /dev/null +++ b/app/src/test/java/eu/llembas/android/AssistTest.kt @@ -0,0 +1,76 @@ +package eu.llembas.android + +import eu.llembas.android.api.LiveReply +import eu.llembas.android.api.Step +import eu.llembas.android.api.Tail +import eu.llembas.android.assist.AssistController +import eu.llembas.android.assist.AssistTurn +import eu.llembas.android.assist.Recorder +import eu.llembas.android.assist.SheetStop +import eu.llembas.android.assist.settle +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class AssistTest { + private val half = 1000f + private val full = 1800f + + @Test + fun aSlowReleaseGoesToTheNearestStop() { + assertEquals(SheetStop.Half, settle(1100f, half, full, 0f)) + assertEquals(SheetStop.Full, settle(1500f, half, full, 0f)) + assertEquals(SheetStop.Half, settle(800f, half, full, 0f)) + // Pulled well below the half: it goes. + assertEquals(SheetStop.Gone, settle(500f, half, full, 0f)) + } + + @Test + fun aFlingDecidesByItsDirection() { + assertEquals(SheetStop.Full, settle(1010f, half, full, -3000f)) + // Down from the full height: to the half, not away. + assertEquals(SheetStop.Half, settle(1700f, half, full, 3000f)) + // Down from the half: away. + assertEquals(SheetStop.Gone, settle(990f, half, full, 3000f)) + } + + @Test + fun aTurnShowsWhatIsWrittenThenWhatWasWritten() { + val asked = AssistTurn("Why?") + assertFalse(asked.writing) + val writing = asked.copy(reply = LiveReply("m1", tail = Tail(text = "Because"))) + assertTrue(writing.writing) + assertEquals("Because", writing.steps.single().markdown) + val earlier = AssistTurn("Why?", earlier = listOf(Step(kind = "text", markdown = "Because."))) + assertFalse(earlier.writing) + assertEquals("Because.", earlier.steps.single().markdown) + } + + @Test + fun aVoiceReadsOnlyTheWords() { + val steps = listOf( + Step(kind = "thinking", text = "Hmm."), + Step(kind = "text", markdown = "**Two** days."), + Step(kind = "tools"), + Step(kind = "text", markdown = "See [this](https://example.org)."), + ) + assertEquals("Two days. See this.", AssistController.spokenWords(steps)) + } + + @Test + fun silenceIsQuietAndAToneIsLoud() { + assertEquals(0f, Recorder.rms(ByteArray(3200), 3200), 0f) + // A full-scale square wave: every sample at +-32767. + val loud = ByteArray(3200) { i -> + if (i % 2 == 0) { + 0xFF.toByte() + } else if ((i / 2) % 2 == 0) { + 0x7F + } else { + 0x80.toByte() + } + } + assertTrue(Recorder.rms(loud, loud.size) > 0.9f) + } +} diff --git a/app/src/test/java/eu/llembas/android/shots/Fakes.kt b/app/src/test/java/eu/llembas/android/shots/Fakes.kt index 9118be1..43f4cfc 100644 --- a/app/src/test/java/eu/llembas/android/shots/Fakes.kt +++ b/app/src/test/java/eu/llembas/android/shots/Fakes.kt @@ -28,6 +28,10 @@ import eu.llembas.android.api.SubagentsOffer import eu.llembas.android.api.Tail import eu.llembas.android.api.ToolBlock import eu.llembas.android.api.ToolCall +import eu.llembas.android.assist.AssistTurn +import eu.llembas.android.assist.AssistUiState +import eu.llembas.android.assist.Connection +import eu.llembas.android.assist.LastAssist import eu.llembas.android.auth.Instance import eu.llembas.android.auth.Prefs import eu.llembas.android.ui.chat.ChatState @@ -220,6 +224,56 @@ object Fakes { hasDistributor = true, version = "1.0.0-beta.3", selfUpdate = true, + phoneRecognizer = true, + ) + + // The assistant's sheet, as it opens and as it answers. + private val assistBase = AssistUiState( + instanceName = "Home", + connection = Connection.Online, + models = models, + modelId = models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id, + canSpeak = true, + ) + + /** Just opened over an app that handed over its screen: listening, the words coming in. */ + val assistListening = assistBase.copy( + listening = true, + heard = "How long does waybread keep if it is wrapped in", + level = 0.4f, + screenText = true, + last = LastAssist("c1", "Packing for the road", 0), + ) + + /** Opened from the tile, nothing asked yet: the last chat, the help, the microphone. */ + val assistOpened = assistBase.copy(last = LastAssist("c1", "Packing for the road", 0), screenText = true, includeScreen = true) + + /** A spoken question answered, the answer read aloud. */ + val assistAnswered = assistBase.copy( + chatId = "c9", + turns = listOf(AssistTurn(question.text.orEmpty(), earlier = answer.steps)), + speaking = true, + ) + + /** An answer being written. */ + val assistWriting = assistBase.copy( + chatId = "c9", + busy = true, + turns = listOf( + AssistTurn( + "What is on my screen?", + reply = LiveReply("m9", tail = Tail(text = "It is a recipe for waybread: flour, honey and a leaf to wrap it in. The"), status = "Writing…"), + ), + ), + ) + + /** The instance cannot be reached. */ + val assistOffline = assistBase.copy( + connection = Connection.Offline, + models = emptyList(), + modelId = null, + canSpeak = false, + error = "Home cannot be reached.", ) // Scheduled: shaped as the server's contract fixtures are (contract/schedule*.json). diff --git a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt index 889fc0f..ac4f781 100644 --- a/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt +++ b/app/src/test/java/eu/llembas/android/shots/ScreenShots.kt @@ -16,6 +16,10 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import eu.llembas.android.assist.AssistActions +import eu.llembas.android.assist.AssistSheetContent +import eu.llembas.android.assist.AssistSheetFrame +import eu.llembas.android.assist.AssistUiState import eu.llembas.android.ui.chat.ActivityActions import eu.llembas.android.ui.chat.ActivityContent import eu.llembas.android.ui.chat.ChatActions @@ -49,6 +53,8 @@ private object NoActivityActions : ActivityActions private object NoSettingsActions : SettingsActions +private object NoAssistActions : AssistActions + /** * The app's screens with made-up data ([Fakes]), as a phone shows them: each in Shire and * Moria, at a large phone's size and, where things crowd, a small one's and with large type. @@ -124,6 +130,8 @@ class ScreenShots { fun settings() { shoot("08-settings") { SettingsContent(Fakes.settings, NoSettingsActions) } shoot("08-settings", Phone.Small) { SettingsContent(Fakes.settings, NoSettingsActions) } + // The whole page: Language, the assistant's switches and Voice input. + shoot("08-settings", Phone.Scroll) { SettingsContent(Fakes.settings, NoSettingsActions) } } @Test @@ -166,6 +174,30 @@ class ScreenShots { } } + /** + * The assistant's sheet over an app (a chat stands in for whatever was on screen): at half + * height as it opens, at a small phone's size and with large type too. + */ + @Test + fun assistant() { + val over: (AssistUiState, Boolean) -> @Composable () -> Unit = { state, locked -> + { + Box(Modifier.fillMaxSize()) { + ChatContent(Fakes.transcript, NoChatActions, agent = false) + AssistSheetFrame(onDismiss = {}) { handle, _ -> AssistSheetContent(state, NoAssistActions, locked, handle) } + } + } + } + shoot("18-assistant-listening", content = over(Fakes.assistListening, false)) + shoot("18-assistant-listening", Phone.Small, fontScale = 1.5f, content = over(Fakes.assistListening, false)) + shoot("19-assistant-opened", content = over(Fakes.assistOpened, false)) + shoot("19-assistant-opened", Phone.Small, content = over(Fakes.assistOpened, false)) + shoot("20-assistant-answered", content = over(Fakes.assistAnswered, false)) + shoot("21-assistant-writing", content = over(Fakes.assistWriting, false)) + shoot("22-assistant-locked", content = over(Fakes.assistOpened, true)) + shoot("23-assistant-offline", Phone.Small, content = over(Fakes.assistOffline, false)) + } + @Test fun schedulingModels() = shoot("13-scheduling-models") { SchedulingModelsContent(Fakes.schedulingModels) } } diff --git a/scripts/strings.py b/scripts/strings.py index 24f2549..4a9f1ae 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -299,10 +299,43 @@ STRINGS: dict[str, str] = { "update_installing": "Installing %1$s…", # Assistant "assist_hint": "Ask anything", - "assist_include_screen": "Include screen", "assist_signed_out": "Sign in to a LLeMbas instance in the app first.", "assist_open_app": "Open the app", "assist_open_in_app": "Continue in the app", + "assist_use_screen": "Use screen", + "assist_screen_both": "The screen's text and a screenshot go with your next question.", + "assist_screen_text": "The screen's text goes with your next question.", + "assist_screen_shot": "A screenshot goes with your next question.", + "assist_quick_summarise": "Summarise this", + "assist_quick_summarise_prompt": "Summarise what is on my screen.", + "assist_quick_translate": "Translate this", + "assist_quick_translate_prompt": "Translate what is on my screen into English.", + "assist_quick_explain": "Explain this", + "assist_quick_explain_prompt": "Explain what is on my screen.", + "assist_continue": "Continue the last chat", + "assist_help": "Hold the power button to open the assistant over any app, or use the Quick Settings tile.", + "assist_no_wake_word": "There is no wake word: on stock Android, listening for one is kept for the assistant built into the phone.", + "assist_connecting": "Connecting…", + "assist_offline": "%1$s cannot be reached", + "assist_no_model": "No model", + "assist_voice_reply_on": "Voice reply is on", + "assist_voice_reply_off": "Voice reply is off", + "assist_read_aloud": "Read aloud", + "assist_stop_reading": "Stop reading", + "assist_answer_in_app": "This reply is waiting for your answer: open it in the app.", + "assist_send_now": "Send what I said", + "assist_say_it": "Say it, then pause", + "assist_type": "Type instead", + "assist_writing_down": "Writing down what you said…", + "assist_recogniser_failed": "The phone's speech recogniser stopped. Try again, or choose LLeMbas under Settings › Voice input.", + "assistant_listens": "Start listening when the assistant opens", + "voice_input": "Voice input", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "Your instance's speech-to-text, through the server. The recording goes to your instance and nowhere else.", + "voice_input_phone": "Phone (Google or the system's)", + "voice_input_phone_line": "The phone's own recogniser. The words appear as you speak; the recording goes wherever that recogniser sends it.", + "voice_input_phone_none": "This phone has no speech recogniser of its own.", + "voice_input_hint": "Used by the assistant. With LLeMbas the words appear a moment behind you, and a pause sends them; with the phone's recogniser they appear as you speak.", # Share "share_sending": "Sending to LLeMbas…", "share_default_prompt": "Have a look at this.", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index 6b6f647..fb18bdd 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -17,12 +17,38 @@ "agent_runs_on": "Běží na %1$s, ve složce %2$s", "agent_stop_confirm": "Zastavit %1$s? Co dosud udělal, zůstane.", "archive": "Archivovat", + "assist_answer_in_app": "Tato odpověď čeká na vaše rozhodnutí: otevřete ji v aplikaci.", + "assist_connecting": "Připojování…", + "assist_continue": "Pokračovat v poslední konverzaci", + "assist_help": "Podržením tlačítka napájení otevřete asistenta nad libovolnou aplikací; nebo použijte dlaždici v Rychlém nastavení.", "assist_hint": "Zeptejte se na cokoli", - "assist_include_screen": "Zahrnout obrazovku", + "assist_no_model": "Žádný model", + "assist_no_wake_word": "Budicí slovo není: na běžném Androidu je naslouchání budicímu slovu vyhrazeno asistentovi zabudovanému v telefonu.", + "assist_offline": "%1$s není dostupná", "assist_open_app": "Otevřít aplikaci", "assist_open_in_app": "Pokračovat v aplikaci", + "assist_quick_explain": "Vysvětlit", + "assist_quick_explain_prompt": "Vysvětli, co je na mé obrazovce.", + "assist_quick_summarise": "Shrnout", + "assist_quick_summarise_prompt": "Shrň, co je na mé obrazovce.", + "assist_quick_translate": "Přeložit", + "assist_quick_translate_prompt": "Přelož, co je na mé obrazovce, do češtiny.", + "assist_read_aloud": "Přečíst nahlas", + "assist_recogniser_failed": "Rozpoznávání řeči v telefonu se zastavilo. Zkuste to znovu nebo zvolte LLeMbas v Nastavení › Hlasový vstup.", + "assist_say_it": "Řekněte to a odmlčte se", + "assist_screen_both": "S vaší další otázkou půjde text obrazovky a snímek obrazovky.", + "assist_screen_shot": "S vaší další otázkou půjde snímek obrazovky.", + "assist_screen_text": "S vaší další otázkou půjde text obrazovky.", + "assist_send_now": "Odeslat, co jsem řekl", "assist_signed_out": "Nejprve se v aplikaci přihlaste k instanci LLeMbas.", + "assist_stop_reading": "Přestat číst", + "assist_type": "Raději psát", + "assist_use_screen": "Použít obrazovku", + "assist_voice_reply_off": "Hlasová odpověď je vypnutá", + "assist_voice_reply_on": "Hlasová odpověď je zapnutá", + "assist_writing_down": "Zapisuji, co jste řekli…", "assistant_explained": "Nastavte LLeMbas jako digitálního asistenta telefonu: zvolte ho v Výchozí aplikace › Digitální asistent. Podržení tlačítka napájení, gesto asistenta nebo zkratka na zamykací obrazovce ho pak otevře přes to, co je právě na obrazovce.", + "assistant_listens": "Začít poslouchat, když se asistent otevře", "assistant_open_settings": "Otevřít nastavení asistenta", "assistant_read_aloud": "Přečíst odpověď nahlas, když se zeptáte hlasem", "assistant_samsung": "Na telefonech Samsung: Nastavení › Pokročilé funkce › Boční tlačítko › Stisknutí a podržení › Digitální asistent.", @@ -174,7 +200,14 @@ "viewer_long_markdown": "Dlouhý soubor, proto je zobrazen jako prostý text.", "viewer_open_browser": "Otevřít v prohlížeči", "viewer_too_large": "Tento soubor je příliš velký na zobrazení; zobrazit lze nejvýše 1 MB.", - "viewer_unavailable": "Tento server zatím aplikaci soubor předat neumí. Otevřete ho v prohlížeči." + "viewer_unavailable": "Tento server zatím aplikaci soubor předat neumí. Otevřete ho v prohlížeči.", + "voice_input": "Hlasový vstup", + "voice_input_hint": "Používá ho asistent. S LLeMbas se slova objevují s malým zpožděním a pauza je odešle; s rozpoznáváním v telefonu se objevují, jak mluvíte.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "Převod řeči na text vaší instance, přes server. Nahrávka jde na vaši instanci a nikam jinam.", + "voice_input_phone": "Telefon (Google nebo systémový)", + "voice_input_phone_line": "Vlastní rozpoznávání řeči v telefonu. Slova se objevují, jak mluvíte; nahrávka jde tam, kam ji to rozpoznávání pošle.", + "voice_input_phone_none": "Tento telefon nemá vlastní rozpoznávání řeči." }, "de": { "about_version": "LLeMbas für Android %1$s", @@ -194,12 +227,38 @@ "agent_runs_on": "Läuft auf %1$s, in %2$s", "agent_stop_confirm": "%1$s stoppen? Was bisher getan wurde, bleibt.", "archive": "Archivieren", + "assist_answer_in_app": "Diese Antwort wartet auf Ihre Entscheidung: öffnen Sie sie in der App.", + "assist_connecting": "Verbinden…", + "assist_continue": "Letzten Chat fortsetzen", + "assist_help": "Halten Sie die Ein-/Aus-Taste, um den Assistenten über jeder App zu öffnen, oder nutzen Sie die Kachel in den Schnelleinstellungen.", "assist_hint": "Fragen Sie irgendetwas", - "assist_include_screen": "Bildschirm einbeziehen", + "assist_no_model": "Kein Modell", + "assist_no_wake_word": "Es gibt kein Aktivierungswort: Auf normalem Android ist das Lauschen darauf dem im Telefon eingebauten Assistenten vorbehalten.", + "assist_offline": "%1$s ist nicht erreichbar", "assist_open_app": "App öffnen", "assist_open_in_app": "In der App fortsetzen", + "assist_quick_explain": "Erklären", + "assist_quick_explain_prompt": "Erkläre, was auf meinem Bildschirm ist.", + "assist_quick_summarise": "Zusammenfassen", + "assist_quick_summarise_prompt": "Fasse zusammen, was auf meinem Bildschirm ist.", + "assist_quick_translate": "Übersetzen", + "assist_quick_translate_prompt": "Übersetze, was auf meinem Bildschirm ist, ins Deutsche.", + "assist_read_aloud": "Vorlesen", + "assist_recogniser_failed": "Die Spracherkennung des Telefons hat angehalten. Versuchen Sie es erneut oder wählen Sie LLeMbas unter Einstellungen › Spracheingabe.", + "assist_say_it": "Sprechen Sie, dann kurz Pause", + "assist_screen_both": "Der Text des Bildschirms und ein Screenshot gehen mit Ihrer nächsten Frage mit.", + "assist_screen_shot": "Ein Screenshot geht mit Ihrer nächsten Frage mit.", + "assist_screen_text": "Der Text des Bildschirms geht mit Ihrer nächsten Frage mit.", + "assist_send_now": "Gesagtes senden", "assist_signed_out": "Melden Sie sich zuerst in der App bei einer LLeMbas-Instanz an.", + "assist_stop_reading": "Vorlesen beenden", + "assist_type": "Lieber tippen", + "assist_use_screen": "Bildschirm verwenden", + "assist_voice_reply_off": "Sprachantwort ist aus", + "assist_voice_reply_on": "Sprachantwort ist an", + "assist_writing_down": "Ihr Gesagtes wird aufgeschrieben…", "assistant_explained": "Machen Sie LLeMbas zum digitalen Assistenten des Telefons: Wählen Sie ihn unter Standard-Apps › Digitaler Assistent. Das Halten der Einschalttaste, die Assistenzgeste oder die Verknüpfung auf dem Sperrbildschirm öffnet ihn dann über allem, was gerade angezeigt wird.", + "assistant_listens": "Beim Öffnen des Assistenten zuhören", "assistant_open_settings": "Assistenten-Einstellungen öffnen", "assistant_read_aloud": "Antwort vorlesen, wenn per Sprache gefragt wurde", "assistant_samsung": "Auf Samsung-Telefonen: Einstellungen › Erweiterte Funktionen › Seitentaste › Gedrückt halten › Digitaler Assistent.", @@ -352,7 +411,14 @@ "viewer_long_markdown": "Eine lange Datei, daher wird sie als reiner Text angezeigt.", "viewer_open_browser": "Im Browser öffnen", "viewer_too_large": "Diese Datei ist zu groß zum Anzeigen; höchstens 1 MB kann angezeigt werden.", - "viewer_unavailable": "Dieser Server kann die Datei der App noch nicht übergeben. Öffnen Sie sie stattdessen im Browser." + "viewer_unavailable": "Dieser Server kann die Datei der App noch nicht übergeben. Öffnen Sie sie stattdessen im Browser.", + "voice_input": "Spracheingabe", + "voice_input_hint": "Wird vom Assistenten genutzt. Mit LLeMbas erscheinen die Wörter einen Moment später, und eine Pause sendet sie; mit der Erkennung des Telefons erscheinen sie beim Sprechen.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "Die Spracherkennung Ihrer Instanz, über den Server. Die Aufnahme geht an Ihre Instanz und nirgendwo sonst hin.", + "voice_input_phone": "Telefon (Google oder das System)", + "voice_input_phone_line": "Die eigene Spracherkennung des Telefons. Die Wörter erscheinen beim Sprechen; die Aufnahme geht dorthin, wohin diese Erkennung sie schickt.", + "voice_input_phone_none": "Dieses Telefon hat keine eigene Spracherkennung." }, "es": { "about_version": "LLeMbas para Android %1$s", @@ -372,12 +438,38 @@ "agent_runs_on": "Se ejecuta en %1$s, en %2$s", "agent_stop_confirm": "¿Detener %1$s? Lo que ha hecho hasta ahora se queda.", "archive": "Archivar", + "assist_answer_in_app": "Esta respuesta espera su decisión: ábrala en la app.", + "assist_connecting": "Conectando…", + "assist_continue": "Continuar el último chat", + "assist_help": "Mantenga pulsado el botón de encendido para abrir el asistente sobre cualquier app, o use el mosaico de Ajustes rápidos.", "assist_hint": "Pregunte lo que quiera", - "assist_include_screen": "Incluir pantalla", + "assist_no_model": "Sin modelo", + "assist_no_wake_word": "No hay palabra de activación: en Android estándar, escucharla está reservado al asistente integrado en el teléfono.", + "assist_offline": "No se puede contactar con %1$s", "assist_open_app": "Abrir la aplicación", "assist_open_in_app": "Continuar en la aplicación", + "assist_quick_explain": "Explicar", + "assist_quick_explain_prompt": "Explica lo que hay en mi pantalla.", + "assist_quick_summarise": "Resumir", + "assist_quick_summarise_prompt": "Resume lo que hay en mi pantalla.", + "assist_quick_translate": "Traducir", + "assist_quick_translate_prompt": "Traduce al español lo que hay en mi pantalla.", + "assist_read_aloud": "Leer en voz alta", + "assist_recogniser_failed": "El reconocimiento de voz del teléfono se detuvo. Inténtelo de nuevo o elija LLeMbas en Ajustes › Entrada de voz.", + "assist_say_it": "Dígalo y haga una pausa", + "assist_screen_both": "El texto de la pantalla y una captura irán con su próxima pregunta.", + "assist_screen_shot": "Una captura de pantalla irá con su próxima pregunta.", + "assist_screen_text": "El texto de la pantalla irá con su próxima pregunta.", + "assist_send_now": "Enviar lo que he dicho", "assist_signed_out": "Primero inicie sesión en una instancia de LLeMbas en la aplicación.", + "assist_stop_reading": "Dejar de leer", + "assist_type": "Escribir en su lugar", + "assist_use_screen": "Usar la pantalla", + "assist_voice_reply_off": "Respuesta por voz desactivada", + "assist_voice_reply_on": "Respuesta por voz activada", + "assist_writing_down": "Escribiendo lo que ha dicho…", "assistant_explained": "Convierta LLeMbas en el asistente digital del teléfono: elíjalo en Aplicaciones predeterminadas › App de asistencia digital. Mantener pulsado el botón de encendido, el gesto de asistencia o el acceso directo de la pantalla de bloqueo lo abrirá entonces sobre lo que haya en pantalla.", + "assistant_listens": "Empezar a escuchar al abrir el asistente", "assistant_open_settings": "Abrir los ajustes del asistente", "assistant_read_aloud": "Leer la respuesta en voz alta cuando se pregunte por voz", "assistant_samsung": "En los teléfonos Samsung: Ajustes › Funciones avanzadas › Botón lateral › Mantener pulsado › Asistente digital.", @@ -529,7 +621,14 @@ "viewer_long_markdown": "Un archivo largo, por eso se muestra como texto sin formato.", "viewer_open_browser": "Abrir en el navegador", "viewer_too_large": "Este archivo es demasiado grande para mostrarlo; se puede mostrar como máximo 1 MB.", - "viewer_unavailable": "Este servidor todavía no puede entregar el archivo a la aplicación. Ábralo en el navegador." + "viewer_unavailable": "Este servidor todavía no puede entregar el archivo a la aplicación. Ábralo en el navegador.", + "voice_input": "Entrada de voz", + "voice_input_hint": "La usa el asistente. Con LLeMbas las palabras aparecen un momento después y una pausa las envía; con el reconocimiento del teléfono aparecen mientras habla.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "La conversión de voz a texto de su instancia, a través del servidor. La grabación va a su instancia y a ningún otro sitio.", + "voice_input_phone": "Teléfono (Google o el del sistema)", + "voice_input_phone_line": "El reconocimiento de voz del propio teléfono. Las palabras aparecen mientras habla; la grabación va adonde ese reconocimiento la envíe.", + "voice_input_phone_none": "Este teléfono no tiene reconocimiento de voz propio." }, "fr": { "about_version": "LLeMbas pour Android %1$s", @@ -549,12 +648,38 @@ "agent_runs_on": "S’exécute sur %1$s, dans %2$s", "agent_stop_confirm": "Arrêter %1$s ? Ce qu’il a déjà fait reste.", "archive": "Archiver", + "assist_answer_in_app": "Cette réponse attend votre décision : ouvrez-la dans l’app.", + "assist_connecting": "Connexion…", + "assist_continue": "Reprendre la dernière conversation", + "assist_help": "Maintenez le bouton marche/arrêt pour ouvrir l’assistant par-dessus n’importe quelle app, ou utilisez la tuile des Réglages rapides.", "assist_hint": "Demandez n'importe quoi", - "assist_include_screen": "Inclure l'écran", + "assist_no_model": "Aucun modèle", + "assist_no_wake_word": "Pas de mot d’activation : sur Android standard, l’écoute d’un tel mot est réservée à l’assistant intégré au téléphone.", + "assist_offline": "%1$s est injoignable", "assist_open_app": "Ouvrir l'application", "assist_open_in_app": "Continuer dans l'application", + "assist_quick_explain": "Expliquer", + "assist_quick_explain_prompt": "Explique ce qui est sur mon écran.", + "assist_quick_summarise": "Résumer", + "assist_quick_summarise_prompt": "Résume ce qui est sur mon écran.", + "assist_quick_translate": "Traduire", + "assist_quick_translate_prompt": "Traduis en français ce qui est sur mon écran.", + "assist_read_aloud": "Lire à voix haute", + "assist_recogniser_failed": "La reconnaissance vocale du téléphone s’est arrêtée. Réessayez, ou choisissez LLeMbas dans Réglages › Saisie vocale.", + "assist_say_it": "Dites-le, puis marquez une pause", + "assist_screen_both": "Le texte de l’écran et une capture accompagneront votre prochaine question.", + "assist_screen_shot": "Une capture d’écran accompagnera votre prochaine question.", + "assist_screen_text": "Le texte de l’écran accompagnera votre prochaine question.", + "assist_send_now": "Envoyer ce que j’ai dit", "assist_signed_out": "Connectez-vous d'abord à une instance LLeMbas dans l'application.", + "assist_stop_reading": "Arrêter la lecture", + "assist_type": "Taper plutôt", + "assist_use_screen": "Utiliser l’écran", + "assist_voice_reply_off": "Réponse vocale désactivée", + "assist_voice_reply_on": "Réponse vocale activée", + "assist_writing_down": "Transcription de ce que vous avez dit…", "assistant_explained": "Faites de LLeMbas l'assistant numérique du téléphone : choisissez-le dans Applications par défaut › Application d'assistance numérique. Maintenir le bouton d'alimentation, le geste d'assistance ou le raccourci de l'écran de verrouillage l'ouvrira alors par-dessus ce qui est affiché.", + "assistant_listens": "Écouter dès l’ouverture de l’assistant", "assistant_open_settings": "Ouvrir les paramètres de l'assistant", "assistant_read_aloud": "Lire la réponse à voix haute en cas de question orale", "assistant_samsung": "Sur les téléphones Samsung : Paramètres › Fonctions avancées › Bouton latéral › Maintenir enfoncé › Assistant numérique.", @@ -707,7 +832,14 @@ "viewer_long_markdown": "Un fichier long, il est donc affiché en texte brut.", "viewer_open_browser": "Ouvrir dans le navigateur", "viewer_too_large": "Ce fichier est trop volumineux pour être affiché ; 1 Mo au plus peut être affiché.", - "viewer_unavailable": "Ce serveur ne peut pas encore transmettre le fichier à l'application. Ouvrez-le plutôt dans le navigateur." + "viewer_unavailable": "Ce serveur ne peut pas encore transmettre le fichier à l'application. Ouvrez-le plutôt dans le navigateur.", + "voice_input": "Saisie vocale", + "voice_input_hint": "Utilisée par l’assistant. Avec LLeMbas, les mots apparaissent avec un léger décalage et une pause les envoie ; avec la reconnaissance du téléphone, ils apparaissent pendant que vous parlez.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "La transcription de votre instance, via le serveur. L’enregistrement va à votre instance et nulle part ailleurs.", + "voice_input_phone": "Téléphone (Google ou celui du système)", + "voice_input_phone_line": "La reconnaissance vocale du téléphone. Les mots apparaissent pendant que vous parlez ; l’enregistrement va là où cette reconnaissance l’envoie.", + "voice_input_phone_none": "Ce téléphone n’a pas de reconnaissance vocale propre." }, "hu": { "about_version": "LLeMbas Androidra %1$s", @@ -727,12 +859,38 @@ "agent_runs_on": "Itt fut: %1$s, ebben: %2$s", "agent_stop_confirm": "Leállítja: %1$s? Amit eddig elvégzett, megmarad.", "archive": "Archiválás", + "assist_answer_in_app": "Ez a válasz az Ön döntésére vár: nyissa meg az alkalmazásban.", + "assist_connecting": "Csatlakozás…", + "assist_continue": "Az utolsó csevegés folytatása", + "assist_help": "Tartsa lenyomva a bekapcsológombot, hogy bármely alkalmazás fölött megnyissa az asszisztenst, vagy használja a Gyorsbeállítások csempét.", "assist_hint": "Kérdezzen bármit", - "assist_include_screen": "Képernyő hozzáadása", + "assist_no_model": "Nincs modell", + "assist_no_wake_word": "Ébresztőszó nincs: a gyári Androidon az ébresztőszó figyelése a telefonba épített asszisztensé.", + "assist_offline": "%1$s nem érhető el", "assist_open_app": "Alkalmazás megnyitása", "assist_open_in_app": "Folytatás az alkalmazásban", + "assist_quick_explain": "Magyarázat", + "assist_quick_explain_prompt": "Magyarázd el, mi van a képernyőmön.", + "assist_quick_summarise": "Összefoglalás", + "assist_quick_summarise_prompt": "Foglald össze, mi van a képernyőmön.", + "assist_quick_translate": "Fordítás", + "assist_quick_translate_prompt": "Fordítsd le magyarra, ami a képernyőmön van.", + "assist_read_aloud": "Felolvasás", + "assist_recogniser_failed": "A telefon beszédfelismerője leállt. Próbálja újra, vagy válassza a LLeMbast a Beállítások › Hangbevitel alatt.", + "assist_say_it": "Mondja, aztán tartson szünetet", + "assist_screen_both": "A képernyő szövege és egy képernyőkép a következő kérdésével megy.", + "assist_screen_shot": "Egy képernyőkép a következő kérdésével megy.", + "assist_screen_text": "A képernyő szövege a következő kérdésével megy.", + "assist_send_now": "Amit mondtam, küldés", "assist_signed_out": "Először jelentkezzen be egy LLeMbas példányba az alkalmazásban.", + "assist_stop_reading": "Felolvasás leállítása", + "assist_type": "Inkább gépelés", + "assist_use_screen": "Képernyő használata", + "assist_voice_reply_off": "A hangos válasz ki van kapcsolva", + "assist_voice_reply_on": "A hangos válasz be van kapcsolva", + "assist_writing_down": "Lejegyzem, amit mondott…", "assistant_explained": "Tegye az LLeMbas-t a telefon digitális asszisztensévé: válassza ki az Alapértelmezett alkalmazások › Digitális asszisztens alkalmazás alatt. A bekapcsológomb lenyomva tartása, az asszisztens-gesztus vagy a lezárási képernyő parancsikonja ezután a képernyőn lévő tartalom felett nyitja meg.", + "assistant_listens": "Hallgatás indítása az asszisztens megnyitásakor", "assistant_open_settings": "Asszisztens beállításainak megnyitása", "assistant_read_aloud": "Olvassa fel a választ, ha hangos kérdés érkezett", "assistant_samsung": "Samsung telefonokon: Beállítások › Speciális funkciók › Oldalgomb › Nyomva tartás › Digitális asszisztens.", @@ -885,7 +1043,14 @@ "viewer_long_markdown": "Hosszú fájl, ezért egyszerű szövegként jelenik meg.", "viewer_open_browser": "Megnyitás a böngészőben", "viewer_too_large": "Ez a fájl túl nagy a megjelenítéshez; legfeljebb 1 MB jeleníthető meg.", - "viewer_unavailable": "Ez a szerver még nem tudja átadni a fájlt az alkalmazásnak. Nyissa meg inkább a böngészőben." + "viewer_unavailable": "Ez a szerver még nem tudja átadni a fájlt az alkalmazásnak. Nyissa meg inkább a böngészőben.", + "voice_input": "Hangbevitel", + "voice_input_hint": "Az asszisztens használja. LLeMbasszal a szavak kis késéssel jelennek meg, és egy szünet elküldi őket; a telefon felismerőjével beszéd közben jelennek meg.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "A példánya beszédfelismerése, a szerveren át. A felvétel a példányához megy, máshová nem.", + "voice_input_phone": "Telefon (Google vagy a rendszeré)", + "voice_input_phone_line": "A telefon saját beszédfelismerője. A szavak beszéd közben jelennek meg; a felvétel oda megy, ahová az a felismerő küldi.", + "voice_input_phone_none": "Ennek a telefonnak nincs saját beszédfelismerője." }, "it": { "about_version": "LLeMbas per Android %1$s", @@ -905,12 +1070,38 @@ "agent_runs_on": "Gira su %1$s, in %2$s", "agent_stop_confirm": "Fermare %1$s? Ciò che ha fatto finora resta.", "archive": "Archivia", + "assist_answer_in_app": "Questa risposta attende una sua decisione: la apra nell’app.", + "assist_connecting": "Connessione…", + "assist_continue": "Continua l’ultima chat", + "assist_help": "Tenga premuto il tasto di accensione per aprire l’assistente sopra qualsiasi app, oppure usi il riquadro delle Impostazioni rapide.", "assist_hint": "Chiedi qualsiasi cosa", - "assist_include_screen": "Includi lo schermo", + "assist_no_model": "Nessun modello", + "assist_no_wake_word": "Non c’è una parola di attivazione: su Android standard, l’ascolto di una tale parola è riservato all’assistente integrato nel telefono.", + "assist_offline": "%1$s non è raggiungibile", "assist_open_app": "Apri l'app", "assist_open_in_app": "Continua nell'app", + "assist_quick_explain": "Spiega", + "assist_quick_explain_prompt": "Spiega cosa c’è sul mio schermo.", + "assist_quick_summarise": "Riassumi", + "assist_quick_summarise_prompt": "Riassumi cosa c’è sul mio schermo.", + "assist_quick_translate": "Traduci", + "assist_quick_translate_prompt": "Traduci in italiano cosa c’è sul mio schermo.", + "assist_read_aloud": "Leggi ad alta voce", + "assist_recogniser_failed": "Il riconoscimento vocale del telefono si è fermato. Riprovi, oppure scelga LLeMbas in Impostazioni › Input vocale.", + "assist_say_it": "Lo dica, poi faccia una pausa", + "assist_screen_both": "Il testo dello schermo e uno screenshot accompagnano la sua prossima domanda.", + "assist_screen_shot": "Uno screenshot accompagna la sua prossima domanda.", + "assist_screen_text": "Il testo dello schermo accompagna la sua prossima domanda.", + "assist_send_now": "Invia ciò che ho detto", "assist_signed_out": "Accedi prima a un'istanza LLeMbas nell'app.", + "assist_stop_reading": "Interrompi la lettura", + "assist_type": "Scrivi invece", + "assist_use_screen": "Usa lo schermo", + "assist_voice_reply_off": "Risposta vocale disattivata", + "assist_voice_reply_on": "Risposta vocale attiva", + "assist_writing_down": "Trascrivo ciò che ha detto…", "assistant_explained": "Rendi LLeMbas l'assistente digitale del telefono: selezionalo in App predefinite › App di assistenza digitale. Tenendo premuto il tasto di accensione, il gesto di assistenza o la scorciatoia della schermata di blocco lo apre quindi sopra qualsiasi cosa sia a schermo.", + "assistant_listens": "Inizia ad ascoltare all’apertura dell’assistente", "assistant_open_settings": "Apri le impostazioni dell'assistente", "assistant_read_aloud": "Leggi la risposta ad alta voce quando la domanda è vocale", "assistant_samsung": "Sui telefoni Samsung: Impostazioni › Funzioni avanzate › Tasto laterale › Pressione prolungata › Assistente digitale.", @@ -1062,7 +1253,14 @@ "viewer_long_markdown": "Un file lungo, quindi è mostrato come testo semplice.", "viewer_open_browser": "Apri nel browser", "viewer_too_large": "Questo file è troppo grande da mostrare; si può mostrare al massimo 1 MB.", - "viewer_unavailable": "Questo server non può ancora passare il file all'app. Aprilo invece nel browser." + "viewer_unavailable": "Questo server non può ancora passare il file all'app. Aprilo invece nel browser.", + "voice_input": "Input vocale", + "voice_input_hint": "La usa l’assistente. Con LLeMbas le parole appaiono con un attimo di ritardo e una pausa le invia; con il riconoscimento del telefono appaiono mentre parla.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "La trascrizione della sua istanza, tramite il server. La registrazione va alla sua istanza e da nessun’altra parte.", + "voice_input_phone": "Telefono (Google o quello di sistema)", + "voice_input_phone_line": "Il riconoscimento vocale del telefono. Le parole appaiono mentre parla; la registrazione va dove la manda quel riconoscimento.", + "voice_input_phone_none": "Questo telefono non ha un riconoscimento vocale proprio." }, "pl": { "about_version": "LLeMbas na Androida %1$s", @@ -1082,12 +1280,38 @@ "agent_runs_on": "Działa na %1$s, w %2$s", "agent_stop_confirm": "Zatrzymać %1$s? To, co już zrobił, zostaje.", "archive": "Archiwizuj", + "assist_answer_in_app": "Ta odpowiedź czeka na Twoją decyzję: otwórz ją w aplikacji.", + "assist_connecting": "Łączenie…", + "assist_continue": "Kontynuuj ostatni czat", + "assist_help": "Przytrzymaj przycisk zasilania, aby otworzyć asystenta nad dowolną aplikacją, albo użyj kafelka w Szybkich ustawieniach.", "assist_hint": "Zapytaj o cokolwiek", - "assist_include_screen": "Dołącz ekran", + "assist_no_model": "Brak modelu", + "assist_no_wake_word": "Nie ma słowa wybudzającego: w zwykłym Androidzie nasłuchiwanie go jest zarezerwowane dla asystenta wbudowanego w telefon.", + "assist_offline": "%1$s jest nieosiągalna", "assist_open_app": "Otwórz aplikację", "assist_open_in_app": "Kontynuuj w aplikacji", + "assist_quick_explain": "Wyjaśnij", + "assist_quick_explain_prompt": "Wyjaśnij, co jest na moim ekranie.", + "assist_quick_summarise": "Podsumuj", + "assist_quick_summarise_prompt": "Podsumuj, co jest na moim ekranie.", + "assist_quick_translate": "Przetłumacz", + "assist_quick_translate_prompt": "Przetłumacz na polski to, co jest na moim ekranie.", + "assist_read_aloud": "Przeczytaj na głos", + "assist_recogniser_failed": "Rozpoznawanie mowy w telefonie przestało działać. Spróbuj ponownie albo wybierz LLeMbas w Ustawienia › Wprowadzanie głosowe.", + "assist_say_it": "Powiedz to i zrób pauzę", + "assist_screen_both": "Tekst z ekranu i zrzut ekranu zostaną wysłane z następnym pytaniem.", + "assist_screen_shot": "Zrzut ekranu zostanie wysłany z następnym pytaniem.", + "assist_screen_text": "Tekst z ekranu zostanie wysłany z następnym pytaniem.", + "assist_send_now": "Wyślij, co powiedziałem", "assist_signed_out": "Najpierw zaloguj się do instancji LLeMbas w aplikacji.", + "assist_stop_reading": "Przestań czytać", + "assist_type": "Zamiast tego pisz", + "assist_use_screen": "Użyj ekranu", + "assist_voice_reply_off": "Odpowiedź głosowa wyłączona", + "assist_voice_reply_on": "Odpowiedź głosowa włączona", + "assist_writing_down": "Zapisuję, co powiedziałeś…", "assistant_explained": "Ustaw LLeMbas jako cyfrowego asystenta telefonu: wybierz go w Domyślne aplikacje › Aplikacja asystenta cyfrowego. Przytrzymanie przycisku zasilania, gest asystenta lub skrót z ekranu blokady otwiera go wtedy nad tym, co jest na ekranie.", + "assistant_listens": "Zacznij słuchać po otwarciu asystenta", "assistant_open_settings": "Otwórz ustawienia asystenta", "assistant_read_aloud": "Odczytaj odpowiedź na głos, gdy pytanie było głosowe", "assistant_samsung": "W telefonach Samsung: Ustawienia › Funkcje zaawansowane › Przycisk boczny › Naciśnięcie i przytrzymanie › Asystent cyfrowy.", @@ -1239,7 +1463,14 @@ "viewer_long_markdown": "Długi plik, dlatego jest pokazany jako zwykły tekst.", "viewer_open_browser": "Otwórz w przeglądarce", "viewer_too_large": "Ten plik jest za duży, by go pokazać; można pokazać najwyżej 1 MB.", - "viewer_unavailable": "Ten serwer nie potrafi jeszcze przekazać pliku aplikacji. Otwórz go w przeglądarce." + "viewer_unavailable": "Ten serwer nie potrafi jeszcze przekazać pliku aplikacji. Otwórz go w przeglądarce.", + "voice_input": "Wprowadzanie głosowe", + "voice_input_hint": "Używa go asystent. Z LLeMbas słowa pojawiają się z lekkim opóźnieniem, a pauza je wysyła; z rozpoznawaniem telefonu pojawiają się w trakcie mówienia.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "Zamiana mowy na tekst Twojej instancji, przez serwer. Nagranie trafia do Twojej instancji i nigdzie indziej.", + "voice_input_phone": "Telefon (Google lub systemowy)", + "voice_input_phone_line": "Własne rozpoznawanie mowy telefonu. Słowa pojawiają się w trakcie mówienia; nagranie trafia tam, dokąd wyśle je to rozpoznawanie.", + "voice_input_phone_none": "Ten telefon nie ma własnego rozpoznawania mowy." }, "sk": { "about_version": "LLeMbas pre Android %1$s", @@ -1259,12 +1490,38 @@ "agent_runs_on": "Beží na %1$s, v priečinku %2$s", "agent_stop_confirm": "Zastaviť %1$s? Čo doteraz urobil, zostane.", "archive": "Archivovať", + "assist_answer_in_app": "Táto odpoveď čaká na vaše rozhodnutie: otvorte ju v aplikácii.", + "assist_connecting": "Pripája sa…", + "assist_continue": "Pokračovať v poslednej konverzácii", + "assist_help": "Podržaním tlačidla napájania otvoríte asistenta nad ľubovoľnou aplikáciou; alebo použite dlaždicu v Rýchlych nastaveniach.", "assist_hint": "Spýtajte sa na čokoľvek", - "assist_include_screen": "Zahrnúť obrazovku", + "assist_no_model": "Žiadny model", + "assist_no_wake_word": "Budiace slovo nie je: na bežnom Androide je počúvanie budiaceho slova vyhradené asistentovi zabudovanému v telefóne.", + "assist_offline": "%1$s je nedostupná", "assist_open_app": "Otvoriť aplikáciu", "assist_open_in_app": "Pokračovať v aplikácii", + "assist_quick_explain": "Vysvetliť", + "assist_quick_explain_prompt": "Vysvetli, čo je na mojej obrazovke.", + "assist_quick_summarise": "Zhrnúť", + "assist_quick_summarise_prompt": "Zhrň, čo je na mojej obrazovke.", + "assist_quick_translate": "Preložiť", + "assist_quick_translate_prompt": "Prelož do slovenčiny, čo je na mojej obrazovke.", + "assist_read_aloud": "Prečítať nahlas", + "assist_recogniser_failed": "Rozpoznávanie reči v telefóne sa zastavilo. Skúste to znova alebo zvoľte LLeMbas v Nastaveniach › Hlasový vstup.", + "assist_say_it": "Povedzte to a odmlčte sa", + "assist_screen_both": "S vašou ďalšou otázkou pôjde text obrazovky a snímka obrazovky.", + "assist_screen_shot": "S vašou ďalšou otázkou pôjde snímka obrazovky.", + "assist_screen_text": "S vašou ďalšou otázkou pôjde text obrazovky.", + "assist_send_now": "Odoslať, čo som povedal", "assist_signed_out": "Najprv sa v aplikácii prihláste do inštancie LLeMbas.", + "assist_stop_reading": "Prestať čítať", + "assist_type": "Radšej písať", + "assist_use_screen": "Použiť obrazovku", + "assist_voice_reply_off": "Hlasová odpoveď je vypnutá", + "assist_voice_reply_on": "Hlasová odpoveď je zapnutá", + "assist_writing_down": "Zapisujem, čo ste povedali…", "assistant_explained": "Nastavte LLeMbas ako digitálneho asistenta telefónu: zvoľte ho v Predvolené aplikácie › Digitálny asistent. Podržanie tlačidla napájania, gesto asistenta alebo skratka na uzamknutej obrazovke ho potom otvorí nad tým, čo je práve na obrazovke.", + "assistant_listens": "Začať počúvať, keď sa asistent otvorí", "assistant_open_settings": "Otvoriť nastavenia asistenta", "assistant_read_aloud": "Prečítať odpoveď nahlas, keď sa spýtate hlasom", "assistant_samsung": "Na telefónoch Samsung: Nastavenia › Rozšírené funkcie › Tlačidlo na boku › Stlačenie a podržanie › Digitálny asistent.", @@ -1416,6 +1673,13 @@ "viewer_long_markdown": "Dlhý súbor, preto je zobrazený ako obyčajný text.", "viewer_open_browser": "Otvoriť v prehliadači", "viewer_too_large": "Tento súbor je príliš veľký na zobrazenie; zobraziť možno najviac 1 MB.", - "viewer_unavailable": "Tento server zatiaľ nevie aplikácii súbor odovzdať. Otvorte ho v prehliadači." + "viewer_unavailable": "Tento server zatiaľ nevie aplikácii súbor odovzdať. Otvorte ho v prehliadači.", + "voice_input": "Hlasový vstup", + "voice_input_hint": "Používa ho asistent. S LLeMbas sa slová objavujú s malým oneskorením a pauza ich odošle; s rozpoznávaním v telefóne sa objavujú, ako hovoríte.", + "voice_input_lembas": "LLeMbas", + "voice_input_lembas_line": "Prevod reči na text vašej inštancie, cez server. Nahrávka ide na vašu inštanciu a nikam inam.", + "voice_input_phone": "Telefón (Google alebo systémový)", + "voice_input_phone_line": "Vlastné rozpoznávanie reči v telefóne. Slová sa objavujú, ako hovoríte; nahrávka ide tam, kam ju to rozpoznávanie pošle.", + "voice_input_phone_none": "Tento telefón nemá vlastné rozpoznávanie reči." } }