diff --git a/README.md b/README.md index 1cd35c0..e35162d 100644 --- a/README.md +++ b/README.md @@ -63,8 +63,10 @@ In **Settings → General**, click the shortcut, then press your new key combina 1. Open ClearFlow. In Settings → General, allow Microphone and Accessibility through the normal macOS prompts. 2. Select an editable field in another app. Press **Option–Shift–Space** to start; the compact meter follows microphone input. -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. +3. Speak, then press the shortcut again. The transcript is pasted at the cursor in that app when it is ready, even if you moved the cursor or kept typing meanwhile. +4. If you switched to another app, the focused control is not editable, or it is a password field, ClearFlow puts the transcript on the clipboard for manual paste instead. If a paste cannot be confirmed through Accessibility, the transcript also stays on the clipboard. Check the app’s status for details. + +Transcripts are cleaned up before insertion: hesitations such as “um” and “uh”, stutters and stray spacing are removed, a standalone “new line” or “new paragraph” becomes a line break, and spacing and capitalization follow the text at the cursor. Wording is not rewritten. Turn this off under Settings → General → Clean up transcripts. 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. A persistent warning appears and ClearFlow attempts to transcribe the available audio into Recent Dictations without pasting at a stale cursor. Low disk space triggers an advance warning; a sudden hardware failure cannot always be predicted. Quitting during capture or transcription asks for confirmation and retains audio. @@ -81,7 +83,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. - Audio is stored in ~/Library/Application Support/ClearFlow/Recordings with private file permissions. It is deleted after successful transcription (and history persistence when enabled) or explicit discard. Failed, interrupted or paused requests retain audio across new recordings and app restarts. Review or delete these files under Saved Recordings; no automatic expiry. Existing temporary files from older versions are not imported. -- Field content is read locally to guard insertion and is not uploaded. Known secure fields are rejected. +- Field content is read locally to confirm insertion and is not uploaded. Known secure fields are rejected. - Transcript history is saved on this Mac by default, without automatic pruning, in ~/Library/Application Support/ClearFlow/history.json. Existing explicit history-off preferences are respected. Disable it in Settings → Data & privacy and save to remove stored history; ordinary completed dictations then stay in memory only. Interrupted audio remains recoverable until discarded. Clear recent history removes transcripts, not unfinished audio. Clipboard fallback leaves text 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. diff --git a/Sources/ClearFlow/ClearFlowApp.swift b/Sources/ClearFlow/ClearFlowApp.swift index 1de3054..1bd4e45 100644 --- a/Sources/ClearFlow/ClearFlowApp.swift +++ b/Sources/ClearFlow/ClearFlowApp.swift @@ -32,7 +32,7 @@ import ClearFlowCore do { let reply = try await TranscriptionClient.transcribe(file: URL(fileURLWithPath: path), id: UUID(), endpoint: endpoint, token: token, language: "en", vocabulary: "") - print(reply.text); exit(0) + print(AppSettings.cleanUp ? TranscriptCleanup.clean(reply.text) : reply.text); exit(0) } catch { fputs("\(error.localizedDescription)\n", stderr); exit(1) } } dispatchMain() diff --git a/Sources/ClearFlow/DictationModel.swift b/Sources/ClearFlow/DictationModel.swift index c4b5218..957dce2 100644 --- a/Sources/ClearFlow/DictationModel.swift +++ b/Sources/ClearFlow/DictationModel.swift @@ -20,6 +20,7 @@ import ClearFlowCore @Published var language = AppSettings.language @Published var vocabulary = AppSettings.vocabulary @Published var saveHistory = AppSettings.saveHistory + @Published var cleanUp = AppSettings.cleanUp @Published var settingsMessage = "" @Published var hasAccessibility = AXIsProcessTrusted() @Published var microphoneGranted = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized @@ -239,6 +240,7 @@ import ClearFlowCore mode = .transcribing; status = "Turning speech into text…"; level = 0 let endpoint = AppSettings.endpoint, token = transcribeRecording == nil ? TokenStore.read() : "" let language = AppSettings.language, vocabulary = AppSettings.vocabulary + let cleanUp = AppSettings.cleanUp requestTask = Task { do { let reply: TranscriptionReply @@ -249,7 +251,8 @@ import ClearFlowCore await self?.transcriptionProgress(part: part, count: count, id: id) }) } guard !Task.isCancelled, gate.acceptResult(id) else { return } - let text = reply.text.trimmingCharacters(in: .whitespacesAndNewlines) + let raw = reply.text.trimmingCharacters(in: .whitespacesAndNewlines) + let text = cleanUp ? TranscriptCleanup.clean(raw) : raw guard !text.isEmpty else { mode = .error; status = "No speech was detected. Audio saved for recovery." recordingNotice = status; refreshRecoveries(); return @@ -273,7 +276,7 @@ import ClearFlowCore let outcome: String if interrupted { outcome = saveHistory ? "Recovered transcript saved in Recent Dictations." : "Recovered transcript is available for this session; audio retained." } else if let insertTranscript { outcome = await insertTranscript(text) } - else { outcome = await TextInsertion.insert(text, target: target, captureIssue: captureIssue) } + else { outcome = await TextInsertion.insert(text, target: target, captureIssue: captureIssue, fitToCursor: cleanUp) } guard !Task.isCancelled, currentID == id else { return } status = outcome; mode = .ready // History-off is an explicit privacy choice; retain interrupted audio until discarded. @@ -362,7 +365,7 @@ import ClearFlowCore guard !TokenStore.read().isEmpty else { settingsMessage = "Enter your private service token."; return } AppSettings.endpoint = url.absoluteString; endpoint = url.absoluteString AppSettings.language = lang; language = lang - AppSettings.vocabulary = vocabulary; AppSettings.saveHistory = saveHistory + AppSettings.vocabulary = vocabulary; AppSettings.saveHistory = saveHistory; AppSettings.cleanUp = cleanUp if saveHistory { try HistoryStore.save(history) } else { try HistoryStore.clear() } hasToken = true; settingsMessage = "Saved. Your access token is in macOS Keychain." } catch { settingsMessage = error.localizedDescription } diff --git a/Sources/ClearFlow/SettingsStore.swift b/Sources/ClearFlow/SettingsStore.swift index 242a5bc..6dc11eb 100644 --- a/Sources/ClearFlow/SettingsStore.swift +++ b/Sources/ClearFlow/SettingsStore.swift @@ -20,6 +20,10 @@ struct AppSettings { get { defaults.string(forKey: "language") ?? "" } set { defaults.set(newValue, forKey: "language") } } + static var cleanUp: Bool { + get { defaults.object(forKey: "cleanUpTranscripts") as? Bool ?? true } + set { defaults.set(newValue, forKey: "cleanUpTranscripts") } + } static var saveHistory: Bool { get { defaults.object(forKey: "saveHistory") as? Bool ?? true } set { defaults.set(newValue, forKey: "saveHistory") } diff --git a/Sources/ClearFlow/TextInsertion.swift b/Sources/ClearFlow/TextInsertion.swift index f81a1f9..bc4dd36 100644 --- a/Sources/ClearFlow/TextInsertion.swift +++ b/Sources/ClearFlow/TextInsertion.swift @@ -2,12 +2,11 @@ import AppKit import ApplicationServices import ClearFlowCore +/// The app that was in front when dictation started. Text is pasted at that app's +/// cursor when the transcript is ready, wherever the cursor is by then. struct InsertionTarget { let pid: pid_t let name: String - let element: AXUIElement - let originalValue: String? - let range: CFRange? } struct InsertionCapture { let target: InsertionTarget? @@ -41,36 +40,41 @@ struct InsertionCapture { var range = CFRange() return AXValueGetValue(value, .cfRange, &range) ? range : nil } + static func editable(_ element: AXUIElement) -> Bool { + var settable: DarwinBoolean = false + let valueSettable = AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &settable) == .success + && settable.boolValue + return Editability.allows(role: attribute(element, kAXRoleAttribute) as? String ?? "", + insideEditableContent: attribute(element, "AXEditableAncestor") != nil, + exposesTextSelection: selectedRange(element) != nil, + valueSettable: valueSettable) + } static func capture(previousApp: NSRunningApplication?) -> InsertionCapture { let trusted = AXIsProcessTrusted() let pid = DestinationPolicy.pid(frontmost: NSWorkspace.shared.frontmostApplication?.processIdentifier, previous: previousApp?.processIdentifier, own: ProcessInfo.processInfo.processIdentifier) - // Permission is checked before AX queries so its failure cannot masquerade as missing focus. - let element = trusted ? pid.flatMap { focusedElement(pid: $0) } : nil - let isSecure = element.map { secure($0) } ?? false - let role = element.flatMap { attribute($0, kAXRoleAttribute) as? String } ?? "" - let editable = ["AXTextField", "AXTextArea", "AXComboBox"].contains(role) - if let issue = DestinationPolicy.failure(accessibility: trusted, hasApp: pid != nil, - hasField: element != nil, secure: isSecure, editable: editable) { - return InsertionCapture(target: nil, issue: issue) + guard trusted else { + return InsertionCapture(target: nil, issue: DestinationPolicy.failure(accessibility: false, hasApp: true, + hasField: true, secure: false, editable: true)) + } + guard let pid else { + return InsertionCapture(target: nil, issue: DestinationPolicy.failure(accessibility: true, hasApp: false, + hasField: true, secure: false, editable: true)) } - guard let pid, let element else { return InsertionCapture(target: nil, issue: "No insertion destination.") } + // The field is checked when the transcript is ready, not now: the cursor may + // legitimately move, and apps such as web editors rebuild their elements. return InsertionCapture(target: InsertionTarget(pid: pid, - name: NSRunningApplication(processIdentifier: pid)?.localizedName ?? "your app", element: element, - originalValue: attribute(element, kAXValueAttribute) as? String, range: selectedRange(element)), issue: nil) + name: NSRunningApplication(processIdentifier: pid)?.localizedName ?? "your app"), issue: nil) } - static func insert(_ text: String, target: InsertionTarget?, captureIssue: String? = nil) async -> String { - let outcome = await attemptInsertion(text, target: target, captureIssue: captureIssue) + static func insert(_ text: String, target: InsertionTarget?, captureIssue: String? = nil, + fitToCursor: Bool = false) async -> String { + let outcome = await attemptInsertion(text, target: target, captureIssue: captureIssue, fitToCursor: fitToCursor) // Keep the destination app in front. A rejected insertion still leaves usable // text for an ordinary user-initiated paste, without opening the hub. guard !Task.isCancelled, outcome.hasPrefix("Ready to copy — ") else { return outcome } let board = NSPasteboard.general - let oldItems = board.pasteboardItems?.map { item -> NSPasteboardItem in - let copy = NSPasteboardItem() - for type in item.types { if let data = item.data(forType: type) { copy.setData(data, forType: type) } } - return copy - } ?? [] + let oldItems = snapshot(board) board.clearContents() guard board.setString(text, forType: .string) else { board.clearContents() @@ -79,7 +83,38 @@ struct InsertionCapture { } return outcome.replacingOccurrences(of: "Ready to copy — ", with: "Copied to clipboard — ", options: .anchored) } - private static func attemptInsertion(_ text: String, target: InsertionTarget?, captureIssue: String?) async -> String { + private static func snapshot(_ board: NSPasteboard) -> [NSPasteboardItem] { + board.pasteboardItems?.map { item -> NSPasteboardItem in + let copy = NSPasteboardItem() + for type in item.types { if let data = item.data(forType: type) { copy.setData(data, forType: type) } } + return copy + } ?? [] + } + /// Polls instead of sleeping a fixed time: fast when the condition is already met, + /// tolerant when an app is slow to activate or to apply a paste. + private static func waitUntil(_ timeout: Duration, _ condition: () -> Bool) async -> Bool { + let clock = ContinuousClock(), deadline = clock.now + timeout + while !condition() { + if Task.isCancelled || clock.now >= deadline { return false } + try? await Task.sleep(for: .milliseconds(25)) + } + return true + } + private static func heldModifiers() -> Bool { + !CGEventSource.flagsState(.combinedSessionState) + .intersection([.maskCommand, .maskShift, .maskAlternate, .maskControl, .maskSecondaryFn]).isEmpty + } + /// Up to a few characters on each side of the cursor, for spacing and capitalization. + private static func surroundings(of value: String?, range: CFRange?) -> (before: String, after: String) { + guard let value, let range, range.location >= 0, range.length >= 0 else { return ("", "") } + let text = value as NSString + guard range.location + range.length <= text.length else { return ("", "") } + let start = max(0, range.location - 32), end = range.location + range.length + return (text.substring(with: NSRange(location: start, length: range.location - start)), + text.substring(with: NSRange(location: end, length: min(8, text.length - end)))) + } + private static func attemptInsertion(_ text: String, target: InsertionTarget?, captureIssue: String?, + fitToCursor: Bool) async -> String { guard AXIsProcessTrusted() else { return "Ready to copy — enable Accessibility for ClearFlow in System Settings to insert automatically." } @@ -88,43 +123,39 @@ struct InsertionCapture { let ownPID = ProcessInfo.processInfo.processIdentifier if NSWorkspace.shared.frontmostApplication?.processIdentifier == ownPID { NSRunningApplication(processIdentifier: target.pid)?.activate() - try? await Task.sleep(for: .milliseconds(180)) } - guard !Task.isCancelled, NSWorkspace.shared.frontmostApplication?.processIdentifier == target.pid, - let focused = focusedElement(pid: target.pid), CFEqual(focused, target.element), !secure(focused) - else { return "Ready to copy — focus changed, so nothing was inserted." } - if let original = target.originalValue, - (attribute(focused, kAXValueAttribute) as? String) != original { - return "Ready to copy — the text field changed while you spoke." + let frontmost = await waitUntil(.seconds(1)) { + NSWorkspace.shared.frontmostApplication?.processIdentifier == target.pid } - if let old = target.range { - guard let current = selectedRange(focused), old.location == current.location, old.length == current.length else { - return "Ready to copy — the cursor moved while you spoke." - } + guard !Task.isCancelled else { return "Cancelled — transcript kept." } + guard frontmost else { return "Ready to copy — you switched away from \(target.name), so nothing was inserted." } + guard let focused = focusedElement(pid: target.pid) else { + return "Ready to copy — no text field is focused in \(target.name)." } - guard target.range != nil, target.originalValue != nil else { - return "Ready to copy — this app does not expose enough cursor information for automatic insertion." + guard !secure(focused) else { return "Ready to copy — automatic insertion is disabled in password fields." } + guard editable(focused) else { + return "Ready to copy — the focused control in \(target.name) is not an editable text field." } - var expected: String? - if let value = target.originalValue, let range = target.range, - range.location >= 0, range.length >= 0, - range.location + range.length <= (value as NSString).length { - expected = (value as NSString).replacingCharacters(in: NSRange(location: range.location, length: range.length), with: text) + // A modifier still held from the shortcut would turn Command-V into another command. + _ = await waitUntil(.milliseconds(1500)) { !heldModifiers() } + guard !Task.isCancelled else { return "Cancelled — transcript kept." } + let before = attribute(focused, kAXValueAttribute) as? String + let range = selectedRange(focused) + var text = text + if fitToCursor { + let context = surroundings(of: before, range: range) + text = TranscriptCleanup.fit(text, before: context.before, after: context.after) } - // A no-op replacement already has the desired content; don't enqueue a paste. - if expected == target.originalValue { return "Inserted into \(target.name) — text already matched." } + let expected = PastePrediction.result(of: text, in: before, + location: range.map { $0.location }, length: range.map { $0.length }) + if let expected, expected == before { return "Inserted into \(target.name) — text already matched." } // Some editors report a successful AXSelectedText write without inserting // anything. Use the editor's normal paste action instead of that silent no-op. - guard !Task.isCancelled else { return "Cancelled — transcript kept." } guard let down = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: true), let up = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: false) else { return "Ready to copy — macOS could not create the paste event." } let board = NSPasteboard.general - let oldItems = board.pasteboardItems?.map { item -> NSPasteboardItem in - let copy = NSPasteboardItem() - for type in item.types { if let data = item.data(forType: type) { copy.setData(data, forType: type) } } - return copy - } ?? [] + let oldItems = snapshot(board) board.clearContents() guard board.setString(text, forType: .string) else { board.clearContents(); if !oldItems.isEmpty { board.writeObjects(oldItems) } @@ -133,13 +164,15 @@ struct InsertionCapture { let ownedChange = board.changeCount down.flags = .maskCommand; up.flags = .maskCommand down.post(tap: .cghidEventTap); up.post(tap: .cghidEventTap) - try? await Task.sleep(for: .milliseconds(500)) - let verified = expected != nil && (attribute(focused, kAXValueAttribute) as? String) == expected + var verified = false + if let expected { + verified = await waitUntil(.milliseconds(750)) { (attribute(focused, kAXValueAttribute) as? String) == expected } + } if PasteRestoration.allowed(expected: expected, observed: attribute(focused, kAXValueAttribute) as? String, clipboardUnchanged: board.changeCount == ownedChange) { board.clearContents() if !oldItems.isEmpty { board.writeObjects(oldItems) } } - return verified ? "Inserted into \(target.name)" : "Paste sent to \(target.name) — check the destination. Transcript remains on the clipboard." + return verified ? "Inserted into \(target.name)" : "Pasted into \(target.name). The transcript is also on the clipboard." } } diff --git a/Sources/ClearFlow/Views.swift b/Sources/ClearFlow/Views.swift index 8011a02..5ed2c69 100644 --- a/Sources/ClearFlow/Views.swift +++ b/Sources/ClearFlow/Views.swift @@ -373,6 +373,10 @@ private struct FlowSettings: View { Text("Select a disposable text field in another app, return here, then test. Inserts: ClearFlow insertion test.") .font(.system(size: 11)).foregroundStyle(FlowTheme.muted).padding(.top, 8) rule() + Toggle("Clean up transcripts", isOn: $model.cleanUp).font(.system(size: 14, weight: .medium)) + Text("Removes um and uh, stutters and stray spacing, turns “new line” and “new paragraph” into line breaks, and matches spacing and capitalization to the text at your cursor. Wording is not changed. Click Save changes to apply.") + .font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(3).padding(.top, 8) + rule() Text("Dictation language").font(.system(size: 14, weight: .medium)) TextField("Auto-detect, or en / es / fr", text: $model.language) .textFieldStyle(.roundedBorder).padding(.top, 10) diff --git a/Sources/ClearFlowCore/Insertion.swift b/Sources/ClearFlowCore/Insertion.swift new file mode 100644 index 0000000..13f7467 --- /dev/null +++ b/Sources/ClearFlowCore/Insertion.swift @@ -0,0 +1,25 @@ +import Foundation + +/// Decides from accessibility facts whether Command-V can insert text at a cursor. +public enum Editability { + static let textRoles: Set = ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField"] + /// - Parameters: + /// - insideEditableContent: the element reports an editable ancestor, as web + /// `contenteditable` editors (Slack, Notion, Gmail, ChatGPT) do. + /// - exposesTextSelection: the element reports a text selection range; together + /// with a settable value this identifies custom text views but not sliders. + public static func allows(role: String, insideEditableContent: Bool, + exposesTextSelection: Bool, valueSettable: Bool) -> Bool { + textRoles.contains(role) || insideEditableContent || (exposesTextSelection && valueSettable) + } +} + +/// The field value a successful paste should produce, when the app exposes enough to know. +public enum PastePrediction { + public static func result(of text: String, in value: String?, location: Int?, length: Int?) -> String? { + guard let value, let location, let length, location >= 0, length >= 0 else { return nil } + let current = value as NSString + guard location + length <= current.length else { return nil } + return current.replacingCharacters(in: NSRange(location: location, length: length), with: text) + } +} diff --git a/Sources/ClearFlowCore/TranscriptCleanup.swift b/Sources/ClearFlowCore/TranscriptCleanup.swift new file mode 100644 index 0000000..228c618 --- /dev/null +++ b/Sources/ClearFlowCore/TranscriptCleanup.swift @@ -0,0 +1,105 @@ +import Foundation + +/// Deterministic, instant cleanup of raw speech-to-text output. It removes speech +/// disfluencies and applies spoken layout commands without rewriting wording. +public enum TranscriptCleanup { + private static func regex(_ pattern: String) -> NSRegularExpression { + // Patterns are compile-time constants; a failure is a programming error. + try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) + } + private static func replace(_ text: String, _ pattern: NSRegularExpression, _ template: String) -> String { + pattern.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text), withTemplate: template) + } + // Hesitation sounds only; words such as "like" or "so" often carry meaning. + private static let filler = regex(#"(?:,\s*)?\b(?:u+m+|u+h+m*|e+r+m+|h+m{2,})\b(?:\s*,)?"#) + // Stutters. Grammatical or emphatic repeats ("had had", "very very") are kept. + private static let repeated = regex(#"\b(?!(?:that|had|is|very|really|no|yeah|bye|ha)\b)([a-z']+)(?:\s+\1\b)+"#) + // Layout commands must stand alone as a sentence, so "a new line of products" is kept. + private static let command = regex(#"(^|[.!?,;:]|\n)[ \t]*\bnew (line|paragraph)\b[ \t]*[.!?,;:]?(?=\s|$)"#) + private static let spaceBeforePunctuation = regex(#"[ \t]+([,.!?;:])"#) + private static let repeatedCommas = regex(#",(?:\s*,)+"#) + private static let commaBeforeStop = regex(#",\s*([.!?])"#) + private static let orphanStop = regex(#"([.!?])(?:[ \t]+[.,](?!\d))+"#) + private static let horizontalSpace = regex(#"[ \t]{2,}"#) + private static let spaceAroundBreak = regex(#"[ \t]*\n[ \t]*"#) + private static let removed: Character = "\u{2}" + + public static func clean(_ raw: String) -> String { + var text = raw.replacingOccurrences(of: "\r\n", with: "\n") + text = replace(text, command, "$1\u{1}$2\u{1}") + text = text.replacingOccurrences(of: "\u{1}line\u{1}", with: "\n", options: .caseInsensitive) + .replacingOccurrences(of: "\u{1}paragraph\u{1}", with: "\n\n", options: .caseInsensitive) + text = capitalizeAfterRemovals(replace(text, filler, String(removed))) + text = text.replacingOccurrences(of: String(removed), with: " ") + text = replace(text, orphanStop, "$1") + text = replace(text, repeated, "$1") + text = replace(text, spaceBeforePunctuation, "$1") + text = replace(text, repeatedCommas, ",") + text = replace(text, commaBeforeStop, "$1") + text = replace(text, horizontalSpace, " ") + text = replace(text, spaceAroundBreak, "\n") + while text.contains("\n\n\n") { text = text.replacingOccurrences(of: "\n\n\n", with: "\n\n") } + // A filler removed at the start of a line can leave stray leading punctuation. + return text.split(separator: "\n", omittingEmptySubsequences: false).map { line -> String in + var line = Substring(line) + while let first = line.first, first == "," || first == " " || (first == "." && line.dropFirst().first == " ") { + line = line.dropFirst() + } + return String(line) + }.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + } + + /// Capitalizes the first letter of the text and of each line, and a word that + /// starts a sentence because a filler before it was removed ("Okay. Um, so" → + /// "Okay. So"). Other capitalization is the speech model's and is left alone. + static func capitalizeAfterRemovals(_ text: String) -> String { + var result = "" + var capitalizeNext = true + var sentenceStart = true + for character in text { + if character == removed { + if sentenceStart { capitalizeNext = true } + result.append(character); continue + } + if capitalizeNext, character.isLetter { + result += character.uppercased(); capitalizeNext = false; sentenceStart = false; continue + } + result.append(character) + if character == "\n" { capitalizeNext = true; sentenceStart = true; continue } + if character.isWhitespace { continue } + sentenceStart = ".!?".contains(character) + if character.isLetter || character.isNumber { capitalizeNext = false } + } + return result + } + + /// Adapts cleaned text to the characters around the cursor: spacing, and + /// continuing a sentence in lowercase without a premature full stop. + public static func fit(_ text: String, before: String, after: String) -> String { + guard !text.isEmpty else { return text } + var text = text + let previous = before.last + let previousVisible = before.last { !$0.isWhitespace } + let following = after.first + let nextVisible = after.first { !$0.isWhitespace } + let continuing = previousVisible.map { $0.isLetter || $0.isNumber || ",;".contains($0) } ?? false + if continuing, !text.contains("\n"), let first = text.split(separator: " ").first, + first.count > 1 || first != "I", !isProperCased(first) { + text = first.prefix(1).lowercased() + text.dropFirst() + } + if let nextVisible, nextVisible.isLowercase, text.hasSuffix("."), !text.hasSuffix("..") { + text.removeLast() + } + if let previous, !previous.isWhitespace, !"([{\"'“‘/-".contains(previous), !text.hasPrefix("\n") { + text = " " + text + } + if let following, following.isLetter || following.isNumber { text += " " } + return text + } + /// Words such as "I'm", "NASA" or "iPhone" keep their capitalization mid-sentence. + private static func isProperCased(_ word: Substring) -> Bool { + let letters = word.filter { $0.isLetter } + if letters.first == "I", word.count > 1, word.dropFirst().first.map({ "'’".contains($0) }) == true { return true } + return letters.dropFirst().contains { $0.isUppercase } || !(letters.first?.isUppercase ?? false) + } +} diff --git a/Tests/ClearFlowCoreTests/SessionGateTests.swift b/Tests/ClearFlowCoreTests/SessionGateTests.swift index e5ee9c7..465052b 100644 --- a/Tests/ClearFlowCoreTests/SessionGateTests.swift +++ b/Tests/ClearFlowCoreTests/SessionGateTests.swift @@ -106,6 +106,58 @@ final class SessionGateTests { XCTAssertFalse(PasteRestoration.allowed(expected: "hello", observed: "hello", clipboardUnchanged: false), "Never replace a newer user copy") XCTAssertTrue(PasteRestoration.allowed(expected: "hello", observed: "hello", clipboardUnchanged: true)) } + func testEditableFieldsIncludeWebAndCustomEditors() { + XCTAssertTrue(Editability.allows(role: "AXTextArea", insideEditableContent: false, exposesTextSelection: false, valueSettable: false)) + XCTAssertTrue(Editability.allows(role: "AXGroup", insideEditableContent: true, exposesTextSelection: false, valueSettable: false), + "contenteditable web editors report an editable ancestor") + XCTAssertTrue(Editability.allows(role: "AXUnknown", insideEditableContent: false, exposesTextSelection: true, valueSettable: true)) + XCTAssertFalse(Editability.allows(role: "AXSlider", insideEditableContent: false, exposesTextSelection: false, valueSettable: true), + "a settable non-text value is not a cursor") + XCTAssertFalse(Editability.allows(role: "AXButton", insideEditableContent: false, exposesTextSelection: false, valueSettable: false)) + } + func testPastePredictionUsesTheCursorAtPasteTime() { + XCTAssertEqual(PastePrediction.result(of: "big ", in: "a dog", location: 2, length: 0), "a big dog") + XCTAssertEqual(PastePrediction.result(of: "cat", in: "a dog", location: 2, length: 3), "a cat") + XCTAssertEqual(PastePrediction.result(of: "é", in: "👍", location: 2, length: 0), "👍é") + XCTAssertNil(PastePrediction.result(of: "x", in: "abc", location: 2, length: 5)) + XCTAssertNil(PastePrediction.result(of: "x", in: nil, location: 0, length: 0)) + XCTAssertNil(PastePrediction.result(of: "x", in: "abc", location: nil, length: nil)) + } + func testCleanupRemovesDisfluenciesWithoutRewording() { + func check(_ raw: String, _ expected: String, line: Int = #line) { + let actual = TranscriptCleanup.clean(raw) + XCTAssertTrue(actual == expected, "\(raw.debugDescription) -> \(actual.debugDescription), expected \(expected.debugDescription)", line: line) + } + check("Hey, um, can you send me the notes from yesterday's meeting? I think we need to, uh, review the budget before Friday.", + "Hey can you send me the notes from yesterday's meeting? I think we need to review the budget before Friday.") + check("Um, so we should ship it.", "So we should ship it.") + check("Okay. Uh, so the plan works.", "Okay. So the plan works.") + check("That's it, um.", "That's it.") + check("Okay. Um. Next step.", "Okay. Next step.") + check("I I think the the plan is fine.", "I think the plan is fine.") + check("I know that that is true and I had had enough. It's very very good.", + "I know that that is true and I had had enough. It's very very good.") + check(" Extra spaces , here . ", "Extra spaces, here.") + check("Dear Sam, new line, thanks for the update. New paragraph. See you soon.", + "Dear Sam,\nThanks for the update.\n\nSee you soon.") + check("We need a new line of products.", "We need a new line of products.") + check("Version 3.5 costs $4.99 at 3 p.m. on the U.S. site, e.g. today.", + "Version 3.5 costs $4.99 at 3 p.m. on the U.S. site, e.g. today.") + check("Summary, umbrella and humble words stay.", "Summary, umbrella and humble words stay.") + check("Um", "") + } + func testCleanupFitsTextAroundTheCursor() { + XCTAssertEqual(TranscriptCleanup.fit("Hello there.", before: "", after: ""), "Hello there.") + XCTAssertEqual(TranscriptCleanup.fit("Next point.", before: "Done.", after: ""), " Next point.") + XCTAssertEqual(TranscriptCleanup.fit("Next point.", before: "Done. ", after: ""), "Next point.") + XCTAssertEqual(TranscriptCleanup.fit("The big one.", before: "I want", after: ""), " the big one.") + XCTAssertEqual(TranscriptCleanup.fit("Really big.", before: "a ", after: "dog"), "really big ") + XCTAssertEqual(TranscriptCleanup.fit("I think so.", before: "and", after: ""), " I think so.") + XCTAssertEqual(TranscriptCleanup.fit("I'm in.", before: "and", after: ""), " I'm in.") + XCTAssertEqual(TranscriptCleanup.fit("NASA launched.", before: "and", after: ""), " NASA launched.") + XCTAssertEqual(TranscriptCleanup.fit("Hello.", before: "(", after: ")"), "Hello.") + XCTAssertEqual(TranscriptCleanup.fit("Line one.\nLine two.", before: "Intro", after: ""), " Line one.\nLine two.") + } func testEndpointRejectsCredentialAndQueryLeakage() { XCTAssertEqual(Endpoint.validated("https://example.workers.dev/")?.absoluteString, "https://example.workers.dev") XCTAssertNil(Endpoint.validated("http://public.example")) @@ -128,6 +180,10 @@ final class SessionGateTests { tests.testClipboardMustWaitForObservedInsertion() tests.testMeterTracksActualInputAndReturnsToSilence() tests.testDestinationUsesLiveFocusAndReportsPermissionFirst() + tests.testEditableFieldsIncludeWebAndCustomEditors() + tests.testPastePredictionUsesTheCursorAtPasteTime() + tests.testCleanupRemovesDisfluenciesWithoutRewording() + tests.testCleanupFitsTextAroundTheCursor() if failures > 0 { print("\(failures) failures"); exit(1) } print("PASS: session lifecycle, cancellation/stale result, duplicate result, endpoint validation") } diff --git a/local-stt/README.md b/local-stt/README.md index 7628abc..a7f138f 100644 --- a/local-stt/README.md +++ b/local-stt/README.md @@ -76,7 +76,7 @@ Only one upload/inference runs at a time; overlap returns 429. Audio stays in pr - 401: configure the client with the token belonging to this runtime. - 429: wait for the current recording to finish. - Permission errors on another drive: approve macOS Files & Folders access normally. -- No insertion: check Accessibility, select an editable field before starting, and keep its content/cursor unchanged. Use clipboard fallback when needed. +- No insertion: check Accessibility and keep the app you dictated into in front until the transcript arrives. Use clipboard fallback when needed. ```sh python3 -m unittest discover -s local-stt -v