import AVFoundation import Foundation import Speech import Testing @testable import Voxley private let fixture = ProcessInfo.processInfo.environment["VOXLEY_TEST_AUDIO"] @Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models")) func recorderMeterReflectsMicrophoneAmplitude() async throws { let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)) let locale = try await AppleModels.prepareSpeech(for: "en-US") let module = SpeechTranscriber(locale: locale, preset: .progressiveTranscription) let output = try #require(await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module])) let (_, audio) = AsyncThrowingStream.makeStream() let (readings, meter) = AsyncStream.makeStream() let tap = try AudioTap(input: format, output: output, continuation: audio) { meter.yield($0) } let framesPerColumn = 224 // 14 ms at 16 kHz. let split = 4 * framesPerColumn + framesPerColumn / 2 for range in [0.. MicrophoneWaveform.columnCount) #expect(waveform.peaks.suffix(8).prefix(4).allSatisfy { $0 == WaveformPeak(low: -0.125, high: 0.25) }) #expect(waveform.peaks.suffix(4).allSatisfy { $0 == WaveformPeak() }) // A buffer can replace the history without changing where a shared peak appears on screen. let sameDisplayTime = 100.17 let oldEdge = initial.rightEdge(at: sameDisplayTime) let newEdge = waveform.rightEdge(at: sameDisplayTime) #expect(abs(oldEdge - newEdge - 8) < 0.001) let nextDisplayFrame = waveform.rightEdge(at: sameDisplayTime + 1.0 / 60) #expect(abs(nextDisplayFrame - newEdge - (1.0 / 60) / 0.014) < 0.001) } @Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models")) func appleSpeechRecognizesAnActualRecording() async throws { let url = URL(filePath: try #require(fixture)) let file = try AVAudioFile(forReading: url) let locale = try await AppleModels.prepareSpeech(for: "en-US") let module = SpeechTranscriber(locale: locale, preset: .transcription) let analyzer = SpeechAnalyzer(modules: [module]) let results = Task { try await AppleModels.collect(module) } defer { results.cancel() } do { let end = try #require(try await analyzer.analyzeSequence(from: file)) try await analyzer.finalizeAndFinish(through: end) let transcript = try await results.value #expect(transcript.localizedCaseInsensitiveContains("purple")) #expect(transcript.localizedCaseInsensitiveContains("elephant")) print("Apple Speech (file): \(transcript)") } catch { await analyzer.cancelAndFinishNow() throw error } } @Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models")) func appleSpeechRecognizesProgressiveAudioThroughCaptureConverter() async throws { let url = URL(filePath: try #require(fixture)) let file = try AVAudioFile(forReading: url) let locale = try await AppleModels.prepareSpeech(for: "en-US") let module = SpeechTranscriber(locale: locale, preset: .progressiveTranscription) let format = try #require(await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module])) let analyzer = SpeechAnalyzer(modules: [module]) var preferences = Preferences() _ = try preferences.importVocabulary("purple elephant, sketch") try await AppleModels.configure(analyzer, words: preferences.contextWords) try await analyzer.prepareToAnalyze(in: format) let (stream, continuation) = AsyncThrowingStream.makeStream() let tap = try AudioTap(input: file.processingFormat, output: format, continuation: continuation) let results = Task { try await AppleModels.collect(module) } defer { results.cancel() } do { try await analyzer.start(inputSequence: stream) let time = AVAudioTime(sampleTime: 0, atRate: file.processingFormat.sampleRate) while file.framePosition < file.length { let input = try #require(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 2048)) try file.read(into: input) guard input.frameLength > 0 else { break } tap.block(input, time) } continuation.finish() try await analyzer.finalizeAndFinishThroughEndOfInput() let transcript = try await results.value #expect(transcript.localizedCaseInsensitiveContains("purple")) #expect(transcript.localizedCaseInsensitiveContains("elephant")) print("Apple Speech (stream): \(transcript)") } catch { continuation.finish() await analyzer.cancelAndFinishNow() throw error } } @Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models")) func foundationModelRefinesOrPreservesTranscript() async { let input = "um please send the purple elephant sketch to Jordan" let result = await AppleModels.refine(input, mode: .clean, locale: "en-US") print("Foundation Models status: \(AppleModels.modelStatus), result: \(result.text)") if AppleModels.modelStatus == "Ready" { #expect(result.note == nil) #expect(result.text.localizedCaseInsensitiveContains("purple elephant")) #expect(result.text.localizedCaseInsensitiveContains("Jordan")) #expect(!result.text.localizedCaseInsensitiveContains("um please")) } else { #expect(result.text == input) #expect(result.note != nil) } } @Test(.enabled(if: fixture != nil, "Run Scripts/test-app.sh --with-models to exercise local Apple models")) @MainActor func refineWindowChatsWithTheFoundationModel() async throws { let idea = "um so I'm thinking we send a short weekly digest to customers with the three most useful tips, maybe on Mondays" let session = RefineSession() session.begin(text: idea, source: "Notes", locale: "en-US") guard session.modelReady else { #expect(session.messages.last?.role == .note) return } for request in ["", "make it friendlier and add a subject line"] { session.request = request session.refine() while session.isThinking { try await Task.sleep(for: .milliseconds(100)) } let reply = try #require(session.messages.last) print("Refine \(request.isEmpty ? "Refine" : request): \(reply.text)\n\(session.draft)") #expect(reply.role == .assistant) } #expect(session.previousDrafts.count >= 1) #expect(session.draft.localizedCaseInsensitiveContains("digest") || session.draft.localizedCaseInsensitiveContains("tips")) session.undo() #expect(session.draft != idea || session.previousDrafts.isEmpty) }