Repository Public License
1//2// ORIX Audio3// File: ORIXAudio/Services/ProcessingCenter.swift4// Description: Runs and tracks analysis, transcription and notes jobs per recording, with progress and cancellation.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Foundation10import Observation11import ORIXAudioCore12import SwiftData1314@MainActor @Observable15final class ProcessingCenter {16 enum JobKind: String { case analysis, transcription, notes, modelDownload }17 struct Job: Identifiable {18 var id: String { "\(recordingID)-\(kind.rawValue)" }19 var recordingID: UUID20 var kind: JobKind21 var progress: Double22 var task: Task<Void, Never>?23 }2425 private(set) var jobs: [String: Job] = [:]26 private(set) var errors: [UUID: String] = [:]27 /// Bumped whenever a sidecar file changes, so views reload it.28 private(set) var revision = 029 private let context: ModelContext3031 init(context: ModelContext) { self.context = context }3233 func job(_ id: UUID, _ kind: JobKind) -> Job? { jobs["\(id)-\(kind.rawValue)"] }34 func isRunning(_ id: UUID, _ kind: JobKind) -> Bool { job(id, kind) != nil }35 func clearError(_ id: UUID) { errors[id] = nil }3637 func cancel(_ id: UUID, _ kind: JobKind) {38 jobs["\(id)-\(kind.rawValue)"]?.task?.cancel()39 }4041 private func setProgress(_ id: UUID, _ kind: JobKind, _ p: Double) {42 let key = "\(id)-\(kind.rawValue)"43 if jobs[key] != nil { jobs[key]?.progress = p }44 }4546 private func begin(_ id: UUID, _ kind: JobKind) -> Bool {47 let key = "\(id)-\(kind.rawValue)"48 guard jobs[key] == nil else { return false }49 jobs[key] = Job(recordingID: id, kind: kind, progress: 0)50 errors[id] = nil51 return true52 }5354 private func end(_ id: UUID, _ kind: JobKind) { jobs["\(id)-\(kind.rawValue)"] = nil; revision += 1 }5556 private func attach(_ task: Task<Void, Never>, _ id: UUID, _ kind: JobKind) { jobs["\(id)-\(kind.rawValue)"]?.task = task }5758 // MARK: Analysis5960 /// Full analysis pass: report + waveform summary written next to the audio.61 func analyze(_ recording: Recording) async throws {62 let id = recording.id, url = recording.audioURL63 guard begin(id, .analysis) else { return }64 recording.analysisStatus = .running65 defer { end(id, .analysis) }66 do {67 let output = try await Task.detached(priority: .utility) { [weak self] in68 try AudioAnalyzer.analyze(url: url, progress: { p in Task { @MainActor in self?.setProgress(id, .analysis, p) } }, isCancelled: { Task.isCancelled })69 }.value70 try LibraryFiles.save(output.report, to: LibraryFiles.analysisURL(id))71 try LibraryFiles.write(output.waveform.serialized(), to: LibraryFiles.waveformURL(id))72 recording.analysisStatus = .done73 recording.peakDBFS = Double(output.report.time.peakDBFS)74 recording.integratedLUFS = output.report.loudness.integratedLUFS75 try? context.save()76 } catch {77 recording.analysisStatus = error is CancellationError || (error as? AudioIOError).map { if case .cancelled = $0 { true } else { false } } == true ? .none : .failed78 if recording.analysisStatus == .failed { errors[id] = CoreText.describe(error) }79 throw error80 }81 }8283 func analyzeInBackground(_ recording: Recording) {84 let task = Task { _ = try? await analyze(recording) }85 attach(task, recording.id, .analysis)86 }8788 // MARK: Transcription8990 func transcribe(_ recording: Recording, locale: Locale, allowModelDownload: Bool) async throws {91 let id = recording.id, url = recording.audioURL92 guard begin(id, .transcription) else { return }93 recording.transcriptStatus = .running94 defer { end(id, .transcription) }95 do {96 // SpeechAnalyzer / SpeechTranscriber work on-device without the Speech Recognition permission. Only the legacy97 // recogniser needs it — and its system prompt says audio "is sent to Apple", which ORIX Audio prevents by98 // requiring on-device recognition. So the prompt is shown only when that path is actually used.99 if await TranscriptionEngine.path(for: locale) == .legacyOnDevice {100 guard await TranscriptionEngine.requestAuthorization() else { throw TranscriptionError.notAuthorized }101 }102 let transcript = try await TranscriptionEngine.transcribe(url: url, locale: locale, allowModelDownload: allowModelDownload) { [weak self] p in103 Task { @MainActor in self?.setProgress(id, .transcription, p) }104 }105 try LibraryFiles.save(transcript, to: LibraryFiles.transcriptURL(id))106 recording.transcriptStatus = .done107 recording.localeIdentifier = transcript.localeIdentifier108 try? context.save()109 } catch is CancellationError {110 recording.transcriptStatus = LibraryFiles.transcript(id) == nil ? .none : .done111 throw CancellationError()112 } catch {113 recording.transcriptStatus = LibraryFiles.transcript(id) == nil ? .failed : .done114 errors[id] = CoreText.describe(error)115 throw error116 }117 }118119 func transcribeInBackground(_ recording: Recording, locale: Locale, allowModelDownload: Bool) {120 let task = Task { _ = try? await transcribe(recording, locale: locale, allowModelDownload: allowModelDownload) }121 attach(task, recording.id, .transcription)122 }123124 func saveTranscript(_ transcript: Transcript, for recording: Recording) {125 try? LibraryFiles.save(transcript, to: LibraryFiles.transcriptURL(recording.id))126 revision += 1127 }128129 // MARK: Notes130131 func summarize(_ recording: Recording) async throws {132 let id = recording.id133 guard let transcript = LibraryFiles.transcript(id) else { throw IntelligenceError.emptyTranscript }134 guard begin(id, .notes) else { return }135 defer { end(id, .notes) }136 do {137 let notes = try await MeetingIntelligence.notes(for: transcript, style: recording.kind.notesStyle) { [weak self] p in138 Task { @MainActor in self?.setProgress(id, .notes, p) }139 }140 try LibraryFiles.save(notes, to: LibraryFiles.notesURL(id))141 recording.hasNotes = true142 try? context.save()143 } catch is CancellationError {144 throw CancellationError()145 } catch {146 errors[id] = CoreText.describe(error)147 throw error148 }149 }150151 func summarizeInBackground(_ recording: Recording) {152 let task = Task { _ = try? await summarize(recording) }153 attach(task, recording.id, .notes)154 }155156 func saveNotes(_ notes: MeetingNotes, for recording: Recording) {157 var edited = notes; edited.isEdited = true158 try? LibraryFiles.save(edited, to: LibraryFiles.notesURL(recording.id))159 revision += 1160 }161}162