Files
attendi/Apps/Attendi/View Models/ContentViewModel.swift
T

148 lines
5.7 KiB
Swift
Raw Normal View History

import Foundation
import Observation
import OSLog
import Recording
import Speech
extension ContentView {
/// The observable model that drives ``ContentView``.
///
/// The model owns the recording and transcribing services attached to the recording feature, along with the ``locale`` the feature
/// transcribes in, picked in the view's toolbar from the supported ``locales`` that ``load()`` fetches. It also holds the transcription
/// currently presented in the view's modal sheet: ``received(_:)`` presents the transcription of a processed recording, and
/// ``dismissed()`` clears it when the sheet closes.
@MainActor
@Observable
final class Model {
// MARK: Properties
/// The locale of the spoken language to transcribe.
var locale: Locale
/// The transcription currently presented in the modal sheet, or `nil` when none is shown.
var transcription: Transcription?
/// The locales the transcriber supports, sorted by their localized names, or empty while ``load()`` has not finished yet.
private(set) var locales: [Locale]
/// The service that captures the audio from the device's microphone.
@ObservationIgnored
let capturer: AudioCapturing
/// The logger that records the failures of the speech model asset management.
@ObservationIgnored
private let logger = Logger(
subsystem: Bundle.main.bundleIdentifier ?? "Attendi",
category: "ContentView.Model"
)
/// The service that transcribes the recorded audio into text on device.
@ObservationIgnored
let transcriber: AudioTranscribing
// MARK: Initializers
/// Creates a model set to the user's current locale, with no supported locales loaded yet, attached to the on-device recording
/// and transcribing services.
init() {
self.locale = .current
self.locales = []
self.capturer = .init()
self.transcriber = .init()
}
// MARK: Methods
/// Loads the locales the transcriber supports into ``locales``, sorted by their localized names, and aligns ``locale`` with the
/// supported equivalent of its current value — falling back to the supported equivalent of a default locale when none exists —
/// so the locale picker starts with a valid selection.
func load() async {
locales = await SpeechTranscriber.supportedLocales.sorted {
name(for: $0).localizedStandardCompare(name(for: $1)) == .orderedAscending
}
if let equivalent = await SpeechTranscriber.supportedLocale(equivalentTo: locale) {
locale = equivalent
} else if let fallback = await SpeechTranscriber.supportedLocale(equivalentTo: .byDefault) {
locale = fallback
}
}
/// Preinstalls the speech model assets for the supported equivalent of ``locale``, so the first transcription in that locale
/// does not have to download them mid-processing.
///
/// The locale reservations of any other locales are released beforehand: the app transcribes a single locale at a time, and
/// the system only permits a limited number of reservations — exceeding it would make the installation request throw.
/// Failures are logged but not surfaced: the transcribing service installs any missing assets itself as a fallback when a
/// transcription starts.
func preinstallAssets() async {
guard let locale = await SpeechTranscriber.supportedLocale(
equivalentTo: locale
) else {
return
}
for reserved in await AssetInventory.reservedLocales where reserved != locale {
_ = await AssetInventory.release(reservedLocale: reserved)
}
let transcriber = SpeechTranscriber(
locale: locale,
preset: .transcription
)
do {
guard let request = try await AssetInventory.assetInstallationRequest(
supporting: [transcriber]
) else {
return
}
try await request.downloadAndInstall()
} catch {
logger.error("The speech model assets for the \"\(locale.identifier, privacy: .public)\" locale failed to preinstall: \(String(describing: error), privacy: .public)")
}
}
/// Returns the localized name of a locale for the locale picker.
///
/// - Parameter locale: The locale to name.
/// - Returns: The name of the locale in the user's current locale, or its identifier when no name is available.
func name(
for locale: Locale
) -> String {
Locale
.current
.localizedString(
forIdentifier: locale.identifier
)?.localizedCapitalized
?? locale.identifier
}
/// Handles the transcription of a processed recording, presenting it in the modal sheet.
///
/// - Parameter transcription: The transcription of the processed recording.
func received(
_ transcription: Transcription
) {
self.transcription = transcription
}
/// Handles the dismissal of the modal sheet.
func dismissed() {
transcription = nil
}
}
}
// MARK: - Constants
private extension Locale {
/// The locale to fall back to when the transcriber supports no equivalent of the user's current locale.
static let byDefault: Locale = .init(identifier: "en_US")
}