Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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'
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
}
}

Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -518,18 +518,21 @@ 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)
}
}
}
}
transcript.endSegment()
if (outcome != VoiceDictationOutcome.RESTART) break
delay(VOICE_RESTART_DELAY_MS)
chatViewModel.startListening()
Expand Down
Loading