Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ In **Settings → General**, click the shortcut, then press your new key combina
3. Speak, then press the shortcut again. Keep the selected field and cursor unchanged while transcription runs.
4. If insertion cannot be verified or the destination changed, ClearFlow keeps the transcript on the clipboard for manual paste. Check the app’s status for details.

The recording limit is 4 minutes 55 seconds. Cancel with the overlay’s ×; pressing the shortcut while processing cancels delivery. Retry returns text for review and never pastes at an old cursor.
There is no elapsed-time cutoff: recording continues until you finish or cancel. After you finish, longer recordings are transcribed sequentially in parts of at most four minutes and combined into one result. Nothing is uploaded or inserted while you are recording. A word spanning a part boundary may be less accurate. Device interruptions or disk errors can still stop capture and are reported as errors; saved audio can be retried when available. Cancel with the overlay’s ×; pressing the shortcut while processing cancels delivery. Retry returns text for review and never pastes at an old cursor.

[Full local setup, custom storage, startup at login, remote Mac and troubleshooting](local-stt/README.md).

Expand All @@ -78,7 +78,7 @@ Deploy the supplied Worker in **your own account**, generate your own secret, an

- The only bundled endpoint is loopback. Audio and vocabulary go only to the address you explicitly configure. No automatic provider fallback.
- Local Whisper holds request audio in memory and does not log audio or transcripts. Setup downloads dependencies/model weights; runtime uses the local model with Hugging Face offline mode.
- Recording uses temporary WAV files, deleted on normal finish/cancel. A crash can leave a temporary file. Failed requests may keep audio in memory for retry.
- Recording uses temporary WAV files, deleted after successful transcription or cancellation. A crash can leave a temporary file. Failed requests retain the temporary recording file for retry until you cancel, start a new recording or quit.
- Field content is read locally to guard insertion and is not uploaded. Known secure fields are rejected.
- History is memory-only by default. Opt-in saved history stores up to 50 transcripts on your Mac. Clipboard fallback leaves the transcript available until replaced.
- Your endpoint is stored in macOS preferences; the token is stored in Keychain. Keep credentials, recordings, personal endpoints and runtime data out of Git.
Expand Down
53 changes: 42 additions & 11 deletions Sources/ClearFlow/AudioCapture.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
import Foundation
import AVFoundation

protocol AudioRecording: AnyObject {
var delegate: AVAudioRecorderDelegate? { get set }
var isMeteringEnabled: Bool { get set }
var currentTime: TimeInterval { get }
func updateMeters()
func averagePower(forChannel channel: Int) -> Float
func prepareToRecord() -> Bool
func record() -> Bool
func record(forDuration duration: TimeInterval) -> Bool
func stop()
}
extension AVAudioRecorder: AudioRecording {}

@MainActor final class AudioCapture: NSObject, AVAudioRecorderDelegate {
private var recorder: AVAudioRecorder?
private var recorder: AudioRecording?
private let makeRecorder: (URL, [String: Any]) throws -> AudioRecording
init(makeRecorder: @escaping (URL, [String: Any]) throws -> AudioRecording = { try AVAudioRecorder(url: $0, settings: $1) }) {
self.makeRecorder = makeRecorder
super.init()
}
private var file: URL?
var onAutomaticStop: (() -> Void)?
var onUnexpectedStop: ((String) -> Void)?
var seconds: Double { recorder?.currentTime ?? 0 }
var level: Double {
guard let recorder else { return 0 }
Expand All @@ -21,33 +39,46 @@ import AVFoundation
AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsFloatKey: false
]
let r = try AVAudioRecorder(url: url, settings: settings)
let r = try makeRecorder(url, settings)
r.delegate = self; r.isMeteringEnabled = true
guard r.prepareToRecord(), r.record(forDuration: 295) else {
guard r.prepareToRecord(), r.record() else {
try? FileManager.default.removeItem(at: url)
throw AppError.message("The microphone could not start. Check the selected input in System Settings.")
}
recorder = r; file = url
}
func stop() throws -> Data {
func stop() throws -> RecordedAudio {
guard let recorder, let file else { throw AppError.message("No recording is active.") }
recorder.delegate = nil
recorder.stop()
self.recorder = nil; self.file = nil
defer { try? FileManager.default.removeItem(at: file) }
let data = try Data(contentsOf: file)
guard data.count > 8044 else { throw AppError.message("That recording was too short. Speak for at least a moment.") }
return data
let recording = RecordedAudio(url: file)
let size = try FileManager.default.attributesOfItem(atPath: file.path)[.size] as? NSNumber
guard (size?.intValue ?? 0) > 8044 else { throw AppError.message("That recording was too short. Speak for at least a moment.") }
return recording
}
func cancel() {
recorder?.delegate = nil; recorder?.stop(); recorder = nil
if let file { try? FileManager.default.removeItem(at: file) }
file = nil
}
nonisolated func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
Task { @MainActor [weak self] in self?.onAutomaticStop?() }
Task { @MainActor [weak self] in
guard let self, self.recorder === recorder else { return }
self.onUnexpectedStop?("The microphone stopped unexpectedly. Check your input device and available disk space.")
}
}
nonisolated func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
Task { @MainActor [weak self] in self?.onAutomaticStop?() }
Task { @MainActor [weak self] in
guard let self, self.recorder === recorder else { return }
self.onUnexpectedStop?("The microphone stopped unexpectedly. Check your input device and available disk space.")
}
}
}

