Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Chat/Dictation.swift10// Module : Chat11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Observation90#if canImport(Speech) && os(iOS)91import Speech92import AVFoundation9394/// Live dictation with the system speech recogniser. Recognition is kept on the device whenever the recogniser for the95/// current language supports it, and the UI states which of the two is happening.96@MainActor @Observable final class Dictation {97 private(set) var isRecording = false98 private(set) var transcript = ""99 private(set) var onDevice = false100 private(set) var prefix = ""101 private var recognizer: SFSpeechRecognizer?102 private var request: SFSpeechAudioBufferRecognitionRequest?103 private var recognitionTask: SFSpeechRecognitionTask?104 private let audio = AVAudioEngine()105106 var isAvailable: Bool { SFSpeechRecognizer(locale: Locale.current) != nil || SFSpeechRecognizer() != nil }107108 /// Starts listening. Returns a message when it cannot (permission refused, recogniser unavailable).109 func start(prefix: String) async -> String? {110 guard !isRecording else { return nil }111 let speech = await withCheckedContinuation { (c: CheckedContinuation<SFSpeechRecognizerAuthorizationStatus, Never>) in112 SFSpeechRecognizer.requestAuthorization { c.resume(returning: $0) }113 }114 guard speech == .authorized else { return "Speech recognition is turned off for ORIX Astra. You can allow it in Settings." }115 let mic = await AVAudioApplication.requestRecordPermission()116 guard mic else { return "Microphone access is turned off for ORIX Astra. You can allow it in Settings." }117 guard let recognizer = SFSpeechRecognizer(locale: Locale.current) ?? SFSpeechRecognizer(), recognizer.isAvailable else {118 return "Dictation is not available right now for this language."119 }120 self.recognizer = recognizer121 let request = SFSpeechAudioBufferRecognitionRequest()122 request.shouldReportPartialResults = true123 onDevice = recognizer.supportsOnDeviceRecognition124 request.requiresOnDeviceRecognition = onDevice125 self.request = request126 do {127 let session = AVAudioSession.sharedInstance()128 try session.setCategory(.record, mode: .measurement, options: .duckOthers)129 try session.setActive(true, options: .notifyOthersOnDeactivation)130 let input = audio.inputNode131 let format = input.outputFormat(forBus: 0)132 guard format.sampleRate > 0, format.channelCount > 0 else { return "No microphone input is available." }133 input.removeTap(onBus: 0)134 input.installTap(onBus: 0, bufferSize: 1024, format: format) { buffer, _ in request.append(buffer) }135 audio.prepare()136 try audio.start()137 } catch {138 cleanup()139 return "The microphone could not be started."140 }141 self.prefix = prefix.isEmpty || prefix.hasSuffix(" ") || prefix.hasSuffix("\n") ? prefix : prefix + " "142 transcript = ""; isRecording = true143 recognitionTask = recognizer.recognitionTask(with: request) { [weak self] result, error in144 let text = result?.bestTranscription.formattedString145 let finished = result?.isFinal ?? false || error != nil146 Task { @MainActor in147 guard let self else { return }148 if let text { self.transcript = text }149 if finished { self.stop() }150 }151 }152 return nil153 }154155 func stop() {156 guard isRecording else { return }157 isRecording = false158 cleanup()159 }160161 private func cleanup() {162 if audio.isRunning { audio.stop() }163 audio.inputNode.removeTap(onBus: 0)164 request?.endAudio(); request = nil165 recognitionTask?.cancel(); recognitionTask = nil166 try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)167 }168}169#else170@MainActor @Observable final class Dictation {171 private(set) var isRecording = false172 private(set) var transcript = ""173 private(set) var onDevice = false174 private(set) var prefix = ""175 var isAvailable: Bool { false }176 func start(prefix: String) async -> String? { "Dictation is not available on this platform." }177 func stop() {}178}179#endif180