diff --git a/CHANGELOG.md b/CHANGELOG.md index e7882a3..ec62d61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ is in alpha and releases come off `main`. ## [Unreleased] +For what is new here the instance must be newer than LLeMbas 2.0.0-beta.14; an older one ignores +what the app adds and answers as before. + +### Added + +- **Dictation and Read aloud follow the chat's model.** An instance may now give a connection + speech models of its own, used for the chats whose model is on that connection. The app says + which chat a recording or a reading is for: the chat it is in, or -- before the chat exists -- + the model chosen for it (in the assistant, the assistant's model). Dictation into another app + belongs to no chat and stays on the instance's default. When the chat's own speech model did + not answer and the default did, the chat says so once, quietly, naming what answered; the + assistant's sheet does not say it, because it may be open over the lock screen. Nothing new + is sent while the phone is locked. + ## [1.0.0-beta.11] — 2026-11-18 Needs LLeMbas 2.0.0-beta.14 for what is new here; with an older instance the app works as before. diff --git a/app/src/main/java/eu/llembas/android/api/ApiClient.kt b/app/src/main/java/eu/llembas/android/api/ApiClient.kt index 40e8336..d073959 100644 --- a/app/src/main/java/eu/llembas/android/api/ApiClient.kt +++ b/app/src/main/java/eu/llembas/android/api/ApiClient.kt @@ -619,22 +619,28 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli suspend fun forgetPush() = empty(authed("$v2/push").delete().build()) // --- Voice (/v1, the `models` scope) ----------------------------------------------------- - suspend fun transcribe(wav: ByteArray, language: String? = null): String { + + /** + * Write a recording down. [media] says which chat it is for, so that the chat's model's + * connection may serve it with its own speech model (server 2.0.0-beta.15); a server before + * that reads only the fields it knows and answers from its one endpoint. + */ + suspend fun transcribe(wav: ByteArray, language: String? = null, media: MediaFor = MediaFor.DEFAULT): Heard = withContext(Dispatchers.IO) { val body = MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("file", "speech.wav", wav.toRequestBody("audio/wav".toMediaType())) - .apply { language?.let { addFormDataPart("language", it) } } + .apply { transcriptionFields(language, media).forEach { (name, value) -> addFormDataPart(name, value) } } .build() - return call(authed("$base/v1/audio/transcriptions").post(body).build(), Transcript.serializer()).text + http.newCall(authed("$base/v1/audio/transcriptions").post(body).build()).await().use { + if (!it.isSuccessful) throw ApiException(it.code, detail(it)) + Heard(LembasJson.decodeFromString(Transcript.serializer(), it.body!!.string()).text, fallbackSource(it)) + } } - suspend fun speech(text: String): ByteArray = withContext(Dispatchers.IO) { - val body = buildJsonObject { - put("input", text.take(20_000)) - put("response_format", "mp3") - } - http.newCall(authed("$base/v1/audio/speech").post(body.toString().toRequestBody(JSON)).build()).await().use { + /** [text] as speech, for the chat [media] names (see [transcribe]). */ + suspend fun speech(text: String, media: MediaFor = MediaFor.DEFAULT): Spoken = withContext(Dispatchers.IO) { + http.newCall(authed("$base/v1/audio/speech").post(speechBody(text, media).toString().toRequestBody(JSON)).build()).await().use { if (!it.isSuccessful) throw ApiException(it.code, detail(it)) - it.body!!.bytes() + Spoken(it.body!!.bytes(), fallbackSource(it)) } } @@ -655,6 +661,33 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli /** 1 MB, the server's own limit on a shown file, with room for a little more. */ const val SHOWN_MAX_BYTES = 1_100_000L + /** The transcription's form fields beside the file: the language, and which chat. */ + fun transcriptionFields(language: String?, media: MediaFor): List> = buildList { + language?.let { add("language" to it) } + media.chatId?.let { add("chat_id" to it) } + media.chatModel?.let { add("chat_model" to it) } + } + + /** The body of a speech request: the words, the format, and which chat. */ + fun speechBody(text: String, media: MediaFor): JsonObject = buildJsonObject { + put("input", text.take(20_000)) + put("response_format", "mp3") + media.chatId?.let { put("chat_id", it) } + media.chatModel?.let { put("chat_model", it) } + } + + /** + * The source that answered in place of the chat's own (`X-Lembas-Fallback`), by its name + * (`X-Lembas-Source`, percent-encoded: a header is Latin-1); null when the one expected + * answered, and from a server that says neither. + */ + fun fallbackSource(fallback: String?, source: String?): String? { + if (fallback.isNullOrBlank() || fallback == "0" || source.isNullOrBlank()) return null + return runCatching { java.net.URLDecoder.decode(source.replace("+", "%2B"), "UTF-8") }.getOrDefault(source).ifBlank { null } + } + + private fun fallbackSource(response: Response): String? = fallbackSource(response.header("X-Lembas-Fallback"), response.header("X-Lembas-Source")) + fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null) /** A model's picture is small; anything larger is not one. */ diff --git a/app/src/main/java/eu/llembas/android/api/Models.kt b/app/src/main/java/eu/llembas/android/api/Models.kt index eede8d6..42beebf 100644 --- a/app/src/main/java/eu/llembas/android/api/Models.kt +++ b/app/src/main/java/eu/llembas/android/api/Models.kt @@ -730,6 +730,31 @@ data class PushKey(val key: String = "", val registered: Boolean = false) @Serializable data class Transcript(val text: String = "") +/** + * Which chat a recording or a reading is for: the chat's own id, or -- for a chat that does not + * exist yet -- the model it will be on. The instance serves it from that model's connection + * where the connection has speech models of its own; with neither ([DEFAULT]) from its default. + * Never both: a chat that exists says its model itself. + */ +data class MediaFor(val chatId: String? = null, val chatModel: String? = null) { + companion object { + /** No chat: another app's dictation. */ + val DEFAULT = MediaFor() + + fun of(chatId: String?, model: String?): MediaFor = when { + !chatId.isNullOrBlank() -> MediaFor(chatId = chatId) + !model.isNullOrBlank() -> MediaFor(chatModel = model) + else -> DEFAULT + } + } +} + +/** A recording written down; [fallback] names the source that answered when the chat's own did not. */ +data class Heard(val text: String, val fallback: String? = null) + +/** Words as sound (mp3); [fallback] as [Heard]'s. */ +class Spoken(val audio: ByteArray, val fallback: String? = null) + // --- The stream's frames ----------------------------------------------------------------- @Serializable data class Tail(val thinking: String = "", val text: String = "", val label: String = "") 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 259d888..e0fa5e0 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistController.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistController.kt @@ -16,6 +16,7 @@ import eu.llembas.android.api.ApiException import eu.llembas.android.api.Card import eu.llembas.android.api.CardAnswer import eu.llembas.android.api.LiveReply +import eu.llembas.android.api.MediaFor import eu.llembas.android.api.ModelInfo import eu.llembas.android.api.Step import eu.llembas.android.api.StreamClient @@ -335,7 +336,7 @@ class AssistController( scope.launch { try { _state.update { it.copy(busy = true, error = null) } - val text = context.lembas.instances.client()?.transcribe(wav).orEmpty() + val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty() _state.update { it.copy(busy = false) } if (text.isNotBlank()) ask(text, spoken = true) } catch (e: CancellationException) { @@ -454,7 +455,7 @@ class AssistController( val seconds = recorder.seconds if (seconds - sent < 0.5f || seconds > 60f || ear?.heardSomething != true || locked()) continue sent = seconds - val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull() + val words = runCatching { api.transcribe(recorder.snapshot(), media = mediaFor()).text }.getOrNull() if (!words.isNullOrBlank() && _state.value.listening) _state.update { it.copy(heard = words) } } } @@ -549,7 +550,7 @@ class AssistController( } try { _state.update { it.copy(busy = true) } - val text = context.lembas.instances.client()?.transcribe(wav).orEmpty() + val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty() _state.update { it.copy(busy = false, heard = "") } if (text.isNotBlank()) askOrStop(text) else endConversation() } catch (e: Exception) { @@ -779,13 +780,19 @@ class AssistController( /** Stop the voice -- and, in a conversation, the listening that would follow it. */ override fun stopReading() = speaker.stop() + /** + * Which chat the sheet's speech is for: the chat it is in, else the model its next chat + * starts on. That a fallback answered is not said here: the sheet may be over the lock. + */ + private fun mediaFor(): MediaFor = _state.value.let { MediaFor.of(it.chatId, it.modelId ?: newChatModel) } + /** Read [words] aloud; true when they were heard to the end. */ private suspend fun speak(words: String): Boolean { // Never aloud over the lock screen: an answer is the account's. if (words.isBlank() || locked()) return false return try { val api = context.lembas.instances.client() ?: return false - speaker.playToEnd(api.speech(words)) + speaker.playToEnd(api.speech(words, mediaFor()).audio) } catch (e: Exception) { _state.update { it.copy(error = context.explain(e)) } false diff --git a/app/src/main/java/eu/llembas/android/assist/LembasRecognitionService.kt b/app/src/main/java/eu/llembas/android/assist/LembasRecognitionService.kt index bbd12e4..3eb0c92 100644 --- a/app/src/main/java/eu/llembas/android/assist/LembasRecognitionService.kt +++ b/app/src/main/java/eu/llembas/android/assist/LembasRecognitionService.kt @@ -11,6 +11,7 @@ import android.speech.RecognitionService import android.speech.RecognizerIntent import android.speech.SpeechRecognizer import androidx.annotation.RequiresApi +import eu.llembas.android.api.MediaFor import eu.llembas.android.lembas import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -200,7 +201,8 @@ class LembasRecognitionService : RecognitionService() { return@launch } try { - val text = lembas.instances.client()?.transcribe(wav).orEmpty() + // Another app's dictation belongs to no chat: the instance's default writes it down. + val text = lembas.instances.client()?.transcribe(wav, media = MediaFor.DEFAULT)?.text.orEmpty() if (text.isBlank()) { listener.error(SpeechRecognizer.ERROR_NO_MATCH) } else { diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt index 7edd9e5..f8c0d56 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatScreen.kt @@ -148,7 +148,15 @@ fun ChatScreen( // Read aloud on a reply, when the instance has a voice; it stops when the chat is left. val context = LocalContext.current val scope = rememberCoroutineScope() - val readAloud = remember { ReadAloud(context, scope) { said -> scope.launch { snackbar.showSnackbar(said) } } } + val readAloud = remember { + ReadAloud( + context, + scope, + media = { model.state.value.mediaFor }, + onFallback = { source -> model.mediaFellBack(MEDIA_SPEECH, context.getString(R.string.read_by_fallback, source)) }, + onError = { said -> scope.launch { snackbar.showSnackbar(said) } }, + ) + } LaunchedEffect(Unit) { readAloud.load() } DisposableEffect(Unit) { onDispose { readAloud.stop() } } diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt index 7e28c9a..6e36c07 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ChatViewModel.kt @@ -25,6 +25,7 @@ import eu.llembas.android.api.DeviceDirectory import eu.llembas.android.api.LembasJson import eu.llembas.android.api.LinkedDevice import eu.llembas.android.api.LiveReply +import eu.llembas.android.api.MediaFor import eu.llembas.android.api.Mention import eu.llembas.android.api.Message import eu.llembas.android.api.MessagePage @@ -146,6 +147,23 @@ val ChatState.folderModel: String? val ChatState.modelInfo: ModelInfo? get() = models.named(modelId) +/** + * Which chat a dictation or a reply read aloud is for: this chat once it exists, else the model + * a new one would be on -- so the instance can serve it from that model's connection. + */ +val ChatState.mediaFor: MediaFor get() = MediaFor.of(chat?.id, modelId) + +/** The two things a chat asks the instance's speech for, each with its own one note of a fallback. */ +const val MEDIA_DICTATION = "dictation" +const val MEDIA_SPEECH = "speech" + +/** + * Whether a fallback of [kind] is still to be said, given what was [told]: once per kind for as + * long as the chat is open. A connection's speech model that is down stays down for a while, + * and the same sentence after every dictation is noise. + */ +fun fallbackToSay(told: Set, kind: String): Boolean = kind !in told + /** The thinking level in force, by the model's levels; null for a model with no choice. */ val ChatState.level: String? get() = modelInfo?.takeIf { it.levelControl != "none" }?.level(if (chat == null) draft.effort else chat.effort?.ifBlank { null }) @@ -227,6 +245,9 @@ interface ChatActions { fun answer(card: Card, answer: CardAnswer) {} fun change(key: String, value: String?) {} + /** The instance's default answered a dictation or a reading ([kind]) for the chat's own: [sentence] says so, once. */ + fun mediaFellBack(kind: String, sentence: String) {} + /** A new agent chat with no computer linked: read the linked devices again. */ fun recheckDevices() {} @@ -545,6 +566,14 @@ class ChatViewModel(app: Application) : refresh() } + private val toldFallback = mutableSetOf() + + override fun mediaFellBack(kind: String, sentence: String) { + if (!fallbackToSay(toldFallback, kind)) return + toldFallback += kind + _state.update { it.copy(notice = sentence) } + } + override fun answer(card: Card, answer: CardAnswer) = control { api, chat -> try { api.answer(chat.id, card.id, answer) diff --git a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt index 087a431..012377e 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/Composer.kt @@ -395,8 +395,12 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () scope.launch { val wav = recorder.stop() if (wav.isNotEmpty()) { - runCatching { context.lembas.instances.client()?.transcribe(wav) } - .onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() } + runCatching { context.lembas.instances.client()?.transcribe(wav, media = state.mediaFor) } + .onSuccess { heard -> + val said = heard?.text + if (!said.isNullOrBlank()) text = (text + " " + said).trim() + heard?.fallback?.let { actions.mediaFellBack(MEDIA_DICTATION, context.getString(R.string.transcribed_by_fallback, it)) } + } } } } else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { diff --git a/app/src/main/java/eu/llembas/android/ui/chat/ReadAloud.kt b/app/src/main/java/eu/llembas/android/ui/chat/ReadAloud.kt index bf7530a..57cd320 100644 --- a/app/src/main/java/eu/llembas/android/ui/chat/ReadAloud.kt +++ b/app/src/main/java/eu/llembas/android/ui/chat/ReadAloud.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import eu.llembas.android.api.MediaFor import eu.llembas.android.assist.AssistController import eu.llembas.android.assist.Speaker import eu.llembas.android.lembas @@ -23,7 +24,15 @@ import kotlinx.coroutines.launch * shows a button that can only fail. */ @Stable -class ReadAloud(private val context: Context, private val scope: CoroutineScope, private val onError: (String) -> Unit) { +class ReadAloud( + private val context: Context, + private val scope: CoroutineScope, + /** Which chat is read from, asked at each reading: its connection may have a voice of its own. */ + private val media: () -> MediaFor = { MediaFor.DEFAULT }, + /** Another source read it than the chat's own: its name. */ + private val onFallback: (String) -> Unit = {}, + private val onError: (String) -> Unit, +) { private val speaker = Speaker(context) private var job: Job? = null @@ -45,7 +54,9 @@ class ReadAloud(private val context: Context, private val scope: CoroutineScope, job = scope.launch { try { val api = context.lembas.instances.client() ?: return@launch - speaker.play(api.speech(AssistController.plain(markdown))) + val spoken = api.speech(AssistController.plain(markdown), media()) + spoken.fallback?.let(onFallback) + speaker.play(spoken.audio) speaker.playing.first { !it } } catch (e: CancellationException) { throw e diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index ad6c867..c03b87c 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -71,6 +71,8 @@ Zkusit znovu Instance není dostupná. Zkontrolujte připojení telefonu a to, zda se dostane na adresu instance. Diktovat + Přepsal %1$s: vlastní model řeči tohoto chatu neodpověděl. + Přečetl %1$s: vlastní model řeči tohoto chatu neodpověděl. Odebrat Více Zpět diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 214ad6d..7961c6e 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -71,6 +71,8 @@ Erneut versuchen Die Instanz ist nicht erreichbar. Prüfen Sie die Verbindung des Telefons und ob es die Adresse der Instanz erreicht. Diktieren + Transkribiert von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet. + Vorgelesen von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet. Entfernen Mehr Zurück diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 1e4c77d..3709e80 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -71,6 +71,8 @@ Reintentar No se puede acceder a la instancia. Compruebe la conexión del teléfono y que llegue a la dirección de la instancia. Dictar + Transcrito por %1$s: el modelo de voz propio de este chat no respondió. + Leído por %1$s: el modelo de voz propio de este chat no respondió. Quitar Más Volver diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 1854b2d..0f8c57e 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -71,6 +71,8 @@ Réessayer L\'instance est injoignable. Vérifiez la connexion du téléphone et qu\'il atteint bien l\'adresse de l\'instance. Dicter + Transcrit par %1$s : le modèle vocal propre à cette discussion n\'a pas répondu. + Lu par %1$s : le modèle vocal propre à cette discussion n\'a pas répondu. Retirer Plus Retour diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 84d026c..1726ee2 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -71,6 +71,8 @@ Újrapróbálás A példány nem érhető el. Ellenőrizze a telefon kapcsolatát, és hogy eléri-e a példány címét. Diktálás + Átírta: %1$s — a csevegés saját beszédmodellje nem válaszolt. + Felolvasta: %1$s — a csevegés saját beszédmodellje nem válaszolt. Eltávolítás Továbbiak Vissza diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 6702fd9..209aad0 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -71,6 +71,8 @@ Riprova L\'istanza non è raggiungibile. Controlla la connessione del telefono e che raggiunga l\'indirizzo dell\'istanza. Detta + Trascritto da %1$s: il modello vocale proprio di questa chat non ha risposto. + Letto da %1$s: il modello vocale proprio di questa chat non ha risposto. Rimuovi Altro Indietro diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a7bc0e4..9b98e59 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -71,6 +71,8 @@ Spróbuj ponownie Instancja jest nieosiągalna. Sprawdź połączenie telefonu i czy dociera on do adresu instancji. Dyktuj + Transkrybował %1$s: własny model mowy tego czatu nie odpowiedział. + Przeczytał %1$s: własny model mowy tego czatu nie odpowiedział. Usuń Więcej Wstecz diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 6e924f4..b9f0249 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -71,6 +71,8 @@ Skúsiť znova Inštancia nie je dostupná. Skontrolujte pripojenie telefónu a či sa dostane na adresu inštancie. Diktovať + Prepísal %1$s: vlastný model reči tohto chatu neodpovedal. + Prečítal %1$s: vlastný model reči tohto chatu neodpovedal. Odstrániť Viac Späť diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0a7cc78..326eba4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -72,6 +72,8 @@ Try again The instance cannot be reached. Check the phone\'s connection, and that it can reach the instance\'s address. Dictate + Transcribed by %1$s: this chat\'s own speech model did not answer. + Read by %1$s: this chat\'s own speech model did not answer. Remove More Back diff --git a/app/src/test/java/eu/llembas/android/MediaForTest.kt b/app/src/test/java/eu/llembas/android/MediaForTest.kt new file mode 100644 index 0000000..3938835 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/MediaForTest.kt @@ -0,0 +1,139 @@ +package eu.llembas.android + +import eu.llembas.android.api.ApiClient +import eu.llembas.android.api.Chat +import eu.llembas.android.api.MediaFor +import eu.llembas.android.api.ModelInfo +import eu.llembas.android.ui.chat.ChatState +import eu.llembas.android.ui.chat.Draft +import eu.llembas.android.ui.chat.MEDIA_DICTATION +import eu.llembas.android.ui.chat.MEDIA_SPEECH +import eu.llembas.android.ui.chat.fallbackToSay +import eu.llembas.android.ui.chat.mediaFor +import kotlinx.coroutines.test.runTest +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Speech follows the chat's model (server 2.0.0-beta.15): a transcription or a speech request + * says which chat it is for -- `chat_id`, or `chat_model` before the chat exists -- and never + * both; another app's dictation says neither. + */ +class MediaForTest { + private lateinit var server: MockWebServer + + @Before + fun up() { + server = MockWebServer().apply { start() } + } + + @After + fun down() = server.shutdown() + + private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test") + + @Test + fun aChatThatExistsIsNamedByItsIdAlone() { + assertEquals(MediaFor(chatId = "c1"), MediaFor.of("c1", "shire/pippin")) + assertEquals(MediaFor(chatModel = "shire/pippin"), MediaFor.of(null, "shire/pippin")) + assertEquals(MediaFor(chatModel = "shire/pippin"), MediaFor.of(" ", "shire/pippin")) + assertEquals(MediaFor.DEFAULT, MediaFor.of(null, null)) + assertEquals(MediaFor.DEFAULT, MediaFor.of("", " ")) + } + + @Test + fun theTranscriptionFieldsSayWhichChat() { + assertEquals(listOf("chat_id" to "c1"), ApiClient.transcriptionFields(null, MediaFor.of("c1", "shire/pippin"))) + assertEquals( + listOf("language" to "sk", "chat_model" to "shire/pippin"), + ApiClient.transcriptionFields("sk", MediaFor.of(null, "shire/pippin")), + ) + assertEquals(emptyList>(), ApiClient.transcriptionFields(null, MediaFor.DEFAULT)) + } + + @Test + fun theSpeechBodySaysWhichChat() { + val inChat = ApiClient.speechBody("Hello", MediaFor.of("c1", "shire/pippin")).toString() + assertTrue(inChat, inChat.contains("\"chat_id\":\"c1\"")) + assertFalse(inChat, inChat.contains("chat_model")) + assertTrue(inChat, inChat.contains("\"input\":\"Hello\"")) + val before = ApiClient.speechBody("Hello", MediaFor.of(null, "shire/pippin")).toString() + assertTrue(before, before.contains("\"chat_model\":\"shire/pippin\"")) + assertFalse(before, before.contains("chat_id")) + val none = ApiClient.speechBody("Hello", MediaFor.DEFAULT).toString() + assertFalse(none, none.contains("chat_")) + } + + @Test + fun aTranscriptionCarriesTheChatAndReadsTheFallback() = runTest { + server.enqueue( + MockResponse().setBody("""{"text":"Second breakfast"}""") + .setHeader("X-Lembas-Source", "Bree%20%2B%20Inn").setHeader("X-Lembas-Fallback", "1"), + ) + val heard = client().transcribe(ByteArray(64), media = MediaFor.of("c1", null)) + assertEquals("Second breakfast", heard.text) + assertEquals("Bree + Inn", heard.fallback) + val request = server.takeRequest() + assertEquals("/v1/audio/transcriptions", request.path) + val body = request.body.readUtf8() + assertTrue(body, body.contains("name=\"chat_id\"")) + assertFalse(body, body.contains("chat_model")) + } + + @Test + fun anotherAppsDictationNamesNoChat() = runTest { + server.enqueue(MockResponse().setBody("""{"text":"Elevenses"}""").setHeader("X-Lembas-Source", "stt%2Fsmall")) + val heard = client().transcribe(ByteArray(64)) + assertEquals("Elevenses", heard.text) + // The source is named, and it is the one expected: nothing to say. + assertNull(heard.fallback) + val body = server.takeRequest().body.readUtf8() + assertFalse(body, body.contains("chat_id")) + assertFalse(body, body.contains("chat_model")) + } + + @Test + fun speechCarriesTheModelOfAChatNotMadeYet() = runTest { + server.enqueue(MockResponse().setBody("mp3")) + val spoken = client().speech("Hello", MediaFor.of(null, "shire/pippin")) + // An older server names no source at all. + assertNull(spoken.fallback) + assertEquals(3, spoken.audio.size) + val request = server.takeRequest() + assertEquals("/v1/audio/speech", request.path) + assertTrue(request.body.readUtf8().contains("\"chat_model\":\"shire/pippin\"")) + } + + @Test + fun aFallbackIsNamedOnlyWhenTheServerSaysBoth() { + assertEquals("Bree", ApiClient.fallbackSource("1", "Bree")) + assertNull(ApiClient.fallbackSource(null, "Bree")) + assertNull(ApiClient.fallbackSource("1", null)) + assertNull(ApiClient.fallbackSource("0", "Bree")) + // A name that is not percent-encoding stays as it came. + assertEquals("100%", ApiClient.fallbackSource("1", "100%")) + } + + @Test + fun theChatScreenNamesItsChatOrTheModelItWillBeOn() { + val models = listOf(ModelInfo(id = "pippin", ref = "shire/pippin", default = true), ModelInfo(id = "merry", ref = "buckland/merry")) + assertEquals(MediaFor(chatModel = "shire/pippin"), ChatState(models = models).mediaFor) + assertEquals(MediaFor(chatModel = "buckland/merry"), ChatState(models = models, draft = Draft(model = "buckland/merry")).mediaFor) + assertEquals(MediaFor(chatId = "c1"), ChatState(models = models, chat = Chat(id = "c1", model = "merry")).mediaFor) + assertEquals(MediaFor.DEFAULT, ChatState().mediaFor) + } + + @Test + fun aFallbackIsSaidOncePerKind() { + assertTrue(fallbackToSay(emptySet(), MEDIA_DICTATION)) + assertFalse(fallbackToSay(setOf(MEDIA_DICTATION), MEDIA_DICTATION)) + assertTrue(fallbackToSay(setOf(MEDIA_DICTATION), MEDIA_SPEECH)) + } +} diff --git a/scripts/strings.py b/scripts/strings.py index 4638966..e072b40 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -84,6 +84,10 @@ STRINGS: dict[str, str] = { "retry": "Try again", "offline": "The instance cannot be reached. Check the phone's connection, and that it can reach the instance's address.", "dictate": "Dictate", + # A connection's own speech model did not answer and the instance's default did (the + # server's sentences, `SERVER_ENGLISH`): a note in the chat, once. + "transcribed_by_fallback": "Transcribed by %1$s: this chat's own speech model did not answer.", + "read_by_fallback": "Read by %1$s: this chat's own speech model did not answer.", "remove": "Remove", "more": "More", "back": "Back", @@ -643,6 +647,8 @@ STRINGS: dict[str, str] = { # taken from the server's catalogue and its named placeholders numbered in the order the # English names them -- so "%(steps)s steps, %(tools)s tools" becomes `%1$s`, `%2$s`. SERVER_ENGLISH: dict[str, str] = { + "transcribed_by_fallback": "Transcribed by %(source)s: this chat's own speech model did not answer.", + "read_by_fallback": "Read by %(source)s: this chat's own speech model did not answer.", # The progress texts: the server's catalogues key them by the spec's English, {{fields}} and all. "progress_queued_ahead": "Queued: {{ahead}} ahead", "progress_waiting_for_model": "Waiting for {{model}}: {{reason}}", diff --git a/scripts/strings_own.json b/scripts/strings_own.json index 563ac25..6145c92 100644 --- a/scripts/strings_own.json +++ b/scripts/strings_own.json @@ -395,7 +395,9 @@ "wake_word_unavailable": "V tomto sestavení není. Sestavení pro F-Droid nemá modul pro budicí slovo, protože F-Droid sestavuje každou knihovnu ze zdrojů; sestavení z llembas.eu ho má.", "widget_description": "Ptejte se hlasem nebo textem, nebo pokračujte v poslední konverzaci s asistentem. Neukazuje nic z vašeho účtu.", "widget_hint": "Zeptejte se na cokoli", - "widget_speak": "Mluvit" + "widget_speak": "Mluvit", + "transcribed_by_fallback": "Přepsal %1$s: vlastní model řeči tohoto chatu neodpověděl.", + "read_by_fallback": "Přečetl %1$s: vlastní model řeči tohoto chatu neodpověděl." }, "de": { "about_version": "LLeMbas für Android %1$s", @@ -794,7 +796,9 @@ "wake_word_unavailable": "Nicht in diesem Build. Der F-Droid-Build hat keine Aktivierungswort-Engine, weil F-Droid jede Bibliothek aus dem Quellcode baut; der Build von llembas.eu hat eine.", "widget_description": "Per Sprache oder Text fragen oder den letzten Assistenten-Chat fortsetzen. Zeigt nichts aus Ihrem Konto.", "widget_hint": "Frag mich alles", - "widget_speak": "Sprechen" + "widget_speak": "Sprechen", + "transcribed_by_fallback": "Transkribiert von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet.", + "read_by_fallback": "Vorgelesen von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet." }, "es": { "about_version": "LLeMbas para Android %1$s", @@ -1192,7 +1196,9 @@ "wake_word_unavailable": "No en esta versión. La versión de F-Droid no tiene motor de palabra de activación, porque F-Droid compila cada biblioteca desde el código fuente; la de llembas.eu sí lo tiene.", "widget_description": "Pregunta por voz o por texto, o continúa el último chat del asistente. No muestra nada de tu cuenta.", "widget_hint": "Pregunta lo que quieras", - "widget_speak": "Hablar" + "widget_speak": "Hablar", + "transcribed_by_fallback": "Transcrito por %1$s: el modelo de voz propio de este chat no respondió.", + "read_by_fallback": "Leído por %1$s: el modelo de voz propio de este chat no respondió." }, "fr": { "about_version": "LLeMbas pour Android %1$s", @@ -1591,7 +1597,9 @@ "wake_word_unavailable": "Pas dans cette version. La version F-Droid n’a pas de moteur de mot d’activation, car F-Droid compile chaque bibliothèque depuis les sources ; celle de llembas.eu en a un.", "widget_description": "Demandez à la voix ou par écrit, ou reprenez la dernière discussion de l’assistant. N’affiche rien de votre compte.", "widget_hint": "Posez une question", - "widget_speak": "Parler" + "widget_speak": "Parler", + "transcribed_by_fallback": "Transcrit par %1$s : le modèle vocal propre à cette discussion n'a pas répondu.", + "read_by_fallback": "Lu par %1$s : le modèle vocal propre à cette discussion n'a pas répondu." }, "hu": { "about_version": "LLeMbas Androidra %1$s", @@ -1990,7 +1998,9 @@ "wake_word_unavailable": "Ebben a változatban nincs. Az F-Droid-változatban nincs ébresztőszó-motor, mert az F-Droid minden könyvtárat forrásból fordít; a llembas.eu-s változatban van.", "widget_description": "Kérdezz hanggal vagy szöveggel, vagy folytasd az asszisztens legutóbbi csevegését. A fiókodból semmit sem mutat.", "widget_hint": "Kérdezz bármit", - "widget_speak": "Beszéd" + "widget_speak": "Beszéd", + "transcribed_by_fallback": "Átírta: %1$s — a csevegés saját beszédmodellje nem válaszolt.", + "read_by_fallback": "Felolvasta: %1$s — a csevegés saját beszédmodellje nem válaszolt." }, "it": { "about_version": "LLeMbas per Android %1$s", @@ -2388,7 +2398,9 @@ "wake_word_unavailable": "Non in questa build. La build F-Droid non ha un motore per la parola di attivazione, perché F-Droid compila ogni libreria dal sorgente; la build di llembas.eu ce l’ha.", "widget_description": "Chiedi a voce o per iscritto, o continua l’ultima chat dell’assistente. Non mostra nulla del tuo account.", "widget_hint": "Chiedi qualsiasi cosa", - "widget_speak": "Parla" + "widget_speak": "Parla", + "transcribed_by_fallback": "Trascritto da %1$s: il modello vocale proprio di questa chat non ha risposto.", + "read_by_fallback": "Letto da %1$s: il modello vocale proprio di questa chat non ha risposto." }, "pl": { "about_version": "LLeMbas na Androida %1$s", @@ -2786,7 +2798,9 @@ "wake_word_unavailable": "Nie w tej wersji. Wersja z F-Droid nie ma silnika słowa aktywującego, bo F-Droid buduje każdą bibliotekę ze źródeł; wersja z llembas.eu go ma.", "widget_description": "Pytaj głosem lub tekstem albo kontynuuj ostatni czat asystenta. Nie pokazuje niczego z Twojego konta.", "widget_hint": "Zapytaj o cokolwiek", - "widget_speak": "Mów" + "widget_speak": "Mów", + "transcribed_by_fallback": "Transkrybował %1$s: własny model mowy tego czatu nie odpowiedział.", + "read_by_fallback": "Przeczytał %1$s: własny model mowy tego czatu nie odpowiedział." }, "sk": { "about_version": "LLeMbas pre Android %1$s", @@ -3184,6 +3198,8 @@ "wake_word_unavailable": "V tomto zostavení nie je. Zostavenie pre F-Droid nemá modul pre budiace slovo, pretože F-Droid zostavuje každú knižnicu zo zdrojov; zostavenie z llembas.eu ho má.", "widget_description": "Pýtajte sa hlasom alebo textom, alebo pokračujte v poslednej konverzácii s asistentom. Neukazuje nič z vášho účtu.", "widget_hint": "Opýtajte sa na čokoľvek", - "widget_speak": "Hovoriť" + "widget_speak": "Hovoriť", + "transcribed_by_fallback": "Prepísal %1$s: vlastný model reči tohto chatu neodpovedal.", + "read_by_fallback": "Prečítal %1$s: vlastný model reči tohto chatu neodpovedal." } }