diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulator.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulator.kt index 33d559a10..b19d550ed 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulator.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulator.kt @@ -1,43 +1,154 @@ package com.yugahashimoto.andcode.feature.assistant -/** Keeps recognition segments together while Android rotates its speech session. */ -internal class SpeechTranscriptAccumulator { +/** + * Keeps recognition segments together while Android rotates its speech session. + * + * @param clock milliseconds on a monotonic clock, used to tell a pause from continuous speech + */ +internal class SpeechTranscriptAccumulator( + private val clock: () -> Long = { System.nanoTime() / 1_000_000 }, +) { private var value = "" + /** The latest partial result of the segment in progress, not yet part of [value]. */ + private var partial = "" + + /** [value] when the segment in progress began. */ + private var segmentStart = "" + + /** What this segment's earlier utterances added to [value], before its final result. */ + private var keptFromSegment = "" + + private var lastPartialAt: Long? = null + val text: String get() = value + /** + * Adds a segment's final result. Recognisers differ in what it holds after a pause: only the + * last utterance, or everything said in the segment. In the second case it replaces what + * [preview] kept from the segment, instead of repeating it. + */ fun append(segment: String) { - value = combine(value, segment) + val next = segment.trim() + value = + if (keptFromSegment.isNotEmpty() && normalized(next).startsWith(normalized(keptFromSegment))) { + combine(segmentStart, next) + } else { + combine(value, next) + } + startSegment() + } + + /** + * Ends the segment in progress. A segment cut short by a pause can end in "no match" or a + * timeout instead of a final result, leaving what was said only in its last partial result; + * that is kept here, or the next segment's partials would replace it. + */ + fun endSegment() { + value = combine(value, partial) + startSegment() + } + + /** + * The transcript so far plus [segment], the latest partial result. During long speech, and + * after a pause, some recognisers close an utterance internally without a final result and + * start the partials over: Google's on a Samsung phone sends an empty partial when speech + * resumes, then partials for the new utterance alone. The text before such a restart is kept + * here, or everything said before it would be lost. + */ + fun preview(segment: String): String { + val next = segment.trim() + if (next.isEmpty()) { + keepPartial() + return value + } + val now = clock() + val paused = lastPartialAt?.let { now - it >= PAUSE_MILLIS } ?: false + lastPartialAt = now + if (startedOver(partial, next, paused)) keepPartial() + partial = next + return combine(value, partial) + } + + /** Moves the utterance in progress into the transcript; its partials have stopped revising it. */ + private fun keepPartial() { + value = combine(value, partial) + keptFromSegment = combine(keptFromSegment, partial) + partial = "" } - fun preview(segment: String): String = combine(value, segment) + private fun startSegment() { + partial = "" + segmentStart = value + keptFromSegment = "" + lastPartialAt = null + } + + /** + * Whether [next] begins a new utterance instead of revising [previous]. A revision keeps the + * opening words. After a [paused] gap, any partial that does not is a new utterance. Without + * one, it must also be much shorter, and short partials are never treated as a restart, + * since recognisers often rewrite the first word or two while the speaker is still talking. + */ + private fun startedOver( + previous: String, + next: String, + paused: Boolean, + ): Boolean { + if (previous.isEmpty() || next.isEmpty()) return false + if (openingOf(previous) == openingOf(next)) return false + if (paused) return !normalized(next).startsWith(normalized(previous)) + return previous.length >= MIN_RESTART_CHARS && next.length * 2 <= previous.length + } + + private fun openingOf(text: String): String { + val words = text.lowercase().split(Regex("\\s+")).filter(String::isNotEmpty) + return if (words.size > 1) words.take(2).joinToString(" ") else text.lowercase().take(OPENING_CHARS) + } + + private fun normalized(text: String): String = text.lowercase().split(Regex("\\s+")).filter(String::isNotEmpty).joinToString(" ") private fun combine( prefix: String, segment: String, - ): String { - val next = segment.trim() - if (next.isEmpty()) return prefix - if (prefix.isEmpty()) return next - - val separator = - if (prefix.last().isWhitespace() || next.first().isWhitespace() || - prefix.last().isCjk() || next.first().isCjk() || - prefix.last() in NO_SPACE_BEFORE_PUNCTUATION || next.first() in OPENING_PUNCTUATION - ) { - "" - } else { - " " - } - return prefix + separator + next - } + ): String = joinSpeech(prefix, segment) + + internal companion object { + private const val MIN_RESTART_CHARS = 40 - private fun Char.isCjk(): Boolean = this in '\u3040'..'\u30ff' || this in '\u3400'..'\u4dbf' || this in '\u4e00'..'\u9fff' + /** Partials stop while the speaker is silent; a gap this long between two is a pause. */ + private const val PAUSE_MILLIS = 1_200L + private const val OPENING_CHARS = 4 - private companion object { - val NO_SPACE_BEFORE_PUNCTUATION = + private val NO_SPACE_BEFORE_PUNCTUATION = setOf('、', '。', ',', '.', ',', '.', '!', '?', '!', '?', ':', ';', ':', ';') - val OPENING_PUNCTUATION = setOf('(', '[', '{', '(', '「', '『', '【') + private val OPENING_PUNCTUATION = setOf('(', '[', '{', '(', '「', '『', '【') + + /** + * [prefix] followed by [segment], with a space between them where the language uses one. + * Also joins dictation to text already in the composer. + */ + fun joinSpeech( + prefix: String, + segment: String, + ): String { + val next = segment.trim() + if (next.isEmpty()) return prefix + if (prefix.isEmpty()) return next + + val separator = + if (prefix.last().isWhitespace() || next.first().isWhitespace() || + prefix.last().isCjk() || next.first().isCjk() || + prefix.last() in NO_SPACE_BEFORE_PUNCTUATION || next.first() in OPENING_PUNCTUATION + ) { + "" + } else { + " " + } + return prefix + separator + next + } + + private fun Char.isCjk(): Boolean = this in '\u3040'..'\u30ff' || this in '\u3400'..'\u4dbf' || this in '\u4e00'..'\u9fff' } } diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicy.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicy.kt index ec2fe3867..f00649c81 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicy.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicy.kt @@ -24,13 +24,28 @@ internal object VoiceDictationPolicy { /** How many silent segments in a row before silence is reported rather than retried. */ const val MAX_SILENT_SEGMENTS = 3 + /** + * With [keepListeningThroughPauses], how many silent segments in a row end dictation that has + * already heard something. Each one lasts until the recogniser's own silence timeout, so this + * is a pause of the better part of a minute, not a breath between sentences. + */ + const val MAX_PAUSE_SEGMENTS = 8 + + /** + * [keepListeningThroughPauses] is for chat dictation, which the user stops with the microphone + * button: a pause to think must not end it. The voice assistant leaves it off, so a pause + * after speaking still submits what was said. + */ fun outcomeFor( code: Int?, hasTranscript: Boolean, consecutiveFailures: Int, + keepListeningThroughPauses: Boolean = false, ): VoiceDictationOutcome = when { !isTransient(code) -> VoiceDictationOutcome.REPORT + hasTranscript && !keepListeningThroughPauses -> VoiceDictationOutcome.FINISH + hasTranscript && consecutiveFailures < MAX_PAUSE_SEGMENTS -> VoiceDictationOutcome.RESTART hasTranscript -> VoiceDictationOutcome.FINISH consecutiveFailures < MAX_SILENT_SEGMENTS -> VoiceDictationOutcome.RESTART else -> VoiceDictationOutcome.REPORT diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt index e6b580bdf..c5e1a8520 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt @@ -159,6 +159,7 @@ import com.yugahashimoto.andcode.core.diagnostics.StallDiagnosis import com.yugahashimoto.andcode.core.diagnostics.StallReason import com.yugahashimoto.andcode.core.diagnostics.explain import com.yugahashimoto.andcode.core.diagnostics.supportingDetail +import com.yugahashimoto.andcode.feature.assistant.SpeechTranscriptAccumulator import com.yugahashimoto.andcode.feature.browser.PreviewTarget import com.yugahashimoto.andcode.feature.browser.PreviewUiState import com.yugahashimoto.andcode.feature.workspace.GitHubAutoAttachChips @@ -408,9 +409,17 @@ fun ChatHomeScreen( if (totalItems > 0 && isAtBottom.value) listState.animateScrollToItem(totalItems - 1) } + // Dictation adds to what is already in the box (typed, or dictated before the microphone was + // stopped and started again) instead of replacing it. + val dictating = state.isListening || state.isSpeechProcessing + var textBeforeDictation by remember { mutableStateOf("") } + LaunchedEffect(dictating) { + if (dictating) textBeforeDictation = inputValue.text + } LaunchedEffect(state.partialText) { - if ((state.isListening || state.isSpeechProcessing) && state.partialText.isNotBlank()) { - inputValue = TextFieldValue(state.partialText, TextRange(state.partialText.length)) + if (dictating && state.partialText.isNotBlank()) { + val text = SpeechTranscriptAccumulator.joinSpeech(textBeforeDictation, state.partialText) + inputValue = TextFieldValue(text, TextRange(text.length)) } } diff --git a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt index 6251219b6..44dbfafc3 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt @@ -518,11 +518,13 @@ fun AndCodeApp( } is SpeechResult.Error -> { silentSegments += 1 + transcript.endSegment() outcome = VoiceDictationPolicy.outcomeFor( code = result.code, hasTranscript = transcript.text.isNotBlank(), consecutiveFailures = silentSegments, + keepListeningThroughPauses = true, ) if (outcome == VoiceDictationOutcome.REPORT) { chatViewModel.reportSpeechError(result.message) @@ -530,6 +532,7 @@ fun AndCodeApp( } } } + transcript.endSegment() if (outcome != VoiceDictationOutcome.RESTART) break delay(VOICE_RESTART_DELAY_MS) chatViewModel.startListening() diff --git a/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulatorTest.kt b/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulatorTest.kt index 591a8cce1..754254a49 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulatorTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/SpeechTranscriptAccumulatorTest.kt @@ -23,4 +23,143 @@ class SpeechTranscriptAccumulatorTest { assertEquals("hello world", accumulator.text) } + + @Test + fun `keeps speech from before the recogniser started its partials over`() { + val accumulator = SpeechTranscriptAccumulator() + val first = "so the first thing I want to explain is how the handoff tool moves projects" + + accumulator.preview("so the first thing") + accumulator.preview(first) + val restarted = accumulator.preview("between devices") + accumulator.append("between devices without losing work") + + assertEquals("$first between devices", restarted) + assertEquals("$first between devices without losing work", accumulator.text) + } + + @Test + fun `a revised partial replaces the previous one instead of adding to it`() { + val accumulator = SpeechTranscriptAccumulator() + + accumulator.preview("the quick brown fox jumps over the lazy dog near the river") + val revised = accumulator.preview("the quick brown fox jumped over the lazy dog by the river") + accumulator.append("the quick brown fox jumped over the lazy dog by the river bank") + + assertEquals("the quick brown fox jumped over the lazy dog by the river", revised) + assertEquals("the quick brown fox jumped over the lazy dog by the river bank", accumulator.text) + } + + @Test + fun `a rewritten first word in a short partial is not mistaken for a restart`() { + val accumulator = SpeechTranscriptAccumulator() + + accumulator.preview("I want") + accumulator.preview("Hi") + accumulator.append("Hi there") + + assertEquals("Hi there", accumulator.text) + } + + @Test + fun `speech heard only as a partial survives the end of its segment`() { + val accumulator = SpeechTranscriptAccumulator() + + accumulator.preview("first thought") + accumulator.endSegment() + val next = accumulator.preview("second") + + assertEquals("first thought second", next) + accumulator.append("second thought") + assertEquals("first thought second thought", accumulator.text) + } + + @Test + fun `ending a segment after its final result adds nothing twice`() { + val accumulator = SpeechTranscriptAccumulator() + + accumulator.preview("hello wor") + accumulator.append("hello world") + accumulator.endSegment() + accumulator.endSegment() + + assertEquals("hello world", accumulator.text) + } + + private class FakeClock { + var now = 0L + + fun at(millis: Long): FakeClock = apply { now = millis } + } + + @Test + fun `speech after a pause in the same segment is added, not swapped in`() { + val clock = FakeClock() + val accumulator = SpeechTranscriptAccumulator { clock.now } + + clock.at(0) + accumulator.preview("hello there") + clock.at(300) + accumulator.preview("hello there friend") + clock.at(3_000) + val afterPause = accumulator.preview("and") + clock.at(3_300) + accumulator.preview("and more") + accumulator.append("and more stuff") + + assertEquals("hello there friend and", afterPause) + assertEquals("hello there friend and more stuff", accumulator.text) + } + + @Test + fun `a final result that repeats the whole segment is not added twice`() { + val clock = FakeClock() + val accumulator = SpeechTranscriptAccumulator { clock.now } + + clock.at(0) + accumulator.preview("hello there friend") + clock.at(3_000) + accumulator.preview("and more") + accumulator.append("Hello there friend and more stuff") + + assertEquals("Hello there friend and more stuff", accumulator.text) + } + + @Test + fun `a pause before a revision of the same words is not a new utterance`() { + val clock = FakeClock() + val accumulator = SpeechTranscriptAccumulator { clock.now } + + clock.at(0) + accumulator.preview("hello there") + clock.at(2_000) + val revised = accumulator.preview("hello there friend") + + assertEquals("hello there friend", revised) + } + + @Test + fun `an empty partial when speech resumes keeps the utterance before it`() { + // Recorded from Google's recogniser on a Samsung phone: after a pause it reports the end and + // start of speech, sends an empty partial, then partials for the new utterance alone. + val accumulator = SpeechTranscriptAccumulator() + + accumulator.preview("") + accumulator.preview("so this is a test to check if the listening module can write") + accumulator.preview("") + accumulator.preview(" sentences") + val shown = accumulator.preview(" sentences continuously") + accumulator.endSegment() + + assertEquals("so this is a test to check if the listening module can write sentences continuously", shown) + assertEquals(shown, accumulator.text) + } + + @Test + fun `dictation joins text already in the composer`() { + assertEquals("typed first said next", SpeechTranscriptAccumulator.joinSpeech("typed first", " said next")) + assertEquals("typed first\nsaid next", SpeechTranscriptAccumulator.joinSpeech("typed first\n", "said next")) + assertEquals("said next", SpeechTranscriptAccumulator.joinSpeech("", "said next")) + assertEquals("前半後半", SpeechTranscriptAccumulator.joinSpeech("前半", "後半")) + } } diff --git a/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicyTest.kt b/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicyTest.kt index 8dbd8c9c8..8fa763c75 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicyTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/feature/assistant/VoiceDictationPolicyTest.kt @@ -93,4 +93,30 @@ class VoiceDictationPolicyTest { VoiceDictationPolicy.outcomeFor(code = null, hasTranscript = false, consecutiveFailures = 1), ) } + + @Test + fun `chat dictation keeps listening through a pause after speech`() { + assertEquals( + VoiceDictationOutcome.RESTART, + VoiceDictationPolicy.outcomeFor( + code = SpeechRecognizer.ERROR_SPEECH_TIMEOUT, + hasTranscript = true, + consecutiveFailures = 1, + keepListeningThroughPauses = true, + ), + ) + } + + @Test + fun `chat dictation ends quietly after a very long pause`() { + assertEquals( + VoiceDictationOutcome.FINISH, + VoiceDictationPolicy.outcomeFor( + code = SpeechRecognizer.ERROR_NO_MATCH, + hasTranscript = true, + consecutiveFailures = VoiceDictationPolicy.MAX_PAUSE_SEGMENTS, + keepListeningThroughPauses = true, + ), + ) + } }