-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStream.swift
More file actions
317 lines (257 loc) · 10.9 KB
/
Stream.swift
File metadata and controls
317 lines (257 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import ArgumentParser
import AVFoundation
import FluidAudio
import Foundation
/// Thread-safe state for tracking incremental transcript output.
private actor StreamState {
private var lastFullTranscript = ""
private var printedLength = 0
/// Given the full accumulated transcript, return only the new portion.
/// Handles model revisions by finding the longest common prefix.
func getNewText(_ fullTranscript: String) -> String? {
let text = fullTranscript.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
guard text != lastFullTranscript else { return nil }
lastFullTranscript = text
// Find how much of the text we've already printed
if text.count > printedLength {
let newPortion = String(text.dropFirst(printedLength)).trimmingCharacters(in: .whitespaces)
if !newPortion.isEmpty {
printedLength = text.count
return newPortion
}
}
return nil
}
/// Get the live preview (last N chars of full transcript).
func getPreview(_ fullTranscript: String, maxLen: Int = 100) -> String? {
let text = fullTranscript.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil }
guard text != lastFullTranscript else { return nil }
return String(text.suffix(maxLen))
}
}
struct Stream: AsyncParsableCommand {
static let configuration = CommandConfiguration(
abstract: "Stream live audio transcription from microphone."
)
@Option(name: .long, help: "Output format: text or jsonl.")
var format: StreamOutputFormat = .text
@Option(name: .long, help: "Streaming engine: default (multilingual, higher latency) or nemotron (English-only, low latency ~560ms).")
var engine: StreamEngine = .default
@Option(name: .shortAndLong, help: "Also save output to file.")
var output: String?
@Flag(name: .long, help: "Show status information.")
var verbose: Bool = false
func run() async throws {
switch engine {
case .nemotron:
try await runNemotron()
case .default:
try await runSlidingWindow()
}
}
// MARK: - Nemotron Engine (English-only, low latency)
private func runNemotron() async throws {
log("Initializing streaming ASR (Nemotron 560ms, English-only)...")
log("Downloading model if needed (first run only, ~600MB)...")
let engine = StreamingAsrEngineFactory.create(.nemotron560ms)
do {
try await engine.loadModels()
} catch {
log("Model loading failed: \(error.localizedDescription)")
log("Cleaning cache and retrying download...")
let cacheDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
.appendingPathComponent("FluidAudio/Models/nemotron-streaming")
try? FileManager.default.removeItem(at: cacheDir)
let freshEngine = StreamingAsrEngineFactory.create(.nemotron560ms)
try await freshEngine.loadModels()
log("Retry successful.")
try await runNemotronWithEngine(freshEngine)
return
}
log("Models loaded.")
try await runNemotronWithEngine(engine)
}
private func runNemotronWithEngine(_ engine: any StreamingAsrEngine) async throws {
let audioEngine = AVAudioEngine()
let inputNode = audioEngine.inputNode
let inputFormat = inputNode.outputFormat(forBus: 0)
if verbose {
log("Microphone: \(inputFormat.sampleRate)Hz, \(inputFormat.channelCount) ch")
}
let startTime = Date()
let state = StreamState()
let fmt = format
var outputFile: FileHandle? = nil
if let outputPath = output {
FileManager.default.createFile(atPath: outputPath, contents: nil)
outputFile = FileHandle(forWritingAtPath: outputPath)
}
// Capture file handle for sendable closure
nonisolated(unsafe) let outFile = outputFile
// Partial callback — fires after each 560ms chunk with the full accumulated transcript.
// We diff to find new text and emit only the delta.
await engine.setPartialTranscriptCallback { fullTranscript in
Task {
let elapsed = Date().timeIntervalSince(startTime)
switch fmt {
case .text:
// Show live preview on stderr (ephemeral, overwritten)
let preview = String(fullTranscript.trimmingCharacters(in: .whitespaces).suffix(100))
if !preview.isEmpty {
let ts = formatStreamTimestamp(elapsed)
FileHandle.standardError.write(Data("\r\u{1B}[K[\(ts)] \(preview)".utf8))
}
case .jsonl:
break
}
// Emit new portion to stdout
if let newText = await state.getNewText(fullTranscript) {
let ts = formatStreamTimestamp(elapsed)
let line: String
switch fmt {
case .text:
FileHandle.standardError.write(Data("\r\u{1B}[K".utf8))
line = "[\(ts)] \(newText)"
case .jsonl:
let jsonObj: [String: Any] = [
"time": round(elapsed * 10) / 10,
"text": newText,
]
if let data = try? JSONSerialization.data(withJSONObject: jsonObj, options: [.sortedKeys]),
let jsonStr = String(data: data, encoding: .utf8) {
line = jsonStr
} else {
return
}
}
print(line)
fflush(stdout)
if let file = outFile {
file.write(Data((line + "\n").utf8))
}
}
}
}
setupSignalHandler()
inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { buffer, _ in
nonisolated(unsafe) let buf = buffer
do { try engine.appendAudio(buf) } catch {}
}
try audioEngine.start()
log("Listening (English, low latency)... press Ctrl+C to stop")
// Processing loop — drives the engine to process buffered audio
while true {
try await engine.processBufferedAudio()
try await Task.sleep(nanoseconds: 50_000_000) // 50ms
}
}
// MARK: - SlidingWindow Engine (Multilingual, default)
private func runSlidingWindow() async throws {
log("Initializing streaming ASR (Parakeet TDT v3, multilingual)...")
log("Downloading model if needed (first run only, ~600MB)...")
let streamManager = SlidingWindowAsrManager(config: .streaming)
try await streamManager.start(source: .microphone)
log("Models loaded.")
let audioEngine = AVAudioEngine()
let inputNode = audioEngine.inputNode
let inputFormat = inputNode.outputFormat(forBus: 0)
if verbose {
log("Microphone: \(inputFormat.sampleRate)Hz, \(inputFormat.channelCount) ch")
}
let startTime = Date()
var outputFile: FileHandle? = nil
var lastConfirmedText = ""
var lastVolatileText = ""
if let outputPath = output {
FileManager.default.createFile(atPath: outputPath, contents: nil)
outputFile = FileHandle(forWritingAtPath: outputPath)
}
setupSignalHandler()
inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { buffer, _ in
nonisolated(unsafe) let buf = buffer
streamManager.streamAudio(buf)
}
try audioEngine.start()
log("Listening (multilingual)... press Ctrl+C to stop")
let updates = await streamManager.transcriptionUpdates
for await update in updates {
let text = update.text.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { continue }
let elapsed = Date().timeIntervalSince(startTime)
if update.isConfirmed {
guard text != lastConfirmedText else { continue }
lastConfirmedText = text
lastVolatileText = ""
emitLine(text: text, elapsed: elapsed, outputFile: outputFile)
} else {
guard text != lastVolatileText else { continue }
lastVolatileText = text
switch format {
case .text:
let ts = formatStreamTimestamp(elapsed)
let preview = String(text.suffix(100))
FileHandle.standardError.write(Data("\r\u{1B}[K[\(ts)] \(preview)".utf8))
case .jsonl:
break
}
}
}
audioEngine.stop()
inputNode.removeTap(onBus: 0)
_ = try await streamManager.finish()
}
// MARK: - Helpers
private func emitLine(text: String, elapsed: Double, outputFile: FileHandle?) {
let line: String
switch format {
case .text:
let ts = formatStreamTimestamp(elapsed)
FileHandle.standardError.write(Data("\r\u{1B}[K".utf8))
line = "[\(ts)] \(text)"
case .jsonl:
let jsonObj: [String: Any] = [
"time": round(elapsed * 10) / 10,
"text": text,
]
if let data = try? JSONSerialization.data(withJSONObject: jsonObj, options: [.sortedKeys]),
let jsonStr = String(data: data, encoding: .utf8) {
line = jsonStr
} else {
return
}
}
print(line)
fflush(stdout)
if let file = outputFile {
file.write(Data((line + "\n").utf8))
}
}
private func setupSignalHandler() {
signal(SIGINT) { _ in
FileHandle.standardError.write(Data("\n".utf8))
Darwin.exit(0)
}
}
private func log(_ message: String) {
FileHandle.standardError.write(Data("[scribe] \(message)\n".utf8))
}
}
private func formatStreamTimestamp(_ seconds: Double) -> String {
let totalSeconds = Int(seconds)
let hours = totalSeconds / 3600
let minutes = (totalSeconds % 3600) / 60
let secs = totalSeconds % 60
if hours > 0 {
return String(format: "%02d:%02d:%02d", hours, minutes, secs)
}
return String(format: "%02d:%02d", minutes, secs)
}
enum StreamOutputFormat: String, ExpressibleByArgument, CaseIterable, Sendable {
case text, jsonl
}
enum StreamEngine: String, ExpressibleByArgument, CaseIterable, Sendable {
case `default`
case nemotron
}