Cotton code
225 lines · 12.4 KB · SwiftRaw
// The engines on recorded speech, end to end on a simulator: Apple's// recogniser live, a sherpa-onnx model as the second pass, the audio played// in real time as if spoken. OPT-IN: it runs only when `VOICE_PROOF_DIR`// names a folder holding `audio/<name>.wav` and `models/<sherpa folder>/`// (xcodebuild passes `TEST_RUNNER_VOICE_PROOF_DIR` through); otherwise it// skips, so the suite never downloads or needs a model.//// The core here is a test double that only assembles (settled = the finals,// a second pass replaces its utterance): the core's own rules are voice-core's// and are proved there. What this proves is the platform half: the engines// hear the recordings, the second pass re-reads each utterance's audio, the// session applies what comes back, and how long each step takes.@testable import CottonVoiceimport CottonKitimport CottonSpeechimport Speechimport XCTest/// Assembles hearings the simplest way, so the platform can be measured.actor AssemblingCore: CottonCalling {    var plan = ""    private var finals: [String] = []    private var tentative = ""    private var seconds = 0    private var last = ""    func callRaw(_ method: String, requestJSON: String) async throws -> String {        let request = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8))) as? [String: Any] ?? [:]        switch method {        case CottonMethod.voicePlan:            return #"{"ok":true,"data":\#(plan)}"#        case CottonMethod.voiceHeard:            let text = request["text"] as? String ?? ""            let final = request["final"] as? Bool ?? false            if request["pass"] as? String == "second" {                if seconds < finals.count, !text.isEmpty { finals[seconds] = text }                seconds += 1            } else if final {                finals.append(text)                tentative = ""            } else {                tentative = text            }            return envelope()        case CottonMethod.voiceEnd:            tentative = ""            let text = finals.joined(separator: " ")            return #"{"ok":true,"data":{"text":\#(Self.quote(text)),"edits":[]}}"#        default:            return #"{"ok":true,"data":{}}"#        }    }    private func envelope() -> String {        let settled = finals.joined(separator: " ")        let shown = settled.isEmpty || tentative.isEmpty ? tentative : " " + tentative        return #"{"ok":true,"data":{"settled":\#(Self.quote(settled)),"tentative":\#(Self.quote(shown)),"edits":[]}}"#    }    static func quote(_ text: String) -> String {        String(decoding: try! JSONEncoder().encode(text), as: UTF8.self)    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}@MainActorfinal class VoiceEngineProofTests: XCTestCase {    private var root: URL!    override func setUpWithError() throws {        guard let path = ProcessInfo.processInfo.environment["VOICE_PROOF_DIR"], !path.isEmpty else {            throw XCTSkip("VOICE_PROOF_DIR is not set: the engine proof is opt-in")        }        root = URL(fileURLWithPath: path)    }    private func entry(_ folder: String, kind: String, family: String) throws -> (VoiceModelEntry, URL) {        let at = root.appendingPathComponent("models").appendingPathComponent(folder)        let names = try FileManager.default.contentsOfDirectory(atPath: at.path).filter { !$0.hasPrefix(".") && $0.contains(".") }        // These proof folders are sherpa-onnx's own releases: the test spells each file's part, as the catalogue does.        func part(_ name: String) -> String {            for part in ["encoder", "decoder", "joiner", "tokens"] where name.contains(part) { return part }            return name.hasSuffix(".onnx") ? "model" : ""        }        let files = names.map { VoiceModelFile(name: $0, url: "", bytes: 0, sha256: "", part: part($0)) }        return (VoiceModelEntry(model: folder, family: family, kind: kind, files: files), at)    }    /// One recording through Apple live and a sherpa second pass; answers    /// what was written and the timings.    private func run(_ audio: String, language: String, second: (VoiceModelEntry, URL)?,                     live liveEngine: (@MainActor () throws -> any LiveVoiceEngine)? = nil) async throws -> (String, VoiceTimings) {        let core = AssemblingCore()        let secondEngine = try second.map { try SherpaSecond(entry: $0.0, language: language, folder: $0.1) }        let maker = VoiceEngineMaker(            live: { _, language, vocabulary, _ in                if let liveEngine { return try liveEngine() }                return AppleSpeechEngine(language: language, vocabulary: vocabulary)            },            second: { _, _, _ in                guard let secondEngine else { throw VoiceFailure.modelMissing("none") }                return secondEngine            },            input: { source in                guard case .recording(let url) = source else { fatalError() }                return RecordingInput(url: url)            },            opensAudioSession: false)        let session = VoiceSession(            core: core, store: VoiceModelStore(root: FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)),            source: .recording(root.appendingPathComponent("audio/\(audio).wav")), engines: maker)        // The plan the core would give: the language, live, and the second.        await core.setPlan(language: language, second: second?.0.model)        await session.start(VoicePlanRequest(surface: "proof", mode: .dictate))        if case .failed(let failure) = session.phase { XCTFail("\(audio): \(failure)"); return ("", session.timings) }        // The recording ends the session by itself (a tap on the mic).        for _ in 0 ..< 600 where session.phase != .idle { try await Task.sleep(for: .milliseconds(100)) }        let written = session.region.display        let t = session.timings        let said = "voice-proof \(audio) [\(language)] written=\(written)\n"            + "voice-proof \(audio) first_word_ms=\(t.firstWordMs ?? -1) live_settled_ms=\(t.liveSettledMs) second_settled_ms=\(t.secondSettledMs) corrections=\(t.corrections)\n"        print(said, terminator: "")        // Beside the recordings, where the walker reads it (xcodebuild keeps no stdout).        let log = root.appendingPathComponent("results.txt")        if let handle = try? FileHandle(forWritingTo: log) {            handle.seekToEndOfFile()            handle.write(Data(said.utf8))            try? handle.close()        } else {            try? Data(said.utf8).write(to: log)        }        return (written, t)    }    /// What Apple's recogniser offers on this device, for the report.    func testAppleOffers() async throws {        var said = "voice-proof apple SpeechTranscriber.isAvailable=\(SpeechTranscriber.isAvailable)\n"        said += "voice-proof apple SpeechTranscriber.supported=\(await SpeechTranscriber.supportedLocales.map(\.identifier).sorted().prefix(80))\n"        said += "voice-proof apple SpeechTranscriber.installed=\(await SpeechTranscriber.installedLocales.map(\.identifier).sorted())\n"        said += "voice-proof apple DictationTranscriber.supported=\(await DictationTranscriber.supportedLocales.map(\.identifier).sorted().prefix(80))\n"        said += "voice-proof apple DictationTranscriber.installed=\(await DictationTranscriber.installedLocales.map(\.identifier).sorted())\n"        for module in [DictationTranscriber(locale: Locale(identifier: "en_US"), preset: .progressiveShortDictation) as any SpeechModule] {            let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module])            said += "voice-proof apple dictation en_US format=\(String(describing: format))\n"            do {                if let request = try await AssetInventory.assetInstallationRequest(supporting: [module]) {                    try await request.downloadAndInstall()                    said += "voice-proof apple dictation en_US installed now\n"                } else { said += "voice-proof apple dictation en_US no install needed\n" }            } catch { said += "voice-proof apple dictation en_US install error=\(error)\n" }            said += "voice-proof apple dictation en_US status=\(await AssetInventory.status(forModules: [module]))\n"            said += "voice-proof apple dictation en_US format after=\(String(describing: await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [module])))\n"        }        let ours = DictationTranscriber(            locale: Locale(identifier: "en_US"), contentHints: [], transcriptionOptions: [.punctuation],            reportingOptions: [.volatileResults], attributeOptions: [.audioTimeRange, .transcriptionConfidence])        said += "voice-proof apple ours en_US status=\(await AssetInventory.status(forModules: [ours])) format=\(String(describing: await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [ours])))\n"        said += "voice-proof apple wanted en=\(String(describing: await SpeechModel.locale(DictationTranscriber.self, for: AppleSpeechEngine.locale("en")))) ja=\(String(describing: await SpeechModel.locale(DictationTranscriber.self, for: AppleSpeechEngine.locale("ja"))))\n"        write(said)    }    private func write(_ said: String) {        print(said, terminator: "")        let log = root.appendingPathComponent("results.txt")        if let handle = try? FileHandle(forWritingTo: log) {            handle.seekToEndOfFile()            handle.write(Data(said.utf8))            try? handle.close()        } else {            try? Data(said.utf8).write(to: log)        }    }    /// RULE: English is heard live by Apple's recogniser and re-read by a sherpa model, each utterance.    func testEnglishTwoPasses() async throws {        let parakeet = try entry("sherpa-onnx-nemo-parakeet_tdt_ctc_110m-en-36000-int8", kind: "offline-nemo-ctc", family: "parakeet")        let (written, timings) = try await run("en-note", language: "en", second: parakeet)        XCTAssertTrue(written.lowercased().contains("milk"), written)        XCTAssertNotNil(timings.firstWordMs)        XCTAssertFalse(timings.secondSettledMs.isEmpty)    }    /// RULE: Japanese is heard live and re-read by SenseVoice.    func testJapaneseTwoPasses() async throws {        let senseVoice = try entry("sherpa-onnx-sense-voice-zh-en-ja-ko-yue-int8-2025-09-09", kind: "offline-sense-voice", family: "sense-voice")        let (written, timings) = try await run("ja", language: "ja", second: senseVoice)        XCTAssertTrue(written.contains("東京"), written)        XCTAssertFalse(timings.secondSettledMs.isEmpty)    }    // The live sherpa engines exist only where the archive links (the    // simulator and the phone); the Mac build of these tests has none.    #if canImport(SherpaOnnxC)    /// RULE: A short spoken command is heard whole by the streaming model, to its last word.    func testAShortCommandIsHeardByTheStreamingModel() async throws {        let kroko = try entry("sherpa-onnx-streaming-zipformer-en-kroko-2025-08-06", kind: "online-transducer", family: "zipformer")        let (written, _) = try await run("en-command", language: "en", second: nil) {            SherpaStreaming(entry: kroko.0, files: SherpaFiles(folder: kroko.1, files: kroko.0.files), language: "en", vocabulary: [])        }        XCTAssertTrue(written.lowercased().contains("open"), written)    }    /// RULE: Telugu, which Apple's recogniser does not hear, is heard live by Whisper on voice-activity segments.    func testTeluguBySherpa() async throws {        let whisper = try entry(ProcessInfo.processInfo.environment["VOICE_PROOF_WHISPER"] ?? "sherpa-onnx-whisper-turbo", kind: "offline-whisper", family: "whisper")        let vad = try entry("silero", kind: "vad-silero", family: "silero-vad")        let (written, _) = try await run("te", language: "te", second: nil) {            SherpaSegmented(                entry: whisper.0, files: SherpaFiles(folder: whisper.1, files: whisper.0.files),                language: "te", vad: SherpaFiles(folder: vad.1, files: vad.0.files), vadEntry: vad.0)        }        XCTAssertFalse(written.isEmpty)    }    #endif}extension AssemblingCore {    /// The plan this double answers.    func setPlan(language: String, second: String?) {        plan = #"{"session":"proof","mode":"dictate","languages":["\#(language)"],"live":{"engine":"apple.speech"},"second":\#(second.map { #"{"engine":"sherpa:\#($0)"}"# } ?? "null"),"vocabulary":["Ravi","Seetha","Hyderabad"]}"#    }}