|
| 1 | +package expo.modules.t3voicetranscription |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import com.google.mlkit.genai.common.DownloadStatus |
| 5 | +import com.google.mlkit.genai.common.FeatureStatus |
| 6 | +import com.google.mlkit.genai.common.GenAiException |
| 7 | +import com.google.mlkit.genai.speechrecognition.SpeechRecognition |
| 8 | +import com.google.mlkit.genai.speechrecognition.SpeechRecognizerOptions |
| 9 | +import com.google.mlkit.genai.speechrecognition.SpeechRecognizerResponse |
| 10 | +import com.google.mlkit.genai.speechrecognition.speechRecognizerOptions |
| 11 | +import com.google.mlkit.genai.speechrecognition.speechRecognizerRequest |
| 12 | +import java.io.Closeable |
| 13 | +import java.util.Locale |
| 14 | +import kotlinx.coroutines.NonCancellable |
| 15 | +import kotlinx.coroutines.flow.Flow |
| 16 | +import kotlinx.coroutines.flow.first |
| 17 | +import kotlinx.coroutines.withContext |
| 18 | + |
| 19 | +internal class VoiceTranscriptionException( |
| 20 | + val code: String, |
| 21 | + message: String, |
| 22 | + cause: Throwable? = null |
| 23 | +) : Exception(message, cause) |
| 24 | + |
| 25 | +private val recognitionModes = listOf( |
| 26 | + SpeechRecognizerOptions.Mode.MODE_ADVANCED, |
| 27 | + SpeechRecognizerOptions.Mode.MODE_BASIC |
| 28 | +) |
| 29 | + |
| 30 | +internal suspend fun isGoogleVoiceTranscriptionSupported( |
| 31 | + createClient: (Int) -> GoogleSpeechClient |
| 32 | +): Boolean { |
| 33 | + for (mode in recognitionModes) { |
| 34 | + createClient(mode).use { client -> |
| 35 | + when (checkModelSupport(client)) { |
| 36 | + FeatureStatus.AVAILABLE, |
| 37 | + FeatureStatus.DOWNLOADABLE, |
| 38 | + FeatureStatus.DOWNLOADING -> return true |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return false |
| 43 | +} |
| 44 | + |
| 45 | +internal suspend fun prepareGoogleVoiceTranscription( |
| 46 | + createClient: (Int) -> GoogleSpeechClient |
| 47 | +): Int { |
| 48 | + for (mode in recognitionModes) { |
| 49 | + createClient(mode).use { client -> |
| 50 | + if (prepareModel(client)) return mode |
| 51 | + } |
| 52 | + } |
| 53 | + throw VoiceTranscriptionException( |
| 54 | + "unavailable", |
| 55 | + "On-device voice transcription is not available for this device language." |
| 56 | + ) |
| 57 | +} |
| 58 | + |
| 59 | +private suspend fun prepareModel(client: GoogleSpeechClient): Boolean = try { |
| 60 | + val status = client.checkStatus() |
| 61 | + if (status == FeatureStatus.UNAVAILABLE) { |
| 62 | + false |
| 63 | + } else { |
| 64 | + if (status == FeatureStatus.DOWNLOADABLE || |
| 65 | + status == FeatureStatus.DOWNLOADING |
| 66 | + ) { |
| 67 | + client.download() |
| 68 | + } |
| 69 | + when (client.checkStatus()) { |
| 70 | + FeatureStatus.UNAVAILABLE -> false |
| 71 | + FeatureStatus.AVAILABLE -> true |
| 72 | + else -> throw VoiceTranscriptionException( |
| 73 | + "preparation-failed", |
| 74 | + "Voice transcription could not prepare this language." |
| 75 | + ) |
| 76 | + } |
| 77 | + } |
| 78 | +} catch (error: GenAiException) { |
| 79 | + if (!isModelUnavailable(error)) throw error |
| 80 | + false |
| 81 | +} |
| 82 | + |
| 83 | +// Any probe failure for one mode means "try the next mode"; prepare surfaces the real error. |
| 84 | +private suspend fun checkModelSupport(client: GoogleSpeechClient): Int = try { |
| 85 | + client.checkStatus() |
| 86 | +} catch (_: GenAiException) { |
| 87 | + FeatureStatus.UNAVAILABLE |
| 88 | +} |
| 89 | + |
| 90 | +private fun isModelUnavailable(error: GenAiException): Boolean = when (error.errorCode) { |
| 91 | + GenAiException.ErrorCode.NOT_AVAILABLE, |
| 92 | + GenAiException.ErrorCode.NOT_SUPPORTED, |
| 93 | + GenAiException.ErrorCode.AICORE_INCOMPATIBLE, |
| 94 | + GenAiException.ErrorCode.NEEDS_SYSTEM_UPDATE -> true |
| 95 | + else -> false |
| 96 | +} |
| 97 | + |
| 98 | +internal suspend fun collectGoogleVoiceTranscript( |
| 99 | + responses: Flow<SpeechRecognizerResponse> |
| 100 | +): String { |
| 101 | + val text = StringBuilder() |
| 102 | + var partial = "" |
| 103 | + var completed = false |
| 104 | + responses.collect { response -> |
| 105 | + when (response) { |
| 106 | + // Separators between final utterances are supplied by the SDK. |
| 107 | + is SpeechRecognizerResponse.FinalTextResponse -> { |
| 108 | + text.append(response.text) |
| 109 | + partial = "" |
| 110 | + } |
| 111 | + is SpeechRecognizerResponse.PartialTextResponse -> partial = response.text |
| 112 | + is SpeechRecognizerResponse.ErrorResponse -> throw response.e |
| 113 | + is SpeechRecognizerResponse.CompletedResponse -> completed = true |
| 114 | + else -> Unit |
| 115 | + } |
| 116 | + } |
| 117 | + requireCompleteAudio(completed) { "Speech recognition did not complete the recording." } |
| 118 | + // Some sessions complete with a trailing partial instead of another final event. |
| 119 | + return text.append(partial).toString().trim() |
| 120 | +} |
| 121 | + |
| 122 | +internal interface GoogleSpeechClient : Closeable { |
| 123 | + suspend fun checkStatus(): Int |
| 124 | + suspend fun download() |
| 125 | +} |
| 126 | + |
| 127 | +internal class MlKitSpeechClient(context: Context, locale: Locale, mode: Int) : GoogleSpeechClient { |
| 128 | + private val context = context.applicationContext |
| 129 | + private val recognizer = SpeechRecognition.getClient( |
| 130 | + speechRecognizerOptions { |
| 131 | + this.locale = locale |
| 132 | + preferredMode = mode |
| 133 | + } |
| 134 | + ) |
| 135 | + |
| 136 | + override suspend fun checkStatus() = recognizer.checkStatus() |
| 137 | + |
| 138 | + override suspend fun download() { |
| 139 | + val result = recognizer.download().first { |
| 140 | + it is DownloadStatus.DownloadCompleted || it is DownloadStatus.DownloadFailed |
| 141 | + } |
| 142 | + if (result is DownloadStatus.DownloadFailed) throw result.e |
| 143 | + } |
| 144 | + |
| 145 | + suspend fun transcribe(uri: String): String = withRecordedPcm(context, uri) { pcm -> |
| 146 | + PcmPipe.open().use { pipe -> |
| 147 | + val request = speechRecognizerRequest { audioSource = pipe.source } |
| 148 | + try { |
| 149 | + collectGoogleVoiceTranscript( |
| 150 | + pacedRecordedResponses(pcm, pipe) { |
| 151 | + recognizer.startRecognition(request) |
| 152 | + } |
| 153 | + ) |
| 154 | + } finally { |
| 155 | + // Stop inference before closing the SDK-owned descriptor, including cancellation. |
| 156 | + withContext(NonCancellable) { runCatching { recognizer.stopRecognition() } } |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + override fun close() = recognizer.close() |
| 162 | +} |
0 commit comments