Skip to content

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

fix: chunk long local api transcriptions

altic-dev400667311f47
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 3cb021aa..85963727 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -2690,9 +2690,52 @@ final class ASRService: ObservableObject {
}
guard provider.prefersNativeFileTranscription else {
- let samples = try LocalAPIAudioDecoder.samples(from: fileURL)
- let result = try await self.transcribeSamplesForAPI(samples)
- return (result, samples.count)
+ let reader = try LocalAPIAudioDecoder.ChunkReader(fileURL: fileURL)
+ let (combinedText, confidence, processedSampleCount) = try await transcriptionExecutor.run { [provider] in
+ var textParts: [String] = []
+ var weightedConfidence = 0.0
+ var processedSampleCount = 0
+
+ while true {
+ var samples = try await reader.nextSamples()
+ let sampleCount = samples.count
+ guard sampleCount > 0 else { break }
+ if sampleCount < 16_000 {
+ samples.append(contentsOf: repeatElement(0.0, count: 16_000 - sampleCount))
+ }
+
+ let result = try await provider.transcribeFinal(samples)
+ if !result.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ textParts.append(result.text)
+ }
+ weightedConfidence += Double(result.confidence) * Double(sampleCount)
+ processedSampleCount += sampleCount
+ }
+
+ let confidence = processedSampleCount > 0
+ ? Float(weightedConfidence / Double(processedSampleCount))
+ : 0
+ return (textParts.joined(separator: " "), confidence, processedSampleCount)
+ }
+
+ guard processedSampleCount > 0 else {
+ return (ASRTranscriptionResult(text: "", confidence: 0), sampleCount: 0)
+ }
+
+ if !self.hasCompletedFirstTranscription {
+ self.hasCompletedFirstTranscription = true
+ self.isLoadingModel = false
+ self.modelPreparationPhase = nil
+ }
+
+ let cleanedText = ASRService.applySpokenPunctuationFormatting(
+ ASRService.applyCustomDictionary(ASRService.removeFillerWords(combinedText))
+ )
+ self.recordWordBoostHitIfAny(transcribedText: cleanedText)
+ return (
+ ASRTranscriptionResult(text: cleanedText, confidence: confidence),
+ sampleCount: estimatedSamples
+ )
}
let result = try await transcriptionExecutor.run { [provider] in
diff --git a/Sources/Fluid/Services/LocalAPI/LocalAPIAudioDecoder.swift b/Sources/Fluid/Services/LocalAPI/LocalAPIAudioDecoder.swift
index a553b9e0..21e5fb71 100644
--- a/Sources/Fluid/Services/LocalAPI/LocalAPIAudioDecoder.swift
+++ b/Sources/Fluid/Services/LocalAPI/LocalAPIAudioDecoder.swift
@@ -3,6 +3,56 @@ import Foundation
enum LocalAPIAudioDecoder {
static let sampleRate: Double = 16_000
+ static let maxChunkDurationSeconds: Double = 20 * 60
+
+ actor ChunkReader {
+ private let audioFile: AVAudioFile
+ private let sourceFramesPerChunk: AVAudioFrameCount
+
+ init(
+ fileURL: URL,
+ chunkDurationSeconds: Double = LocalAPIAudioDecoder.maxChunkDurationSeconds
+ ) throws {
+ let audioFile = try AVAudioFile(forReading: fileURL)
+ let sourceSampleRate = audioFile.processingFormat.sampleRate
+ guard sourceSampleRate > 0, chunkDurationSeconds > 0 else {
+ throw NSError(
+ domain: "LocalAPIAudioDecoder",
+ code: -6,
+ userInfo: [NSLocalizedDescriptionKey: "Audio file has an invalid sample rate or chunk duration."]
+ )
+ }
+
+ self.audioFile = audioFile
+ self.sourceFramesPerChunk = AVAudioFrameCount(sourceSampleRate * chunkDurationSeconds)
+ }
+
+ func nextSamples() throws -> [Float] {
+ guard self.audioFile.framePosition < self.audioFile.length else { return [] }
+
+ let remainingFrames = self.audioFile.length - self.audioFile.framePosition
+ let framesToRead = AVAudioFrameCount(min(
+ AVAudioFramePosition(self.sourceFramesPerChunk),
+ remainingFrames
+ ))
+ guard let sourceBuffer = AVAudioPCMBuffer(
+ pcmFormat: self.audioFile.processingFormat,
+ frameCapacity: framesToRead
+ ) else {
+ throw NSError(
+ domain: "LocalAPIAudioDecoder",
+ code: -1,
+ userInfo: [NSLocalizedDescriptionKey: "Unable to allocate audio buffer."]
+ )
+ }
+
+ try self.audioFile.read(into: sourceBuffer, frameCount: framesToRead)
+ return try AudioBufferConverter.monoSamples(
+ from: sourceBuffer,
+ targetSampleRate: LocalAPIAudioDecoder.sampleRate
+ )
+ }
+ }
static func samples(from fileURL: URL) throws -> [Float] {
let file = try AVAudioFile(forReading: fileURL)
diff --git a/Tests/FluidDictationIntegrationTests/AudioBufferConverterTests.swift b/Tests/FluidDictationIntegrationTests/AudioBufferConverterTests.swift
index ff7a78cb..74d60f5c 100644
--- a/Tests/FluidDictationIntegrationTests/AudioBufferConverterTests.swift
+++ b/Tests/FluidDictationIntegrationTests/AudioBufferConverterTests.swift
@@ -63,6 +63,34 @@ final class AudioBufferConverterTests: XCTestCase {
XCTAssertGreaterThan(samples.map(abs).max() ?? 0, 0.4)
}
+ func testLocalAPIAudioChunkReaderBoundsMemoryAndPreservesFinalChunk() async throws {
+ let fileURL = FileManager.default.temporaryDirectory
+ .appendingPathComponent("local-api-chunks-\(UUID().uuidString).wav")
+ defer { try? FileManager.default.removeItem(at: fileURL) }
+
+ let buffer = try self.makeFloatBuffer(sampleRate: 16_000, channels: 1, frameCount: 4000)
+ do {
+ let outputFile = try AVAudioFile(forWriting: fileURL, settings: buffer.format.settings)
+ try outputFile.write(from: buffer)
+ }
+
+ let reader = try LocalAPIAudioDecoder.ChunkReader(
+ fileURL: fileURL,
+ chunkDurationSeconds: 0.1
+ )
+
+ let firstChunk = try await reader.nextSamples()
+ let secondChunk = try await reader.nextSamples()
+ let finalChunk = try await reader.nextSamples()
+
+ XCTAssertEqual(firstChunk.count, 1600)
+ XCTAssertEqual(secondChunk.count, 1600)
+ XCTAssertEqual(finalChunk.count, 800)
+ let exhaustedChunk = try await reader.nextSamples()
+ XCTAssertTrue(exhaustedChunk.isEmpty)
+ XCTAssertEqual(LocalAPIAudioDecoder.maxChunkDurationSeconds, 20 * 60)
+ }
+
private func makeFloatBuffer(
sampleRate: Double,
channels: AVAudioChannelCount,