Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more
Add optional speaker labeling to file transcription
postoso62e38c64795f
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex 8c91c842..bcecd4df 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -1374,6 +1374,24 @@ final class SettingsStore: ObservableObject {}}+ /// Label speakers ("Speaker 1", "Speaker 2") in file transcriptions (default: OFF).+ var fileTranscriptionSpeakerLabelsEnabled: Bool {+ get { self.defaults.bool(forKey: Keys.fileTranscriptionSpeakerLabelsEnabled) }+ set {+ objectWillChange.send()+ self.defaults.set(newValue, forKey: Keys.fileTranscriptionSpeakerLabelsEnabled)+ }+ }++ /// Expected speaker count hint for file transcription diarization. 0 = auto-detect.+ var fileTranscriptionExpectedSpeakerCount: Int {+ get { self.defaults.integer(forKey: Keys.fileTranscriptionExpectedSpeakerCount) }+ set {+ objectWillChange.send()+ self.defaults.set(newValue, forKey: Keys.fileTranscriptionExpectedSpeakerCount)+ }+ }+/// Anonymous analytics toggle (default: ON). Uses default-true semantics so existing installs/// upgrading to a version that includes analytics do not silently default to OFF.var shareAnonymousAnalytics: Bool {@@ -4877,6 +4895,8 @@ private extension SettingsStore {enum Keys {static let enableAIProcessing = "EnableAIProcessing"static let showMainWindowAtLoginLaunch = "ShowMainWindowAtLoginLaunch"+ static let fileTranscriptionSpeakerLabelsEnabled = "FileTranscriptionSpeakerLabelsEnabled"+ static let fileTranscriptionExpectedSpeakerCount = "FileTranscriptionExpectedSpeakerCount"static let dictationPromptOff = "DictationPromptOff"static let enableDebugLogs = "EnableDebugLogs"static let availableAIModels = "AvailableAIModels"diff --git a/Sources/Fluid/Services/MeetingTranscriptionService.swift b/Sources/Fluid/Services/MeetingTranscriptionService.swiftindex 67d1eede..5b2ebb22 100644--- a/Sources/Fluid/Services/MeetingTranscriptionService.swift+++ b/Sources/Fluid/Services/MeetingTranscriptionService.swift@@ -4,6 +4,20 @@ import CoreMediaimport Foundationimport UniformTypeIdentifiers+/// One speaker-attributed portion of a file transcription.+struct SpeakerTranscriptSegment: Identifiable, Sendable, Codable, Equatable {+ let speaker: String+ let startSeconds: Double+ let endSeconds: Double+ let text: String++ var id: String { "\(self.speaker)-\(self.startSeconds)" }++ enum CodingKeys: String, CodingKey {+ case speaker, startSeconds, endSeconds, text+ }+}+/// Result of a transcription operationstruct TranscriptionResult: Identifiable, Sendable, Codable {let id: UUID@@ -13,6 +27,8 @@ struct TranscriptionResult: Identifiable, Sendable, Codable {let processingTime: TimeIntervallet fileName: Stringlet timestamp: Date+ /// Speaker-attributed segments when diarization was enabled; empty otherwise.+ let speakerSegments: [SpeakerTranscriptSegment]init(id: UUID = UUID(),@@ -21,7 +37,8 @@ struct TranscriptionResult: Identifiable, Sendable, Codable {duration: TimeInterval,processingTime: TimeInterval,fileName: String,- timestamp: Date = Date()+ timestamp: Date = Date(),+ speakerSegments: [SpeakerTranscriptSegment] = []) {self.id = idself.text = text@@ -30,10 +47,11 @@ struct TranscriptionResult: Identifiable, Sendable, Codable {self.processingTime = processingTimeself.fileName = fileNameself.timestamp = timestamp+ self.speakerSegments = speakerSegments}enum CodingKeys: String, CodingKey {- case text, confidence, duration, processingTime, fileName, timestamp+ case text, confidence, duration, processingTime, fileName, timestamp, speakerSegments}init(from decoder: Decoder) throws {@@ -45,6 +63,7 @@ struct TranscriptionResult: Identifiable, Sendable, Codable {self.processingTime = try c.decode(TimeInterval.self, forKey: .processingTime)self.fileName = try c.decode(String.self, forKey: .fileName)self.timestamp = try c.decode(Date.self, forKey: .timestamp)+ self.speakerSegments = try c.decodeIfPresent([SpeakerTranscriptSegment].self, forKey: .speakerSegments) ?? []}func encode(to encoder: Encoder) throws {@@ -55,6 +74,9 @@ struct TranscriptionResult: Identifiable, Sendable, Codable {try c.encode(self.processingTime, forKey: .processingTime)try c.encode(self.fileName, forKey: .fileName)try c.encode(self.timestamp, forKey: .timestamp)+ if !self.speakerSegments.isEmpty {+ try c.encode(self.speakerSegments, forKey: .speakerSegments)+ }}}@@ -207,6 +229,23 @@ final class MeetingTranscriptionService: ObservableObject {let isVideoContainer = UTType(filenameExtension: fileExtension).map { $0.conforms(to: .movie) } ?? false+ // Speaker-labeled path: diarize first, then transcribe each speaker turn.+ // Any diarization failure falls back to the standard paths below.+ if SettingsStore.shared.fileTranscriptionSpeakerLabelsEnabled, SpeakerDiarizationService.isSupported {+ if let labeledResult = await self.transcribeFileWithSpeakerLabels(+ fileURL,+ provider: provider,+ duration: duration,+ startTime: startTime+ ) {+ return labeledResult+ }+ DebugLogger.shared.warning(+ "Speaker labeling unavailable for this file; falling back to standard transcription",+ source: "MeetingTranscriptionService"+ )+ }+if provider.prefersNativeFileTranscription && !isVideoContainer {self.currentStatus = duration > 0 ? "Transcribing audio (\(Int(duration))s)..." : "Transcribing audio..."self.progress = 0.3@@ -433,4 +472,281 @@ final class MeetingTranscriptionService: ObservableObject {self.currentStatus = ""self.progress = 0.0}++ // MARK: - Speaker-Labeled Transcription++ /// Diarize-first pipeline: identify speaker turns, then transcribe the audio slice for+ /// each turn with the active provider. Returns nil when diarization fails or yields+ /// nothing usable, so the caller can fall back to the standard transcription paths.+ private func transcribeFileWithSpeakerLabels(+ _ fileURL: URL,+ provider: TranscriptionProvider,+ duration: Double,+ startTime: Date+ ) async -> TranscriptionResult? {+ self.currentStatus = "Identifying speakers..."+ self.progress = 0.25++ let expectedSpeakers = SettingsStore.shared.fileTranscriptionExpectedSpeakerCount+ let diarizer = SpeakerDiarizationService(+ expectedSpeakers: expectedSpeakers > 0 ? expectedSpeakers : nil+ )++ let turns: [SpeakerDiarizationService.SpeakerTurn]+ do {+ turns = try await diarizer.diarize(fileURL: fileURL)+ } catch {+ DebugLogger.shared.warning(+ "Diarization failed: \(error.localizedDescription)",+ source: "MeetingTranscriptionService"+ )+ return nil+ }++ guard !turns.isEmpty else {+ DebugLogger.shared.info(+ "Diarization found no speaker turns",+ source: "MeetingTranscriptionService"+ )+ return nil+ }++ let audioFile: AVAudioFile+ do {+ audioFile = try AVAudioFile(forReading: fileURL)+ } catch {+ DebugLogger.shared.warning(+ "Could not open audio for speaker slicing: \(error.localizedDescription)",+ source: "MeetingTranscriptionService"+ )+ return nil+ }++ var segments: [SpeakerTranscriptSegment] = []+ var totalConfidence: Float = 0++ for (index, turn) in turns.enumerated() {+ self.currentStatus = "Transcribing speaker segments (\(index + 1)/\(turns.count))..."+ self.progress = 0.3 + (Double(index) / Double(turns.count)) * 0.65++ let samples: [Float]+ do {+ samples = try self.readSamples(+ from: audioFile,+ startSeconds: turn.startSeconds,+ endSeconds: turn.endSeconds,+ minimumDurationSeconds: 1.1+ )+ } catch {+ DebugLogger.shared.warning(+ "Skipping speaker segment at \(String(format: "%.1f", turn.startSeconds))s: \(error.localizedDescription)",+ source: "MeetingTranscriptionService"+ )+ continue+ }++ // Mirror the standard path's 1-second ASR minimum+ guard samples.count >= 16_000 else { continue }++ let chunkResult: ASRTranscriptionResult+ do {+ chunkResult = try await provider.transcribe(samples)+ } catch {+ DebugLogger.shared.warning(+ "Transcription failed for speaker segment at \(String(format: "%.1f", turn.startSeconds))s: \(error.localizedDescription)",+ source: "MeetingTranscriptionService"+ )+ continue+ }++ let text = chunkResult.text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else { continue }++ segments.append(SpeakerTranscriptSegment(+ speaker: turn.speakerLabel,+ startSeconds: turn.startSeconds,+ endSeconds: turn.endSeconds,+ text: text+ ))+ totalConfidence += chunkResult.confidence+ }++ guard !segments.isEmpty else {+ DebugLogger.shared.warning(+ "No speaker segments produced text",+ source: "MeetingTranscriptionService"+ )+ return nil+ }++ let labeledText = segments+ .map { "\($0.speaker): \($0.text)" }+ .joined(separator: "\n\n")+ let avgConfidence = totalConfidence / Float(segments.count)+ let processingTime = Date().timeIntervalSince(startTime)++ let result = TranscriptionResult(+ text: labeledText,+ confidence: avgConfidence,+ duration: duration,+ processingTime: processingTime,+ fileName: fileURL.lastPathComponent,+ speakerSegments: segments+ )++ self.currentStatus = "Complete!"+ self.progress = 1.0++ AnalyticsService.shared.capture(+ .meetingTranscriptionCompleted,+ properties: [+ "success": true,+ "file_type": fileURL.pathExtension.lowercased(),+ "audio_duration_bucket": AnalyticsBuckets.bucketSeconds(duration),+ "processing_time_bucket": AnalyticsBuckets.bucketSeconds(processingTime),+ "speaker_labels": true,+ "speaker_count": Set(segments.map(\.speaker)).count,+ ]+ )++ self.result = result+ FileTranscriptionHistoryStore.shared.addEntry(result)+ return result+ }++ /// Read a time range from an audio file as 16kHz mono Float32 samples.+ /// Short ranges are widened symmetrically to `minimumDurationSeconds` (clamped to+ /// the file bounds) so very brief speaker turns still meet the ASR input minimum.+ private nonisolated func readSamples(+ from audioFile: AVAudioFile,+ startSeconds: Double,+ endSeconds: Double,+ minimumDurationSeconds: Double+ ) throws -> [Float] {+ let sourceSampleRate = audioFile.processingFormat.sampleRate+ guard sourceSampleRate > 0 else {+ throw TranscriptionError.audioConversionFailed("Invalid audio file: sample rate is 0")+ }+ let fileDurationSeconds = Double(audioFile.length) / sourceSampleRate++ var start = max(0, startSeconds)+ var end = min(endSeconds, fileDurationSeconds)+ if end - start < minimumDurationSeconds {+ let deficit = minimumDurationSeconds - (end - start)+ start = max(0, start - deficit / 2)+ end = min(fileDurationSeconds, start + minimumDurationSeconds)+ start = max(0, end - minimumDurationSeconds)+ }+ guard end > start else { return [] }++ let startFrame = AVAudioFramePosition((start * sourceSampleRate).rounded(.down))+ let frameCount = AVAudioFrameCount(((end - start) * sourceSampleRate).rounded(.up))+ guard frameCount > 0 else { return [] }++ guard let buffer = AVAudioPCMBuffer(+ pcmFormat: audioFile.processingFormat,+ frameCapacity: frameCount+ ) else {+ throw TranscriptionError.audioConversionFailed("Could not create audio buffer")+ }++ audioFile.framePosition = startFrame+ try audioFile.read(into: buffer, frameCount: frameCount)+ return try self.resampleBuffer(buffer)+ }++ // MARK: - Audio Resampling Helpers++ /// Resample an audio buffer to 16kHz mono Float32 samples+ /// - Parameters:+ /// - buffer: Source audio buffer+ /// - targetSampleRate: Target sample rate (default 16000 Hz)+ /// - Returns: Array of Float32 samples at target sample rate+ private nonisolated func resampleBuffer(_ buffer: AVAudioPCMBuffer, targetSampleRate: Double = 16_000) throws -> [Float] {+ let sourceFormat = buffer.format+ let sourceSampleRate = sourceFormat.sampleRate+ let sourceChannels = sourceFormat.channelCount++ // Create target format (16kHz mono Float32)+ guard let targetFormat = AVAudioFormat(+ commonFormat: .pcmFormatFloat32,+ sampleRate: targetSampleRate,+ channels: 1,+ interleaved: false+ ) else {+ throw NSError(+ domain: "MeetingTranscriptionService",+ code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Could not create target audio format"]+ )+ }++ // If already in correct format, just extract samples+ // Must also verify the format is Float32 - if source is Float64, floatChannelData returns nil+ if sourceSampleRate == targetSampleRate,+ sourceChannels == 1,+ sourceFormat.commonFormat == .pcmFormatFloat32+ {+ guard let channelData = buffer.floatChannelData else {+ throw NSError(+ domain: "MeetingTranscriptionService",+ code: -2,+ userInfo: [NSLocalizedDescriptionKey: "Could not access audio channel data"]+ )+ }+ let frameLength = Int(buffer.frameLength)+ return Array(UnsafeBufferPointer(start: channelData[0], count: frameLength))+ }++ // Create converter+ guard let converter = AVAudioConverter(from: sourceFormat, to: targetFormat) else {+ throw NSError(+ domain: "MeetingTranscriptionService",+ code: -3,+ userInfo: [NSLocalizedDescriptionKey: "Could not create audio converter"]+ )+ }++ // Calculate output buffer size+ let ratio = targetSampleRate / sourceSampleRate+ let estimatedFrameCount = AVAudioFrameCount(Double(buffer.frameLength) * ratio)++ guard let outputBuffer = AVAudioPCMBuffer(pcmFormat: targetFormat, frameCapacity: estimatedFrameCount + 1024) else {+ throw NSError(+ domain: "MeetingTranscriptionService",+ code: -4,+ userInfo: [NSLocalizedDescriptionKey: "Could not create output buffer"]+ )+ }++ // Convert+ var error: NSError?+ var inputConsumed = false++ converter.convert(to: outputBuffer, error: &error) { _, outStatus in+ if inputConsumed {+ outStatus.pointee = .endOfStream+ return nil+ }+ inputConsumed = true+ outStatus.pointee = .haveData+ return buffer+ }++ if let error = error {+ throw error+ }++ // Extract samples+ guard let channelData = outputBuffer.floatChannelData else {+ throw NSError(+ domain: "MeetingTranscriptionService",+ code: -5,+ userInfo: [NSLocalizedDescriptionKey: "Could not access converted audio data"]+ )+ }++ let frameLength = Int(outputBuffer.frameLength)+ return Array(UnsafeBufferPointer(start: channelData[0], count: frameLength))+ }}diff --git a/Sources/Fluid/Services/SpeakerDiarizationService.swift b/Sources/Fluid/Services/SpeakerDiarizationService.swiftnew file mode 100644index 00000000..3fd91b0c--- /dev/null+++ b/Sources/Fluid/Services/SpeakerDiarizationService.swift@@ -0,0 +1,140 @@+import Foundation++#if arch(arm64)+import FluidAudio++/// Identifies who spoke when in an audio file using FluidAudio's offline diarizer.+/// Diarizer CoreML models download automatically on first use (same flow as the ASR models).+actor SpeakerDiarizationService {+ static let isSupported = true++ /// A contiguous stretch of speech attributed to one speaker.+ struct SpeakerTurn: Sendable, Equatable {+ let speakerLabel: String+ let startSeconds: Double+ let endSeconds: Double++ var durationSeconds: Double { self.endSeconds - self.startSeconds }+ }++ private let manager: OfflineDiarizerManager+ private var modelsReady = false++ /// - Parameter expectedSpeakers: Exact speaker count hint for clustering.+ /// Pass nil (or a non-positive count upstream) to let the diarizer estimate it.+ init(expectedSpeakers: Int? = nil) {+ var config = OfflineDiarizerConfig.default+ if let expectedSpeakers, expectedSpeakers > 0 {+ config = config.withSpeakers(exactly: expectedSpeakers)+ }+ self.manager = OfflineDiarizerManager(config: config)+ }++ /// Diarize an audio file into chronological speaker turns.+ /// Speaker labels are assigned in order of first appearance ("Speaker 1" spoke first).+ /// Returns an empty array when no speech is detected.+ func diarize(fileURL: URL) async throws -> [SpeakerTurn] {+ if !self.modelsReady {+ DebugLogger.shared.info(+ "SpeakerDiarizationService: preparing diarizer models",+ source: "SpeakerDiarizationService"+ )+ try await self.manager.prepareModels()+ self.modelsReady = true+ }++ let result: DiarizationResult+ do {+ result = try await self.manager.process(fileURL)+ } catch let error as OfflineDiarizationError {+ if case .noSpeechDetected = error {+ return []+ }+ throw error+ }++ // Sort chronologically before assigning stable labels so "Speaker 1" is the+ // first speaker to talk, not the first cluster the pipeline happens to emit.+ let chronological = result.segments.sorted { $0.startTimeSeconds < $1.startTimeSeconds }++ var labelByClusterId: [String: String] = [:]+ var nextSpeakerNumber = 1+ let turns: [SpeakerTurn] = chronological.map { segment in+ let label: String+ if let existing = labelByClusterId[segment.speakerId] {+ label = existing+ } else {+ label = "Speaker \(nextSpeakerNumber)"+ labelByClusterId[segment.speakerId] = label+ nextSpeakerNumber += 1+ }+ return SpeakerTurn(+ speakerLabel: label,+ startSeconds: Double(segment.startTimeSeconds),+ endSeconds: Double(segment.endTimeSeconds)+ )+ }++ return Self.mergeAdjacentTurns(turns)+ }++ /// Merge consecutive turns from the same speaker separated by short gaps.+ /// Fewer, longer turns give the ASR more context per slice and read better.+ /// Merged turns are capped so downstream slice reads stay bounded (mirrors the+ /// 20-minute chunk ceiling used by the standard file transcription path).+ static func mergeAdjacentTurns(+ _ turns: [SpeakerTurn],+ maxGapSeconds: Double = 1.0,+ maxTurnSeconds: Double = 20 * 60+ ) -> [SpeakerTurn] {+ guard var current = turns.first else { return [] }+ var merged: [SpeakerTurn] = []++ for turn in turns.dropFirst() {+ let gap = turn.startSeconds - current.endSeconds+ let combinedDuration = turn.endSeconds - current.startSeconds+ if turn.speakerLabel == current.speakerLabel,+ gap <= maxGapSeconds,+ combinedDuration <= maxTurnSeconds+ {+ current = SpeakerTurn(+ speakerLabel: current.speakerLabel,+ startSeconds: current.startSeconds,+ endSeconds: turn.endSeconds+ )+ } else {+ merged.append(current)+ current = turn+ }+ }+ merged.append(current)+ return merged+ }+}++#else++/// Stub for Intel Macs where FluidAudio (and therefore diarization) is unavailable.+actor SpeakerDiarizationService {+ static let isSupported = false++ struct SpeakerTurn: Sendable, Equatable {+ let speakerLabel: String+ let startSeconds: Double+ let endSeconds: Double++ var durationSeconds: Double { self.endSeconds - self.startSeconds }+ }++ init(expectedSpeakers: Int? = nil) {}++ func diarize(fileURL: URL) async throws -> [SpeakerTurn] {+ throw NSError(+ domain: "SpeakerDiarizationService",+ code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Speaker diarization is not supported on Intel Macs"]+ )+ }+}++#endifdiff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swiftindex c2061e93..c79279e1 100644--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift@@ -5,6 +5,7 @@ struct MeetingTranscriptionView: View {let asrService: ASRService@StateObject private var transcriptionService: MeetingTranscriptionService@ObservedObject private var fileHistoryStore = FileTranscriptionHistoryStore.shared+ @ObservedObject private var settings = SettingsStore.shared@State private var selectedFileURL: URL?@Environment(\.theme) private var theme@@ -164,6 +165,51 @@ struct MeetingTranscriptionView: View {))+ // Speaker labeling options (unavailable on Intel Macs)+ if SpeakerDiarizationService.isSupported {+ VStack(spacing: 10) {+ Toggle(isOn: self.$settings.fileTranscriptionSpeakerLabelsEnabled) {+ VStack(alignment: .leading, spacing: 2) {+ Text("Label speakers")+ .font(.subheadline)++ Text("Identify who said what (downloads speaker models on first use)")+ .font(.caption)+ .foregroundColor(.secondary)+ }+ }+ .toggleStyle(.switch)++ if self.settings.fileTranscriptionSpeakerLabelsEnabled {+ HStack {+ Text("Number of speakers")+ .font(.subheadline)++ Spacer()++ Picker("", selection: self.$settings.fileTranscriptionExpectedSpeakerCount) {+ Text("Auto").tag(0)+ ForEach(2 ... 8, id: \.self) { count in+ Text("\(count)").tag(count)+ }+ }+ .pickerStyle(.menu)+ .labelsHidden()+ .frame(width: 90)+ }+ }+ }+ .padding()+ .background(+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .fill(self.theme.palette.cardBackground)+ .overlay(+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .stroke(self.theme.palette.cardBorder.opacity(0.5), lineWidth: 1)+ )+ )+ }+// Transcribe ButtonButton(action: {Task {@@ -312,11 +358,36 @@ struct MeetingTranscriptionView: View {// Transcription textScrollView {- Text(result.text)- .font(.body)- .textSelection(.enabled)+ if !result.speakerSegments.isEmpty {+ VStack(alignment: .leading, spacing: 12) {+ ForEach(result.speakerSegments) { segment in+ VStack(alignment: .leading, spacing: 2) {+ HStack(spacing: 6) {+ Text(segment.speaker)+ .font(.caption)+ .fontWeight(.semibold)+ .foregroundColor(Color.fluidGreen)++ Text(Self.timestampString(segment.startSeconds))+ .font(.caption2)+ .foregroundColor(.secondary)+ }++ Text(segment.text)+ .font(.body)+ .textSelection(.enabled)+ }+ }+ }.frame(maxWidth: .infinity, alignment: .leading).padding()+ } else {+ Text(result.text)+ .font(.body)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding()+ }}.frame(maxHeight: 300).background(@@ -587,6 +658,18 @@ struct MeetingTranscriptionView: View {return formatter.string(fromByteCount: fileSize)}+ /// Format seconds as m:ss (or h:mm:ss for long files) for speaker segment timestamps.+ private static func timestampString(_ seconds: Double) -> String {+ let total = Int(seconds.rounded(.down))+ let hours = total / 3600+ let minutes = (total % 3600) / 60+ let secs = total % 60+ if hours > 0 {+ return String(format: "%d:%02d:%02d", hours, minutes, secs)+ }+ return String(format: "%d:%02d", minutes, secs)+ }+private func copyToClipboard(_ text: String) {NSPasteboard.general.clearContents()NSPasteboard.general.setString(text, forType: .string)