Cotton code
259 lines · 12.1 KB · SwiftRaw
// Transcribing on this phone (voice plan, 17 Nov 2026): one of the// swappable steps with one interface (audio in, the transcript out: timed// lines with speaker labels), run while the phone is CHARGING; the Mac does// it sooner when it is on. Every rule is the core's (`apps/meetings/CORE.md`):// `meetings.next` names the next waiting recording, the object is asked for// it (`meeting_claim { id, by: phone }`, a 409 when the Mac holds it drops// the job), `meetings.next { id }` hands this phone that one,// `meetings.windows` cuts it into overlapping windows, each window is heard// by the plan's engine, `meetings.merge` makes them one transcript and// `meetings.transcribed` lands it.//// THE ENGINE is the voice engine layer's (`CottonVoice`):// the second-pass engine `voice.plan` names for the meeting's language, a// sherpa model from the shared store or `apple.speech`, fed 16 kHz mono// samples, answering timed words. Lines are cut from the words at a pause// or a sentence's end. No speaker separation runs on the phone yet, so a// window's lines are all S1 and `meetings.merge` keeps them one speaker.#if os(iOS)import AVFoundationimport CottonKitimport CottonVoiceimport Foundation/// The step's engine seam: a window of 16 kHz samples in, timed words out.protocol MeetingWindowHearing: Sendable {    /// `<where>:<engine>`, as `transcribed_by` says it.    var by: String { get }    func hear(_ samples: [Float], offsetMs: Int) async throws -> VoiceHearing}/// The plan's second-pass engine.struct PlannedHearing: MeetingWindowHearing {    let by: String    let engine: any SecondVoiceEngine    func hear(_ samples: [Float], offsetMs: Int) async throws -> VoiceHearing {        try await engine.transcribe(samples, offsetMs: offsetMs)    }    /// The engine `voice.plan` names for this meeting.    @MainActor    static func planned(core: any CottonCalling, meeting: String) async throws -> (PlannedHearing, [String]) {        let plan = try await core.call(            CottonMethod.voicePlan,            VoicePlanRequest(surface: "meeting", table: MeetingsTable.meeting, record: meeting, mode: .dictate),            as: VoicePlan.self)        var choice = plan.second ?? plan.live        let store = VoiceModelStore.current        await store.attach(core)        let engine: any SecondVoiceEngine        do {            engine = try await VoiceEngines.second(choice, language: plan.languages.first, store: store)        } catch where choice.engine != VoiceEngineChoice.appleSpeech {            // The plan's model is not on this phone yet: the phone's own            // recogniser reads it now rather than leaving the meeting waiting.            Log.warn("meetings: phone step: \(choice.engine) is not here (\(error)); the phone's own recogniser reads it")            choice = VoiceEngineChoice(engine: VoiceEngineChoice.appleSpeech)            engine = try await VoiceEngines.second(choice, language: plan.languages.first, store: store)        }        try await engine.prepare()        return (PlannedHearing(by: "phone:\(choice.engine)", engine: engine), plan.languages)    }}@MainActorfinal class MeetingsPhoneStep {    static let shared = MeetingsPhoneStep()    /// The meeting this phone is transcribing now, for its card to say so.    private(set) var current: String?    private var running = false    /// A test's engine in place of the plan's.    var hearing: (any MeetingWindowHearing)?    /// Where the step notes the meeting it holds, so a step the system ended    /// mid-way is said at the next start rather than left `transcribing`.    var notes: UserDefaults = .standard    static let holdingKey = "meetings.phone-step.holding"    static let claimedKey = "meetings.phone-step.claimed"    /// A meeting a step that was ended still held: failed with its why (the    /// page offers Try again), and the object's claim let go. The core keeps    /// no holder on a `transcribing` row, so only this phone's own note can    /// tell its step from the Mac's.    func settleInterrupted(core: any CottonCalling) async {        guard !running, let held = notes.string(forKey: Self.holdingKey) else { return }        let claimed = notes.bool(forKey: Self.claimedKey)        Log.warn("meetings: phone step: \(held) was held by a step that was ended")        let meetings = MeetingsCore(core: core)        try? await meetings.transcriptionFailed(held, why: "engine_failed")        if claimed { await meetings.giveUp(held, why: "engine_failed") }        letGo()    }    private func hold(_ meeting: String, claimed: Bool) {        notes.set(meeting, forKey: Self.holdingKey)        notes.set(claimed, forKey: Self.claimedKey)    }    private func letGo() {        notes.removeObject(forKey: Self.holdingKey)        notes.removeObject(forKey: Self.claimedKey)    }    /// Transcribe what the core hands this phone: while charging any, off power what the core says a phone may take    /// (`meetings.next` with the battery: a short recording at 30% or more, CONTRACT.md "Recordings"). Answers how    /// many transcripts it landed; stops at the first that does not land.    @discardableResult    func drain(core: any CottonCalling, force: Bool = false) async -> Int {        guard !running else { return 0 }        await settleInterrupted(core: core)        running = true        defer { running = false; current = nil }        var landed = 0        while await once(core: core, force: force) { landed += 1 }        return landed    }    /// One recording the core hands this phone, transcribed and landed.    /// False when there is none, or it did not land (and the core was told).    func drainOnce(core: any CottonCalling) async -> Bool {        guard !running else { return false }        await settleInterrupted(core: core)        running = true        defer { running = false; current = nil }        return await once(core: core, force: true)    }    /// One recording: the core names a candidate (`peek`), the object is    /// asked for it (`meeting_claim`) and a 409 drops it for the next, then    /// the core hands this phone that one (`next { id }`).    private func once(core: any CottonCalling, force: Bool) async -> Bool {        let meetings = MeetingsCore(core: core)        let charging = force || MeetingsPower.charging        let battery = charging ? nil : MeetingsPower.battery        var refused: [String] = []        while let candidate = await meetings.next(charging: charging, battery: battery, peek: true, except: refused) {            // A core that named a refused one again has nothing else to give.            guard !refused.contains(candidate.meeting) else { return false }            let claim = await meetings.claim(candidate.meeting)            if claim == .heldByAnother {                refused.append(candidate.meeting)                continue            }            guard let next = await meetings.next(charging: charging, battery: battery, id: candidate.meeting) else { return false }            current = next.meeting            hold(next.meeting, claimed: claim == .claimed)            defer { letGo() }            do {                try await transcribe(next.meeting, audio: next.audio, core: core)                return true            } catch {                // Said, rather than left standing claimed by a step that                // stopped: the card says why and offers Try again.                Log.warn("meetings: phone step: \(next.meeting) was not transcribed: \(error)")                try? await meetings.transcriptionFailed(next.meeting, why: "engine_failed")                if claim == .claimed { await meetings.giveUp(next.meeting, why: "engine_failed") }                return false            }        }        return false    }    private func transcribe(_ meeting: String, audio: URL, core: any CottonCalling) async throws {        let meetings = MeetingsCore(core: core)        let hearing: any MeetingWindowHearing        var languages: [String] = []        if let given = self.hearing {            hearing = given        } else {            let planned = try await PlannedHearing.planned(core: core, meeting: meeting)            hearing = planned.0            languages = planned.1        }        let file = try AVAudioFile(forReading: audio)        let durationMs = Int(Double(file.length) / file.processingFormat.sampleRate * 1000)        let windows = await meetings.windows(durationMs: durationMs)            ?? [MeetingWindow(index: 0, start_ms: 0, end_ms: durationMs)]        var heard: [MeetingsCore.HeardWindow] = []        for window in windows {            let samples = try MeetingsAudioWindow.samples(of: file, fromMs: window.start_ms, toMs: window.end_ms)            let words = try await hearing.hear(samples, offsetMs: window.start_ms)            let language = words.language ?? languages.first            heard.append(.init(                index: window.index, start_ms: window.start_ms, end_ms: window.end_ms, language: language,                lines: MeetingsLines.cut(words.words, speaker: nil, language: language)))        }        let merged = try await meetings.merge(heard)        let transcript = merged.by.isEmpty            ? MeetingTranscript(by: hearing.by, languages: merged.languages, speakers: merged.speakers, lines: merged.lines)            : merged        try await meetings.transcribed(meeting: meeting, transcript)    }}/// A window of a recording as 16 kHz mono samples.enum MeetingsAudioWindow {    static let rate = 16_000.0    static func samples(of file: AVAudioFile, fromMs: Int, toMs: Int) throws -> [Float] {        let source = file.processingFormat        let first = AVAudioFramePosition(Double(fromMs) / 1000 * source.sampleRate)        let count = AVAudioFrameCount(max(0, Double(toMs - fromMs) / 1000 * source.sampleRate))        guard count > 0, first < file.length,              let input = AVAudioPCMBuffer(pcmFormat: source, frameCapacity: count),              let target = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: rate, channels: 1, interleaved: false),              let converter = AVAudioConverter(from: source, to: target)        else { return [] }        file.framePosition = first        try file.read(into: input, frameCount: min(count, AVAudioFrameCount(file.length - first)))        guard let output = AVAudioPCMBuffer(            pcmFormat: target, frameCapacity: AVAudioFrameCount(Double(input.frameLength) * rate / source.sampleRate) + 1024)        else { return [] }        var fed = false        var failure: NSError?        converter.convert(to: output, error: &failure) { _, status in            if fed {                status.pointee = .endOfStream                return nil            }            fed = true            status.pointee = .haveData            return input        }        if let failure { throw failure }        guard let channel = output.floatChannelData?[0] else { return [] }        return Array(UnsafeBufferPointer(start: channel, count: Int(output.frameLength)))    }}/// Timed words cut into a transcript's lines: at a pause of `pauseMs` or/// more, or after a word that ends a sentence once the line has some length.enum MeetingsLines {    static let pauseMs = 900    static let sentenceAfterMs = 4_000    static func cut(_ words: [VoiceWord], speaker: String?, language: String?) -> [MeetingTranscript.Line] {        var lines: [MeetingTranscript.Line] = []        var held: [VoiceWord] = []        func close() {            guard let first = held.first, let last = held.last else { return }            let text = held.map(\.w).joined(separator: " ").trimmingCharacters(in: .whitespaces)            if !text.isEmpty {                lines.append(.init(speaker: speaker, start_ms: first.startMs, end_ms: last.endMs, text: text, language: language))            }            held = []        }        for word in words {            if let last = held.last, word.startMs - last.endMs >= pauseMs { close() }            held.append(word)            if let first = held.first, let end = word.w.last, ".?!".contains(end), word.endMs - first.startMs >= sentenceAfterMs {                close()            }        }        close()        return lines    }}#endif