/// Owns the temporary recording through transcription and retry; removes it on release.
final class RecordedAudio {
let url: URL
init(url: URL) { self.url = url }
deinit { try? FileManager.default.removeItem(at: url) }
}
3 changes: 1 addition & 2 deletions Sources/ClearFlow/ClearFlowApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ import ClearFlowCore
let path = args[2], endpoint = AppSettings.endpoint, token = TokenStore.read()
Task.detached {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let reply = try await TranscriptionClient.transcribe(audio: data, id: UUID(), endpoint: endpoint,
let reply = try await TranscriptionClient.transcribe(file: URL(fileURLWithPath: path), id: UUID(), endpoint: endpoint,
token: token, language: "en", vocabulary: "")
print(reply.text); exit(0)
} catch { fputs("\(error.localizedDescription)\n", stderr); exit(1) }
Expand Down
23 changes: 18 additions & 5 deletions Sources/ClearFlow/DictationModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ import ClearFlowCore
private var currentID: UUID?
private var target: InsertionTarget?
private var captureIssue: String?
private var pendingAudio: Data?
private var pendingAudio: RecordedAudio?
private var ticker: Timer?
private var requestTask: Task<Void, Never>?
private var workspaceObserver: NSObjectProtocol?
Expand All @@ -85,7 +85,13 @@ import ClearFlowCore
app.processIdentifier != ProcessInfo.processInfo.processIdentifier else { return }
Task { @MainActor [weak self] in self?.lastExternalApp = app }
}
capture.onAutomaticStop = { [weak self] in self?.stop() }
capture.onUnexpectedStop = { [weak self] message in
guard let self, self.mode == .recording else { return }
self.ticker?.invalidate(); self.ticker = nil
self.pendingAudio = try? self.capture.stop()
self.gate.cancel(); self.mode = .error; self.level = 0
self.status = message + (self.pendingAudio == nil ? " Please start again." : " Retry to transcribe the saved audio.")
}
}
func refreshPermissions() {
guard !demoMode else { return }
Expand Down Expand Up @@ -164,14 +170,17 @@ import ClearFlowCore
gate.cancel(); mode = .error; status = error.localizedDescription
}
}
private func transcribe(_ audio: Data, id: UUID) {
private func transcribe(_ audio: RecordedAudio, id: UUID) {
mode = .transcribing; status = "Turning speech into text…"; level = 0
let endpoint = AppSettings.endpoint, token = TokenStore.read()
let language = AppSettings.language, vocabulary = AppSettings.vocabulary
requestTask = Task {
do {
let reply = try await TranscriptionClient.transcribe(audio: audio, id: id, endpoint: endpoint,
token: token, language: language, vocabulary: vocabulary)
let reply = try await TranscriptionClient.transcribe(file: audio.url, id: id, endpoint: endpoint,
token: token, language: language, vocabulary: vocabulary,
progress: { [weak self] part, count in
await self?.transcriptionProgress(part: part, count: count, id: id)
})
guard !Task.isCancelled, gate.acceptResult(id) else { return }
let text = reply.text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else {
Expand All @@ -193,6 +202,10 @@ import ClearFlowCore
}
}
}
private func transcriptionProgress(part: Int, count: Int, id: UUID) {
guard currentID == id, mode == .transcribing else { return }
status = count > 1 ? "Transcribing part \(part) of \(count)…" : "Turning speech into text…"
}
func retry() {
guard let audio = pendingAudio, !busy else { return }
gate.cancel(); let id = UUID()
Expand Down
38 changes: 36 additions & 2 deletions Sources/ClearFlow/TranscriptionClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ struct ErrorEnvelope: Decodable {
let error: Detail
}

struct TranscriptionServiceError: LocalizedError {
let status: Int
let code: String
let message: String
var errorDescription: String? { message }
}

enum TranscriptionClient {
static let session: URLSession = {
let config = URLSessionConfiguration.ephemeral
Expand All @@ -28,7 +35,7 @@ enum TranscriptionClient {
return URLSession(configuration: config, delegate: NoRedirectDelegate.shared, delegateQueue: nil)
}()
static func transcribe(audio: Data, id: UUID, endpoint: String, token: String,
language: String, vocabulary: String) async throws -> TranscriptionReply {
language: String, vocabulary: String, session: URLSession = session) async throws -> TranscriptionReply {
guard let base = Endpoint.validated(endpoint), !token.isEmpty else {
throw AppError.message("Set your service address and access token in Settings.")
}
Expand All @@ -51,14 +58,41 @@ enum TranscriptionClient {
guard let http = response as? HTTPURLResponse else { throw AppError.message("No response from the transcription service.") }
guard http.statusCode == 200 else {
let remote = try? JSONDecoder().decode(ErrorEnvelope.self, from: data)
throw AppError.message(remote?.error.message ?? "Transcription failed (HTTP \(http.statusCode)).")
throw TranscriptionServiceError(status: http.statusCode, code: remote?.error.code ?? "UNKNOWN",
message: remote?.error.message ?? "Transcription failed (HTTP \(http.statusCode)).")
}
let reply = try JSONDecoder().decode(TranscriptionReply.self, from: data)
guard reply.requestId.lowercased() == id.uuidString.lowercased() else {
throw AppError.message("The service returned a different recording ID. Nothing was inserted.")
}
return reply
}
static func transcribe(file: URL, id: UUID, endpoint: String, token: String,
language: String, vocabulary: String, session: URLSession = session,
progress: @Sendable (Int, Int) async -> Void = { _, _ in }) async throws -> TranscriptionReply {
let chunks = try WAVChunks(url: file)
var text: [String] = []
var duration = 0.0
var model = ""
for index in 0..<chunks.count {
try Task.checkCancellation()
await progress(index + 1, chunks.count)
try Task.checkCancellation()
do {
let reply = try await transcribe(audio: chunks.chunk(at: index), id: UUID(), endpoint: endpoint,
token: token, language: language, vocabulary: vocabulary, session: session)
text.append(reply.text.trimmingCharacters(in: .whitespacesAndNewlines))
duration += reply.durationMs; model = reply.model
} catch let error as TranscriptionServiceError where error.status == 422 && error.code == "NO_SPEECH" {
// A silent segment must not discard speech in the rest of a long recording.
continue
}
}
try Task.checkCancellation()
let combined = text.filter { !$0.isEmpty }.joined(separator: " ")
guard !combined.isEmpty else { throw AppError.message("No speech was detected. Try again closer to the microphone.") }
return TranscriptionReply(text: combined, requestId: id.uuidString, model: model, durationMs: duration)
}
static func health(endpoint: String) async throws -> String {
guard let base = Endpoint.validated(endpoint) else { throw AppError.message("Enter HTTPS, or HTTP on localhost.") }
let (_, response) = try await session.data(from: base.appendingPathComponent("health"))
Expand Down
2 changes: 1 addition & 1 deletion Sources/ClearFlow/Views.swift
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ private struct FlowSettings: View {
SecureField(model.hasToken ? "Saved in Keychain — leave blank to keep" : "Private service token", text: $model.token)
.textFieldStyle(.roundedBorder).padding(.top, 10)
Button("Check connection") { model.testConnection() }.buttonStyle(FlowButton()).padding(.top, 20)
Text("Transcription begins when you finish speaking. Up to 4 minutes 55 seconds per recording.")
Text("Recording continues until you stop or cancel. Longer recordings are transcribed in parts after you stop.")
.font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(3).padding(.top, 20)
}
}
Expand Down
88 changes: 88 additions & 0 deletions Sources/ClearFlowCore/WAVChunks.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import Foundation

/// Reads only one request-sized PCM segment at a time, even for long recordings.
public struct WAVChunks {
public enum Failure: LocalizedError {
case invalid, tooShort
public var errorDescription: String? {
switch self {
case .invalid: return "The recording is not a complete 16 kHz mono PCM16 WAV file."
case .tooShort: return "That recording was too short. Speak for at least a moment."
}
}
}
public let url: URL
public let count: Int
public let frames: Int
private let dataOffset: UInt64
private let framesPerChunk: Int
public init(url: URL) throws {
self.url = url
let file = try FileHandle(forReadingFrom: url)
defer { try? file.close() }
let size = try file.seekToEnd()
try file.seek(toOffset: 0)
let header = try file.read(upToCount: 12) ?? Data()
guard header.count == 12, header.prefix(4) == Data("RIFF".utf8),
header.suffix(4) == Data("WAVE".utf8), UInt64(header.u32(4)) + 8 == size else { throw Failure.invalid }
var offset: UInt64 = 12
var formatSeen = false
var audio: (UInt64, Int)?
var chunks = 0
while offset < size {
chunks += 1
guard chunks <= 1024, offset + 8 <= size else { throw Failure.invalid }
try file.seek(toOffset: offset)
let chunk = try file.read(upToCount: 8) ?? Data()
guard chunk.count == 8 else { throw Failure.invalid }
let length = UInt64(chunk.u32(4))
let start = offset + 8
guard start + length + length % 2 <= size else { throw Failure.invalid }
if chunk.prefix(4) == Data("fmt ".utf8) {
guard !formatSeen, length >= 16 else { throw Failure.invalid }
let fmt = try file.read(upToCount: 16) ?? Data()
guard fmt.count == 16, fmt.u16(0) == 1, fmt.u16(2) == 1,
fmt.u32(4) == 16000, fmt.u32(8) == 32000,
fmt.u16(12) == 2, fmt.u16(14) == 16 else { throw Failure.invalid }
formatSeen = true
} else if chunk.prefix(4) == Data("data".utf8) {
guard audio == nil, length % 2 == 0 else { throw Failure.invalid }
audio = (start, Int(length / 2))
}
offset = start + length + length % 2
}
guard formatSeen, let audio else { throw Failure.invalid }
guard audio.1 >= 4000 else { throw Failure.tooShort }
dataOffset = audio.0
frames = audio.1
let maxFrames = 240 * 16000
count = (frames + maxFrames - 1) / maxFrames
// Balance the segments so a tiny remainder never becomes a rejected <0.25s request.
framesPerChunk = (frames + count - 1) / count
}
public func chunk(at index: Int) throws -> Data {
guard index >= 0, index < count else { throw Failure.invalid }
let start = index * framesPerChunk
let length = min(framesPerChunk, frames - start) * 2
let file = try FileHandle(forReadingFrom: url)
defer { try? file.close() }
try file.seek(toOffset: dataOffset + UInt64(start * 2))
let pcm = try file.read(upToCount: length) ?? Data()
guard pcm.count == length else { throw Failure.invalid }
var wav = Data("RIFF".utf8)
wav.appendLE(UInt32(length + 36)); wav.append(Data("WAVEfmt ".utf8))
wav.appendLE(UInt32(16)); wav.appendLE(UInt16(1)); wav.appendLE(UInt16(1))
wav.appendLE(UInt32(16000)); wav.appendLE(UInt32(32000))
wav.appendLE(UInt16(2)); wav.appendLE(UInt16(16))
wav.append(Data("data".utf8)); wav.appendLE(UInt32(length)); wav.append(pcm)
return wav
}
}
private extension Data {
func u16(_ offset: Int) -> UInt16 { UInt16(self[offset]) | UInt16(self[offset + 1]) << 8 }
func u32(_ offset: Int) -> UInt32 { UInt32(u16(offset)) | UInt32(u16(offset + 2)) << 16 }
mutating func appendLE<T: FixedWidthInteger>(_ value: T) {
var little = value.littleEndian
Swift.withUnsafeBytes(of: &little) { append(contentsOf: $0) }
}
}
Loading
Loading