|
| 1 | +// FailedAudioDump.swift |
| 2 | +// VocaMac |
| 3 | +// |
| 4 | +// Saves the audio behind a transcription that came back empty, so a failure |
| 5 | +// that only happens with a real microphone can be replayed through |
| 6 | +// `--transcribe-file` and debugged offline. |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +/// Writes the samples behind an empty transcription to a WAV file. |
| 11 | +/// |
| 12 | +/// Off unless the user turns it on, because it puts recorded speech on disk: |
| 13 | +/// |
| 14 | +/// defaults write com.vocamac.app vocamac.debug.saveFailedAudio -bool true |
| 15 | +enum FailedAudioDump { |
| 16 | + |
| 17 | + static let preferenceKey = "vocamac.debug.saveFailedAudio" |
| 18 | + |
| 19 | + /// Most recordings kept before the oldest are removed. |
| 20 | + static let maximumFiles = 20 |
| 21 | + |
| 22 | + static var directory: URL { |
| 23 | + VocaLogger.logDirectory().appendingPathComponent("failed-audio", isDirectory: true) |
| 24 | + } |
| 25 | + |
| 26 | + static var isEnabled: Bool { |
| 27 | + UserDefaults.standard.bool(forKey: preferenceKey) |
| 28 | + } |
| 29 | + |
| 30 | + /// Build a dump filename that cannot collide within the same second. |
| 31 | + static func makeFilename( |
| 32 | + model: String, |
| 33 | + date: Date = Date(), |
| 34 | + uniqueID: String = UUID().uuidString |
| 35 | + ) -> String { |
| 36 | + let stamp = ISO8601DateFormatter.dumpFormatter.string(from: date) |
| 37 | + let token = String(uniqueID.replacingOccurrences(of: "-", with: "").prefix(8)) |
| 38 | + let safeModel = model |
| 39 | + .replacingOccurrences(of: "/", with: "-") |
| 40 | + .replacingOccurrences(of: ":", with: "-") |
| 41 | + return "\(stamp)-\(token)-\(safeModel).wav" |
| 42 | + } |
| 43 | + |
| 44 | + /// Save `samples` if the user asked for dumps. Returns the file written. |
| 45 | + @discardableResult |
| 46 | + static func save(_ samples: [Float], model: String, sampleRate: Int = 16_000) -> URL? { |
| 47 | + guard isEnabled, !samples.isEmpty else { return nil } |
| 48 | + |
| 49 | + let url = directory.appendingPathComponent(makeFilename(model: model)) |
| 50 | + |
| 51 | + do { |
| 52 | + try FileManager.default.createDirectory( |
| 53 | + at: directory, withIntermediateDirectories: true |
| 54 | + ) |
| 55 | + try wavData(from: samples, sampleRate: sampleRate).write(to: url) |
| 56 | + pruneOldest() |
| 57 | + VocaLogger.info(.sherpaService, "Saved the failed recording to \(url.path)") |
| 58 | + return url |
| 59 | + } catch { |
| 60 | + VocaLogger.error(.sherpaService, "Could not save the failed recording: \(error)") |
| 61 | + return nil |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + /// 16-bit mono PCM in a canonical 44-byte WAV container. |
| 66 | + static func wavData(from samples: [Float], sampleRate: Int) -> Data { |
| 67 | + let bytesPerSample = 2 |
| 68 | + let dataBytes = samples.count * bytesPerSample |
| 69 | + var data = Data(capacity: 44 + dataBytes) |
| 70 | + |
| 71 | + func append<T: FixedWidthInteger>(_ value: T) { |
| 72 | + withUnsafeBytes(of: value.littleEndian) { data.append(contentsOf: $0) } |
| 73 | + } |
| 74 | + |
| 75 | + data.append(contentsOf: Array("RIFF".utf8)) |
| 76 | + append(UInt32(36 + dataBytes)) |
| 77 | + data.append(contentsOf: Array("WAVE".utf8)) |
| 78 | + |
| 79 | + data.append(contentsOf: Array("fmt ".utf8)) |
| 80 | + append(UInt32(16)) // PCM header size |
| 81 | + append(UInt16(1)) // PCM |
| 82 | + append(UInt16(1)) // mono |
| 83 | + append(UInt32(sampleRate)) |
| 84 | + append(UInt32(sampleRate * bytesPerSample)) // byte rate |
| 85 | + append(UInt16(bytesPerSample)) // block align |
| 86 | + append(UInt16(16)) // bits per sample |
| 87 | + |
| 88 | + data.append(contentsOf: Array("data".utf8)) |
| 89 | + append(UInt32(dataBytes)) |
| 90 | + for sample in samples { |
| 91 | + append(Int16(max(-1, min(1, sample)) * 32_767)) |
| 92 | + } |
| 93 | + return data |
| 94 | + } |
| 95 | + |
| 96 | + /// Keep the newest `maximumFiles` dumps so this cannot fill the disk. |
| 97 | + private static func pruneOldest() { |
| 98 | + let fileManager = FileManager.default |
| 99 | + guard let files = try? fileManager.contentsOfDirectory( |
| 100 | + at: directory, includingPropertiesForKeys: [.creationDateKey] |
| 101 | + ) else { return } |
| 102 | + |
| 103 | + let sorted = files |
| 104 | + .filter { $0.pathExtension == "wav" } |
| 105 | + .sorted { left, right in |
| 106 | + let leftDate = (try? left.resourceValues(forKeys: [.creationDateKey]))?.creationDate |
| 107 | + let rightDate = (try? right.resourceValues(forKeys: [.creationDateKey]))?.creationDate |
| 108 | + return (leftDate ?? .distantPast) > (rightDate ?? .distantPast) |
| 109 | + } |
| 110 | + |
| 111 | + for file in sorted.dropFirst(maximumFiles) { |
| 112 | + try? fileManager.removeItem(at: file) |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +private extension ISO8601DateFormatter { |
| 118 | + /// Colons are legal in HFS+ paths but confuse shell completion and tools. |
| 119 | + static let dumpFormatter: ISO8601DateFormatter = { |
| 120 | + let formatter = ISO8601DateFormatter() |
| 121 | + formatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime] |
| 122 | + formatter.timeZone = .current |
| 123 | + return formatter |
| 124 | + }() |
| 125 | +} |
0 commit comments