Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

On first transcribe download the model before starting recording

laurenspriem44e392aec0f1
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
index 8c20a132f8..1ac7457b30 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
@@ -77,16 +77,39 @@ fun ChatView(
var inputBarHeightDp by remember { mutableStateOf(0.dp) }
val latestMessageText by rememberUpdatedState(chatState.messageText)
val latestOnMessageChange by rememberUpdatedState(onMessageChange)
+ val sessionKey = chatState.currentSessionId ?: "new-session"
+ val latestSessionKey by rememberUpdatedState(sessionKey)
+ var pendingVoiceSessionKey by remember { mutableStateOf<String?>(null) }
val voiceController = rememberVoiceTranscriptionController(
onTranscript = { transcript ->
latestOnMessageChange(appendVoiceTranscript(latestMessageText, transcript))
}
)
+
+ val editingMessage by remember(chatState.editingMessageId, chatState.messages) {
+ derivedStateOf {
+ chatState.editingMessageId?.let { editingId ->
+ chatState.messages.firstOrNull { it.id == editingId }
+ }
+ }
+ }
+ val canStartVoiceInput = !chatState.isGenerating &&
+ !chatState.isDownloading &&
+ !chatState.isAttachmentDownloadBlocked &&
+ editingMessage == null
+ val latestCanStartVoiceInput by rememberUpdatedState(canStartVoiceInput)
+
val microphonePermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { granted ->
+ val requestedSessionKey = pendingVoiceSessionKey
+ pendingVoiceSessionKey = null
if (granted) {
- voiceController.startRecording()
+ if (requestedSessionKey != null) {
+ voiceController.startRecording {
+ latestSessionKey == requestedSessionKey && latestCanStartVoiceInput
+ }
+ }
} else {
voiceController.onPermissionDenied()
}
@@ -142,14 +165,9 @@ fun ChatView(
}
}
- val sessionKey = chatState.currentSessionId ?: "new-session"
-
- val editingMessage by remember(chatState.editingMessageId, chatState.messages) {
- derivedStateOf {
- chatState.editingMessageId?.let { editingId ->
- chatState.messages.firstOrNull { it.id == editingId }
- }
- }
+ LaunchedEffect(sessionKey) {
+ pendingVoiceSessionKey = null
+ voiceController.cancelActiveVoiceInput()
}
Box(modifier = Modifier.fillMaxSize()) {
@@ -241,15 +259,20 @@ fun ChatView(
onVoiceInput = {
if (voiceController.state.isRecording) {
voiceController.stopAndTranscribe()
- } else if (
- ContextCompat.checkSelfPermission(
+ } else {
+ val hasMicrophonePermission = ContextCompat.checkSelfPermission(
context,
Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED
- ) {
- voiceController.startRecording()
- } else {
- microphonePermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
+ if (canStartVoiceInput && hasMicrophonePermission) {
+ val requestedSessionKey = sessionKey
+ voiceController.startRecording {
+ latestSessionKey == requestedSessionKey && latestCanStartVoiceInput
+ }
+ } else if (canStartVoiceInput) {
+ pendingVoiceSessionKey = sessionKey
+ microphonePermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
+ }
}
},
focusRequestId = focusRequestId
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatVoiceInput.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatVoiceInput.kt
index 114e4b7e64..9cc7cb35f0 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatVoiceInput.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatVoiceInput.kt
@@ -101,6 +101,7 @@ internal class VoiceTranscriptionController(
private val modelsDir = appContext.getDir("ensu_transcription_models", Context.MODE_PRIVATE)
private var audioRecord: AudioRecord? = null
+ private var preparingRecordingJob: Job? = null
private var recordingJob: Job? = null
private var transientErrorJob: Job? = null
private var recordedPcm = ByteArrayOutputStream()
@@ -114,12 +115,44 @@ internal class VoiceTranscriptionController(
}
@SuppressLint("MissingPermission")
- fun startRecording() {
+ fun startRecording(canStartRecording: () -> Boolean = { true }) {
transientErrorJob?.cancel()
- if (state is VoiceInputState.Recording ||
- state is VoiceInputState.Downloading ||
- state is VoiceInputState.Transcribing
- ) {
+ if (state.isWorking || preparingRecordingJob?.isActive == true) {
+ return
+ }
+
+ preparingRecordingJob = scope.launch {
+ try {
+ ensureTranscriptionModelDownloaded()
+ if (!isActive || !canStartRecording()) {
+ if (state is VoiceInputState.Downloading) {
+ state = VoiceInputState.Idle
+ }
+ return@launch
+ }
+ beginRecording()
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: UnsatisfiedLinkError) {
+ Log.w(TAG, "Voice transcription is not available on this device", error)
+ state = VoiceInputState.Error("Voice transcription is not available on this device.")
+ } catch (error: TranscriptionException) {
+ Log.w(TAG, "Voice model preparation failed: ${error.message}", error)
+ state = VoiceInputState.Error(transcriptionErrorMessage(error.message))
+ } catch (error: Throwable) {
+ Log.w(
+ TAG,
+ "Voice model preparation failed: ${error.javaClass.simpleName}: ${error.message}",
+ error
+ )
+ state = VoiceInputState.Error(transcriptionErrorMessage(error.message))
+ }
+ }
+ }
+
+ @SuppressLint("MissingPermission")
+ private fun beginRecording() {
+ if (state is VoiceInputState.Recording || state is VoiceInputState.Transcribing) {
return
}
@@ -177,6 +210,8 @@ internal class VoiceTranscriptionController(
}
state = VoiceInputState.Transcribing
+ preparingRecordingJob?.cancel()
+ preparingRecordingJob = null
scope.launch {
recordingJob?.cancelAndJoin()
recordingJob = null
@@ -192,7 +227,14 @@ internal class VoiceTranscriptionController(
}
fun cancelActiveVoiceInput() {
+ val wasPreparingRecording = preparingRecordingJob?.isActive == true
+ preparingRecordingJob?.cancel()
+ preparingRecordingJob = null
+
if (state !is VoiceInputState.Recording) {
+ if (wasPreparingRecording && state is VoiceInputState.Downloading) {
+ state = VoiceInputState.Idle
+ }
return
}
@@ -207,6 +249,7 @@ internal class VoiceTranscriptionController(
fun dispose() {
transientErrorJob?.cancel()
+ preparingRecordingJob?.cancel()
scope.cancel()
runCatching {
audioRecord?.release()
@@ -216,48 +259,10 @@ internal class VoiceTranscriptionController(
private suspend fun transcribeRecording(pcm: ByteArray, sampleRate: Int) {
try {
+ ensureTranscriptionModelDownloaded()
val transcript = withContext(Dispatchers.IO) {
uniffiEnsureInitialized()
- if (!isTranscriptionModelDownloaded(modelsDir.absolutePath)) {
- withContext(Dispatchers.Main.immediate) {
- state = VoiceInputState.Downloading(null)
- }
- downloadTranscriptionModel(
- modelsDir.absolutePath,
- object : TranscriptionModelEventCallback {
- override fun onEvent(event: TranscriptionModelEvent) {
- when (event) {
- is TranscriptionModelEvent.DownloadProgress -> {
- val percent = event.percentage
- .roundToInt()
- .coerceIn(0, 100)
- scope.launch(Dispatchers.Main.immediate) {
- state = VoiceInputState.Downloading(percent)
- }
- }
- TranscriptionModelEvent.ExtractionStarted -> {
- scope.launch(Dispatchers.Main.immediate) {
- state = VoiceInputState.Downloading(100)
- }
- }
- TranscriptionModelEvent.ExtractionCompleted,
- TranscriptionModelEvent.DownloadComplete -> Unit
- is TranscriptionModelEvent.DownloadError -> {
- Log.w(
- TAG,
- "Voice model download failed: ${event.message}"
- )
- scope.launch(Dispatchers.Main.immediate) {
- state = VoiceInputState.Error(downloadErrorMessage())
- }
- }
- }
- }
- }
- )
- }
-
withContext(Dispatchers.Main.immediate) {
state = VoiceInputState.Transcribing
}
@@ -293,6 +298,77 @@ internal class VoiceTranscriptionController(
}
}
+ private suspend fun ensureTranscriptionModelDownloaded() {
+ withContext(Dispatchers.IO) {
+ val activeJob = coroutineContext[Job]
+ uniffiEnsureInitialized()
+
+ if (isTranscriptionModelDownloaded(modelsDir.absolutePath)) {
+ return@withContext
+ }
+
+ setStateIfJobActive(activeJob, VoiceInputState.Downloading(null))
+ downloadTranscriptionModel(
+ modelsDir.absolutePath,
+ object : TranscriptionModelEventCallback {
+ override fun onEvent(event: TranscriptionModelEvent) {
+ when (event) {
+ is TranscriptionModelEvent.DownloadProgress -> {
+ val percent = event.percentage
+ .roundToInt()
+ .coerceIn(0, 100)
+ postStateIfJobActive(
+ activeJob,
+ VoiceInputState.Downloading(percent)
+ )
+ }
+ TranscriptionModelEvent.ExtractionStarted -> {
+ postStateIfJobActive(
+ activeJob,
+ VoiceInputState.Downloading(100)
+ )
+ }
+ TranscriptionModelEvent.ExtractionCompleted,
+ TranscriptionModelEvent.DownloadComplete -> Unit
+ is TranscriptionModelEvent.DownloadError -> {
+ Log.w(
+ TAG,
+ "Voice model download failed: ${event.message}"
+ )
+ postStateIfJobActive(
+ activeJob,
+ VoiceInputState.Error(downloadErrorMessage())
+ )
+ }
+ }
+ }
+ }
+ )
+ }
+ }
+
+ private suspend fun setStateIfJobActive(activeJob: Job?, nextState: VoiceInputState) {
+ if (activeJob?.isActive == false) {
+ return
+ }
+ withContext(Dispatchers.Main.immediate) {
+ if (activeJob?.isActive != false) {
+ state = nextState
+ }
+ }
+ }
+
+ private fun postStateIfJobActive(activeJob: Job?, nextState: VoiceInputState) {
+ if (activeJob?.isActive == false) {
+ return
+ }
+ scope.launch(Dispatchers.Main.immediate) {
+ if (activeJob?.isActive != false) {
+ state = nextState
+ }
+ }
+ }
+
private fun stopActiveRecorder() {
val recorder = audioRecord ?: return
runCatching {
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj b/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
index fd0ddb7db8..3e3bb11d38 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
+++ b/mobile/native/darwin/Apps/Ensu/Ensu.xcodeproj/project.pbxproj
@@ -35,7 +35,6 @@
DA01087C2E682336006E79AE /* Exceptions for "Ensu" folder in "Ensu" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
- Ensu.entitlements,
Info.plist,
);
target = DA72BC602E5F87A000D128FF /* Ensu */;
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
index 3fb482b3ff..44bce41097 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift
@@ -1038,9 +1038,20 @@ final class ChatViewModel: ObservableObject {
return
}
- voiceTranscriber.startRecording { [weak self] state in
- self?.setVoiceInputState(state)
- }
+ let voiceSessionId = currentSessionId
+ voiceTranscriber.startRecording(
+ onState: { [weak self] state in
+ self?.setVoiceInputState(state)
+ },
+ shouldStartRecording: { [weak self] in
+ guard let self else { return false }
+ return self.currentSessionId == voiceSessionId &&
+ !self.isGenerating &&
+ !self.isDownloading &&
+ !self.isAttachmentDownloadBlocked &&
+ self.editingMessageId == nil
+ }
+ )
}
func cancelVoiceInput() {
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/VoiceTranscriptionService.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/VoiceTranscriptionService.swift
index 2710401028..c1cb954c27 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/VoiceTranscriptionService.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/VoiceTranscriptionService.swift
@@ -87,6 +87,8 @@ final class VoiceTranscriptionService {
private let modelsDir: URL
private var transcriptionTask: Task<Void, Never>?
+ private var activeVoiceTaskId = UUID()
+ private var activeDownloadId: UUID?
#if os(iOS)
private let recorder = PcmAudioRecorder()
@@ -97,15 +99,17 @@ final class VoiceTranscriptionService {
try? FileManager.default.createDirectory(at: modelsDir, withIntermediateDirectories: true, attributes: nil)
}
- func startRecording(onState: @escaping StateHandler) {
+ func startRecording(
+ onState: @escaping StateHandler,
+ shouldStartRecording: @escaping @MainActor @Sendable () -> Bool = { true }
+ ) {
#if os(iOS)
guard !recorder.isRecording else { return }
- transcriptionTask?.cancel()
let session = AVAudioSession.sharedInstance()
switch session.recordPermission {
case .granted:
- beginRecording(onState: onState)
+ prepareModelAndStartRecording(onState: onState, shouldStartRecording: shouldStartRecording)
case .denied:
onState(.error("Microphone permission is required for voice input."))
case .undetermined:
@@ -113,7 +117,10 @@ final class VoiceTranscriptionService {
Task { @MainActor in
guard let self else { return }
if granted {
- self.beginRecording(onState: onState)
+ self.prepareModelAndStartRecording(
+ onState: onState,
+ shouldStartRecording: shouldStartRecording
+ )
} else {
onState(.error("Microphone permission is required for voice input."))
}
@@ -141,43 +148,37 @@ final class VoiceTranscriptionService {
return
}
- transcriptionTask?.cancel()
+ let taskId = beginVoiceTask()
+ let downloadId = beginDownload(taskId: taskId)
+ let downloadCallback = transcriptionDownloadCallback(
+ taskId: taskId,
+ downloadId: downloadId,
+ onState: onState
+ )
let modelsDirPath = modelsDir.path
let sampleRate = recording.sampleRate
let pcm = recording.pcm
- transcriptionTask = Task.detached(priority: .userInitiated) {
+ transcriptionTask = Task.detached(priority: .userInitiated) { [weak self] in
do {
uniffiEnsureTranscriptionInitialized()
if !isTranscriptionModelDownloaded(modelsDir: modelsDirPath) {
- await MainActor.run {
+ await MainActor.run { [weak self] in
+ guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else { return }
onState(.downloading(percent: nil))
}
- let callback = TranscriptionProgressCallback { event in
- switch event {
- case let .downloadProgress(downloaded: _, total: _, percentage: percentage):
- let percent = min(max(Int(percentage.rounded()), 0), 100)
- Task { @MainActor in
- onState(.downloading(percent: percent))
- }
- case .extractionStarted:
- Task { @MainActor in
- onState(.downloading(percent: 100))
- }
- case .extractionCompleted, .downloadComplete:
- break
- case .downloadError:
- Task { @MainActor in
- onState(.error("Voice model download failed."))
- }
- }
- }
- _ = try downloadTranscriptionModel(modelsDir: modelsDirPath, callback: callback)
+ _ = try downloadTranscriptionModel(modelsDir: modelsDirPath, callback: downloadCallback)
}
if Task.isCancelled { return }
- await MainActor.run {
+ let isActive = await MainActor.run { [weak self] in
+ self?.finishDownload(downloadId: downloadId)
+ return self?.isVoiceTaskActive(taskId) == true
+ }
+ guard isActive else { return }
+ await MainActor.run { [weak self] in
+ guard self?.isVoiceTaskActive(taskId) == true else { return }
onState(.transcribing)
}
let transcript = try transcribePcm16(
@@ -189,7 +190,8 @@ final class VoiceTranscriptionService {
.trimmingCharacters(in: .whitespacesAndNewlines)
if Task.isCancelled { return }
- await MainActor.run {
+ await MainActor.run { [weak self] in
+ guard self?.isVoiceTaskActive(taskId) == true else { return }
if transcript.isEmpty {
onState(.error("No speech detected."))
} else {
@@ -200,7 +202,9 @@ final class VoiceTranscriptionService {
} catch is CancellationError {
return
} catch {
- await MainActor.run {
+ await MainActor.run { [weak self] in
+ self?.finishDownload(downloadId: downloadId)
+ guard self?.isVoiceTaskActive(taskId) == true else { return }
onState(.error("Could not transcribe voice input."))
}
}
@@ -213,6 +217,8 @@ final class VoiceTranscriptionService {
func cancel() {
transcriptionTask?.cancel()
transcriptionTask = nil
+ activeVoiceTaskId = UUID()
+ activeDownloadId = nil
#if os(iOS)
if recorder.isRecording {
_ = recorder.stop()
@@ -221,6 +227,112 @@ final class VoiceTranscriptionService {
}
#if os(iOS)
+ private func prepareModelAndStartRecording(
+ onState: @escaping StateHandler,
+ shouldStartRecording: @escaping @MainActor @Sendable () -> Bool
+ ) {
+ let taskId = beginVoiceTask()
+ let downloadId = beginDownload(taskId: taskId)
+ let downloadCallback = transcriptionDownloadCallback(
+ taskId: taskId,
+ downloadId: downloadId,
+ onState: onState
+ )
+ let modelsDirPath = modelsDir.path
+
+ transcriptionTask = Task.detached(priority: .userInitiated) { [weak self] in
+ do {
+ uniffiEnsureTranscriptionInitialized()
+
+ if !isTranscriptionModelDownloaded(modelsDir: modelsDirPath) {
+ await MainActor.run { [weak self] in
+ guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else { return }
+ onState(.downloading(percent: nil))
+ }
+ _ = try downloadTranscriptionModel(modelsDir: modelsDirPath, callback: downloadCallback)
+ }
+
+ if Task.isCancelled { return }
+ await MainActor.run { [weak self] in
+ self?.finishDownload(downloadId: downloadId)
+ guard let self, self.isVoiceTaskActive(taskId) else { return }
+ guard shouldStartRecording() else {
+ onState(.idle)
+ return
+ }
+ self.beginRecording(onState: onState)
+ }
+ } catch is CancellationError {
+ return
+ } catch {
+ await MainActor.run { [weak self] in
+ self?.finishDownload(downloadId: downloadId)
+ guard self?.isVoiceTaskActive(taskId) == true else { return }
+ onState(.error("Voice model download failed."))
+ }
+ }
+ }
+ }
+
+ private func beginVoiceTask() -> UUID {
+ transcriptionTask?.cancel()
+ let taskId = UUID()
+ activeVoiceTaskId = taskId
+ activeDownloadId = nil
+ return taskId
+ }
+
+ private func isVoiceTaskActive(_ taskId: UUID) -> Bool {
+ activeVoiceTaskId == taskId
+ }
+
+ private func beginDownload(taskId: UUID) -> UUID {
+ let downloadId = UUID()
+ if isVoiceTaskActive(taskId) {
+ activeDownloadId = downloadId
+ }
+ return downloadId
+ }
+
+ private func finishDownload(downloadId: UUID) {
+ if activeDownloadId == downloadId {
+ activeDownloadId = nil
+ }
+ }
+
+ private func isDownloadActive(taskId: UUID, downloadId: UUID) -> Bool {
+ isVoiceTaskActive(taskId) && activeDownloadId == downloadId
+ }
+
+ private func transcriptionDownloadCallback(
+ taskId: UUID,
+ downloadId: UUID,
+ onState: @escaping StateHandler
+ ) -> TranscriptionProgressCallback {
+ TranscriptionProgressCallback { [weak self] event in
+ switch event {
+ case let .downloadProgress(downloaded: _, total: _, percentage: percentage):
+ let percent = min(max(Int(percentage.rounded()), 0), 100)
+ Task { @MainActor [weak self] in
+ guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else { return }
+ onState(.downloading(percent: percent))
+ }
+ case .extractionStarted:
+ Task { @MainActor [weak self] in
+ guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else { return }
+ onState(.downloading(percent: 100))
+ }
+ case .extractionCompleted, .downloadComplete:
+ break
+ case .downloadError:
+ Task { @MainActor [weak self] in
+ guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else { return }
+ onState(.error("Voice model download failed."))
+ }
+ }
+ }
+ }
+
private func beginRecording(onState: @escaping StateHandler) {
do {
try recorder.start()