Branchwell

Voxley / app · voxley.si / Tests / VoxleyTests / AppleModelTests.swift

1import AVFoundation
2import Foundation
3import Speech
4import Testing
5@testable import Voxley
6
7private let fixture = ProcessInfo.processInfo.environment["VOXLEY_TEST_AUDIO"]
8
9@Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models"))
10func recorderMeterReflectsMicrophoneAmplitude() async throws {
11 let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1))
12 let locale = try await AppleModels.prepareSpeech(for: "en-US")
13 let module = SpeechTranscriber(locale: locale, preset: .progressiveTranscription)
14 let output = try #require(await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module]))
15 let (_, audio) = AsyncThrowingStream<AnalyzerInput, Error>.makeStream()
16 let (readings, meter) = AsyncStream<WaveformFrame>.makeStream()
17 let tap = try AudioTap(input: format, output: output, continuation: audio) { meter.yield($0) }
18 let framesPerColumn = 224 // 14 ms at 16 kHz.
19 let split = 4 * framesPerColumn + framesPerColumn / 2
20 for range in [0..<split, split..<(12 * framesPerColumn)] {
21 let input = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(range.count)))
22 input.frameLength = AVAudioFrameCount(range.count)
23 let samples = try #require(input.floatChannelData?[0])
24 for (index, frame) in range.enumerated() {
25 samples[index] = (4..<8).contains(frame / framesPerColumn) ? (frame.isMultiple(of: 2) ? -0.125 : 0.25) : 0
26 }
27 let bufferStart = 100 + Double(range.lowerBound) / format.sampleRate
28 let time = AVAudioTime(hostTime: AVAudioTime.hostTime(forSeconds: bufferStart),
29 sampleTime: Int64(range.lowerBound), atRate: format.sampleRate)
30 tap.block(input, time)
31 }
32 meter.finish()
33 audio.finish()
34
35 var iterator = readings.makeAsyncIterator()
36 let initial = try #require(await iterator.next())
37 let waveform = try #require(await iterator.next())
38 #expect(initial.peaks == MicrophoneWaveform.silence)
39 #expect(waveform.peaks.count > MicrophoneWaveform.columnCount)
40 #expect(waveform.peaks.suffix(8).prefix(4).allSatisfy { $0 == WaveformPeak(low: -0.125, high: 0.25) })
41 #expect(waveform.peaks.suffix(4).allSatisfy { $0 == WaveformPeak() })
42
43 // A buffer can replace the history without changing where a shared peak appears on screen.
44 let sameDisplayTime = 100.17
45 let oldEdge = initial.rightEdge(at: sameDisplayTime)
46 let newEdge = waveform.rightEdge(at: sameDisplayTime)
47 #expect(abs(oldEdge - newEdge - 8) < 0.001)
48 let nextDisplayFrame = waveform.rightEdge(at: sameDisplayTime + 1.0 / 60)
49 #expect(abs(nextDisplayFrame - newEdge - (1.0 / 60) / 0.014) < 0.001)
50}
51
52@Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models"))
53func appleSpeechRecognizesAnActualRecording() async throws {
54 let url = URL(filePath: try #require(fixture))
55 let file = try AVAudioFile(forReading: url)
56 let locale = try await AppleModels.prepareSpeech(for: "en-US")
57 let module = SpeechTranscriber(locale: locale, preset: .transcription)
58 let analyzer = SpeechAnalyzer(modules: [module])
59 let results = Task { try await AppleModels.collect(module) }
60 defer { results.cancel() }
61 do {
62 let end = try #require(try await analyzer.analyzeSequence(from: file))
63 try await analyzer.finalizeAndFinish(through: end)
64 let transcript = try await results.value
65 #expect(transcript.localizedCaseInsensitiveContains("purple"))
66 #expect(transcript.localizedCaseInsensitiveContains("elephant"))
67 print("Apple Speech (file): \(transcript)")
68 } catch {
69 await analyzer.cancelAndFinishNow()
70 throw error
71 }
72}
73
74@Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models"))
75func appleSpeechRecognizesProgressiveAudioThroughCaptureConverter() async throws {
76 let url = URL(filePath: try #require(fixture))
77 let file = try AVAudioFile(forReading: url)
78 let locale = try await AppleModels.prepareSpeech(for: "en-US")
79 let module = SpeechTranscriber(locale: locale, preset: .progressiveTranscription)
80 let format = try #require(await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module]))
81 let analyzer = SpeechAnalyzer(modules: [module])
82 var preferences = Preferences()
83 _ = try preferences.importVocabulary("purple elephant, sketch")
84 try await AppleModels.configure(analyzer, words: preferences.contextWords)
85 try await analyzer.prepareToAnalyze(in: format)
86 let (stream, continuation) = AsyncThrowingStream<AnalyzerInput, Error>.makeStream()
87 let tap = try AudioTap(input: file.processingFormat, output: format, continuation: continuation)
88 let results = Task { try await AppleModels.collect(module) }
89 defer { results.cancel() }
90 do {
91 try await analyzer.start(inputSequence: stream)
92 let time = AVAudioTime(sampleTime: 0, atRate: file.processingFormat.sampleRate)
93 while file.framePosition < file.length {
94 let input = try #require(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 2048))
95 try file.read(into: input)
96 guard input.frameLength > 0 else { break }
97 tap.block(input, time)
98 }
99 continuation.finish()
100 try await analyzer.finalizeAndFinishThroughEndOfInput()
101 let transcript = try await results.value
102 #expect(transcript.localizedCaseInsensitiveContains("purple"))
103 #expect(transcript.localizedCaseInsensitiveContains("elephant"))
104 print("Apple Speech (stream): \(transcript)")
105 } catch {
106 continuation.finish()
107 await analyzer.cancelAndFinishNow()
108 throw error
109 }
110}
111
112@Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models"))
113func foundationModelRefinesOrPreservesTranscript() async {
114 let input = "um please send the purple elephant sketch to Jordan"
115 let result = await AppleModels.refine(input, mode: .clean, locale: "en-US")
116 print("Foundation Models status: \(AppleModels.modelStatus), result: \(result.text)")
117 if AppleModels.modelStatus == "Ready" {
118 #expect(result.note == nil)
119 #expect(result.text.localizedCaseInsensitiveContains("purple elephant"))
120 #expect(result.text.localizedCaseInsensitiveContains("Jordan"))
121 #expect(!result.text.localizedCaseInsensitiveContains("um please"))
122 } else {
123 #expect(result.text == input)
124 #expect(result.note != nil)
125 }
126}
127
128@Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models"))
129@MainActor
130func refineWindowChatsWithTheFoundationModel() async throws {
131 let idea = "um so I'm thinking we send a short weekly digest to customers with the three most useful tips, maybe on Mondays"
132 let session = RefineSession()
133 session.begin(text: idea, source: "Notes", locale: "en-US")
134 guard session.modelReady else {
135 #expect(session.messages.last?.role == .note)
136 return
137 }
138 for request in ["", "make it friendlier and add a subject line"] {
139 session.request = request
140 session.refine()
141 while session.isThinking { try await Task.sleep(for: .milliseconds(100)) }
142 let reply = try #require(session.messages.last)
143 print("Refine \(request.isEmpty ? "Refine" : request): \(reply.text)\n\(session.draft)")
144 #expect(reply.role == .assistant)
145 }
146 #expect(session.previousDrafts.count >= 1)
147 #expect(session.draft.localizedCaseInsensitiveContains("digest") || session.draft.localizedCaseInsensitiveContains("tips"))
148 session.undo()
149 #expect(session.draft != idea || session.previousDrafts.isEmpty)
150}