Cotton code
213 lines · 12.4 KB · KotlinRaw
package com.cottondb.meetingsimport androidx.work.ListenableWorkerimport com.cottondb.meetings.transcribe.CottonVoiceimport com.cottondb.meetings.transcribe.Pcm16kimport com.cottondb.meetings.transcribe.PhoneTranscriptionimport com.cottondb.meetings.transcribe.Transcriberimport com.cottondb.meetings.transcribe.TranscriptionQueueimport kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.longimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrueimport org.junit.Ruleimport org.junit.Testimport org.junit.rules.TemporaryFolderimport java.io.File/** * The phone's transcription pass over apps/meetings/CORE.md: the core hands a meeting and cuts its windows; Cotton * Voice hears each; each window's final utterances become lines; the core merges the windows and lands the transcript. */class PhoneTranscriptionTest {    @get:Rule val folder = TemporaryFolder()    private fun json(text: String) = Json.parseToJsonElement(text) as JsonObject    private class Queue(val nexts: MutableList<String>, val windows: String = """{"windows": [{"index": 0, "start_ms": 0, "end_ms": 30000}, {"index": 1, "start_ms": 29000, "end_ms": 60000}]}""") : TranscriptionQueue {        val charging = mutableListOf<Boolean>()        val planned = mutableListOf<String>()        val durations = mutableListOf<Long>()        val merged = mutableListOf<JsonArray>()        val landed = mutableListOf<Pair<String, JsonObject>>()        val claims = mutableListOf<String>()        val failures = mutableListOf<String>()        val givenUp = mutableListOf<String>()        var heldByAnother = emptySet<String>()        var claimed = false        // A peek names the first waiting one (minus those refused); a take by id hands it and it leaves the queue.        override suspend fun next(charging: Boolean, peek: Boolean, except: List<String>, id: String?, battery: Int?): JsonObject {            if (peek) this.charging += charging            val at = nexts.indexOfFirst { n -> except.none { n.contains("\"$it\"") } && (id == null || n.contains("\"$id\"")) }            if (at < 0) return JsonObject(emptyMap())            return Json.parseToJsonElement(if (peek) nexts[at] else nexts.removeAt(at)) as JsonObject        }        override suspend fun claim(meeting: String): TranscriptionQueue.Claim {            claims += meeting            return when {                meeting in heldByAnother -> TranscriptionQueue.Claim.HeldByAnother                claimed -> TranscriptionQueue.Claim.Claimed                else -> TranscriptionQueue.Claim.Alone            }        }        override suspend fun failed(meeting: String, why: String) { failures += "$meeting:$why" }        override suspend fun giveUp(meeting: String, why: String) { givenUp += meeting }        override suspend fun windows(durationMs: Long): JsonObject { durations += durationMs; return Json.parseToJsonElement(windows) as JsonObject }        override suspend fun plan(meeting: String): JsonObject { planned += meeting; return Json.parseToJsonElement("""{"session": "v-$meeting"}""") as JsonObject }        override suspend fun merge(windows: JsonArray): JsonObject {            merged += windows            return Json.parseToJsonElement("""{"transcript": {"languages": ["en"], "speakers": [], "lines": []}}""") as JsonObject        }        override suspend fun transcribed(meeting: String, transcript: JsonObject): JsonObject { landed += meeting to transcript; return JsonObject(emptyMap()) }        val tracked = mutableListOf<Triple<String, JsonArray, String>>()        override suspend fun transcribedTracks(meeting: String, tracks: JsonArray, by: String): JsonObject { tracked += Triple(meeting, tracks, by); return JsonObject(emptyMap()) }    }    private class Engine(val fail: Long? = null, val code: String = "missing_model") : Transcriber {        val heard = mutableListOf<Pair<Long, Long>>()        val plans = mutableListOf<JsonObject>()        override fun durationMs(audio: File) = 60_000L        override suspend fun transcribe(audio: File, fromMs: Long, toMs: Long, plan: JsonObject): JsonObject {            if (fromMs == fail) throw CottonVoice.VoiceFailed(code, "")            heard += fromMs to toMs            plans += plan            return Json.parseToJsonElement(                """{"engine": "sherpa:test", "heard": [                     {"pass": "live", "final": true, "text": "helo there", "from_ms": $fromMs, "to_ms": ${fromMs + 900}},                     {"pass": "second", "final": true, "text": " Hello there. ", "language": "en",                      "words": [{"w": "Hello", "start_ms": ${fromMs + 100}, "end_ms": ${fromMs + 400}}, {"w": "there.", "start_ms": ${fromMs + 450}, "end_ms": ${fromMs + 880}}]}]}""",            ) as JsonObject        }    }    private fun next(audio: File, id: String = "m1") = """{"meeting": "$id", "audio_path": "${audio.absolutePath}"}"""    @Test fun each_window_the_core_cuts_is_heard_once_merged_by_the_core_and_landed() = runBlocking {        val audio = folder.newFile("a.aac")        val queue = Queue(mutableListOf(next(audio), next(audio, "m2")))        val engine = Engine()        assertEquals(ListenableWorker.Result.success(), PhoneTranscription(queue, engine).pass())        assertEquals(listOf(true, true, true), queue.charging)        assertEquals(listOf(60_000L, 60_000L), queue.durations)        assertEquals(listOf(0L to 30000L, 29000L to 60000L, 0L to 30000L, 29000L to 60000L), engine.heard)        assertEquals(listOf("m1", "m2"), queue.planned)        assertEquals("v-m1", engine.plans[0]["session"]!!.jsonPrimitive.content)        val window = queue.merged[0][1].jsonObject        assertEquals(1L, window["index"]!!.jsonPrimitive.long)        assertEquals(29000L, window["start_ms"]!!.jsonPrimitive.long)        val line = window["lines"]!!.jsonArray.single().jsonObject        assertEquals("the second pass's words, its own times", "Hello there.", line["text"]!!.jsonPrimitive.content)        assertEquals(29100L, line["start_ms"]!!.jsonPrimitive.long)        assertEquals(29880L, line["end_ms"]!!.jsonPrimitive.long)        assertEquals("en", line["language"]!!.jsonPrimitive.content)        assertEquals(listOf("m1", "m2"), queue.landed.map { it.first })        assertEquals("phone:sherpa:test", queue.landed[0].second["by"]!!.jsonPrimitive.content)    }    @Test fun a_plan_the_core_hands_with_the_meeting_is_used_as_it_is() = runBlocking {        val audio = folder.newFile("a.aac")        val queue = Queue(mutableListOf(next(audio).replaceFirst("{", """{"plan": {"session": "given"}, """)))        val engine = Engine()        PhoneTranscription(queue, engine).pass()        assertEquals(emptyList<String>(), queue.planned)        assertEquals("given", engine.plans[0]["session"]!!.jsonPrimitive.content)    }    @Test fun nothing_to_hear_is_a_quiet_success() = runBlocking {        val queue = Queue(mutableListOf())        assertEquals(ListenableWorker.Result.success(), PhoneTranscription(queue, Engine(), charging = { false }).pass())        assertEquals(listOf(false), queue.charging)        assertTrue(queue.landed.isEmpty())    }    @Test fun an_engine_failure_lands_nothing_and_is_tried_again_later() = runBlocking {        val audio = folder.newFile("a.aac")        val queue = Queue(mutableListOf(next(audio)))        assertEquals(ListenableWorker.Result.retry(), PhoneTranscription(queue, Engine(fail = 29000)).pass())        assertTrue("no half transcript is merged or landed", queue.merged.isEmpty() && queue.landed.isEmpty())    }    @Test fun a_recording_the_mac_holds_is_passed_over_for_the_next() = runBlocking {        val audio = folder.newFile("a.aac")        val queue = Queue(mutableListOf(next(audio, "m1"), next(audio, "m2"))).apply { heldByAnother = setOf("m1"); claimed = true }        assertEquals(ListenableWorker.Result.success(), PhoneTranscription(queue, Engine()).pass())        assertEquals("the Mac's is asked first, then the next", listOf("m1", "m2"), queue.claims.take(2))        assertEquals("only the one this phone claimed is landed", listOf("m2"), queue.landed.map { it.first })    }    @Test fun a_transcription_that_breaks_is_said_failed_and_its_claim_let_go() = runBlocking {        val audio = folder.newFile("a.aac")        val queue = Queue(mutableListOf(next(audio))).apply { claimed = true }        assertEquals(ListenableWorker.Result.success(), PhoneTranscription(queue, Engine(fail = 29000, code = "engine")).pass())        assertEquals(listOf("m1:engine_failed"), queue.failures)        assertEquals(listOf("m1"), queue.givenUp)        assertTrue(queue.landed.isEmpty())    }    @Test fun audio_no_longer_on_the_phone_is_left_to_the_mac() = runBlocking {        val queue = Queue(mutableListOf(next(File(folder.root, "gone.aac"))))        val engine = Engine()        assertEquals(ListenableWorker.Result.success(), PhoneTranscription(queue, engine).pass())        assertEquals(0, engine.heard.size)    }    @Test fun a_window_with_only_a_live_pass_keeps_the_live_words_and_drops_empty_ones() {        val lines = PhoneTranscription.lines(json(            """{"heard": [{"pass": "live", "final": true, "text": "ok", "from_ms": 10, "to_ms": 300},                          {"pass": "live", "final": true, "text": "  ", "from_ms": 400, "to_ms": 500}]}""",        ))        assertEquals(1, lines.size)        assertEquals(10L, lines[0].jsonObject["start_ms"]!!.jsonPrimitive.long)        assertEquals(JsonPrimitive("ok"), lines[0].jsonObject["text"])    }    @Test fun cotton_voices_times_are_moved_from_the_windows_start_to_the_recordings() {        val moved = CottonVoice.shifted(json("""{"pass": "live", "final": true, "text": "hi", "from_ms": 0, "to_ms": 900, "words": [{"w": "hi", "start_ms": 100, "end_ms": 500}]}"""), 60_000)        assertEquals(60_000L, moved["from_ms"]!!.jsonPrimitive.long)        assertEquals(60_900L, moved["to_ms"]!!.jsonPrimitive.long)        val word = moved["words"]!!.jsonArray[0].jsonObject        assertEquals(60_100L, word["start_ms"]!!.jsonPrimitive.long)        assertEquals(60_500L, word["end_ms"]!!.jsonPrimitive.long)    }    @Test fun pcm_is_made_sixteen_kilohertz_mono_in_tenth_second_chunks() {        val chunks = mutableListOf<ByteArray>()        val pcm = Pcm16k()        // One second of 48 kHz stereo, left 1000 and right 3000: 16000 mono samples of 2000.        val second = ByteArray(48_000 * 4).also { b ->            for (f in 0 until 48_000) { b[f * 4] = (1000 and 0xFF).toByte(); b[f * 4 + 1] = (1000 shr 8).toByte(); b[f * 4 + 2] = (3000 and 0xFF).toByte(); b[f * 4 + 3] = (3000 shr 8).toByte() }        }        pcm.add(second, 0, 48_000, 2) { chunks += it }        pcm.flush { chunks += it }        val all = chunks.fold(ByteArray(0)) { a, b -> a + b }        assertEquals(16_000 * 2, all.size)        assertEquals(3200, chunks.first().size)        assertEquals(2000, (all[all.size - 2].toInt() and 0xFF) or (all[all.size - 1].toInt() shl 8))    }    // RULE (owner, 23 Nov 2026; chat CONTRACT "Take notes"): a call's notes are heard a file per person, each in the    // core's windows, and handed back by track (never merged as one room), so who said what is the track's.    @Test fun a_calls_notes_are_heard_track_by_track() = runBlocking {        val me = folder.newFile("m1.me.aac")        val asha = folder.newFile("m1.asha.aac")        val notes = """{"meeting": "m1", "audio_path": "${me.absolutePath}", "tracks": [{"track": "me", "audio_path": "${me.absolutePath}"}, {"track": "callee:x", "audio_path": "${asha.absolutePath}"}]}"""        val queue = Queue(mutableListOf(notes))        val engine = Engine()        assertEquals(ListenableWorker.Result.success(), PhoneTranscription(queue, engine).pass())        assertEquals("both files, each in both windows", 4, engine.heard.size)        assertEquals(emptyList<JsonArray>(), queue.merged)        assertEquals(emptyList<String>(), queue.landed.map { it.first })        val (meeting, tracks, by) = queue.tracked.single()        assertEquals("m1", meeting)        assertEquals(listOf("me", "callee:x"), tracks.map { it.jsonObject["track"]!!.jsonPrimitive.content })        assertEquals(2, tracks[1].jsonObject["windows"]!!.jsonArray.size)        assertEquals("phone:sherpa:test", by)    }}