Cotton code
129 lines · 6.6 KB · KotlinRaw
package com.cottondb.albumsimport com.cottondb.albums.analysis.KotlinFeaturesimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.doubleimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Testimport java.io.Fileimport java.security.MessageDigestimport java.io.ByteArrayOutputStreamimport java.io.DataInputStreamimport java.util.zip.Inflater/** * THE FACE CROP AGAINST THE CONTRACT'S OWN VECTORS (assets/design/albums/align: README.md and vectors.json, made by * scripts/albums-align-vectors.py): the Kotlin stand-in for the core's crop must give the same transform within 1e-4 * and every crop byte within 1, and refuse points with no spread. Then HyperFace's agreement crops (hyperface.json) * are the very bytes the iPhone's model was given: the on-device check (AlbumsBench "agree") feeds them to LiteRT. */class AlignContractTest {    private val dir = File("../../../assets/design/albums/align")    private val vectors: JsonObject = Json.parseToJsonElement(File(dir, "vectors.json").readText()).jsonObject    /** A plain PNG (8-bit RGB or RGBA, not interlaced, as the vectors are written) to ARGB: no platform decoder. */    private fun argb(name: String): Triple<Int, Int, IntArray> {        val input = DataInputStream(File(dir, name).inputStream().buffered())        input.skipBytes(8)        var w = 0; var h = 0; var channels = 3        val idat = ByteArrayOutputStream()        while (true) {            val len = input.readInt()            val type = String(ByteArray(4).also { input.readFully(it) }, Charsets.US_ASCII)            val data = ByteArray(len).also { input.readFully(it) }            input.readInt()            when (type) {                "IHDR" -> {                    w = java.nio.ByteBuffer.wrap(data, 0, 4).int; h = java.nio.ByteBuffer.wrap(data, 4, 4).int                    check(data[8].toInt() == 8 && data[12].toInt() == 0) { "$name: not a plain 8-bit PNG" }                    channels = when (data[9].toInt()) { 2 -> 3; 6 -> 4; else -> error("$name: colour type ${data[9]}") }                }                "IDAT" -> idat.write(data)                "IEND" -> break            }        }        val stride = w * channels        val raw = ByteArray((stride + 1) * h)        Inflater().apply { setInput(idat.toByteArray()); var at = 0; while (at < raw.size) at += inflate(raw, at, raw.size - at); end() }        val out = IntArray(w * h)        val prev = IntArray(stride); val cur = IntArray(stride)        for (y in 0 until h) {            val filter = raw[y * (stride + 1)].toInt()            for (i in 0 until stride) {                val x = raw[y * (stride + 1) + 1 + i].toInt() and 0xFF                val a = if (i >= channels) cur[i - channels] else 0                val b = prev[i]                val c = if (i >= channels) prev[i - channels] else 0                cur[i] = (x + when (filter) {                    0 -> 0; 1 -> a; 2 -> b; 3 -> (a + b) / 2                    4 -> { val p = a + b - c; val pa = kotlin.math.abs(p - a); val pb = kotlin.math.abs(p - b); val pc = kotlin.math.abs(p - c); if (pa <= pb && pa <= pc) a else if (pb <= pc) b else c }                    else -> error("filter $filter")                }) and 0xFF            }            for (x in 0 until w) out[y * w + x] = (0xFF shl 24) or (cur[x * channels] shl 16) or (cur[x * channels + 1] shl 8) or cur[x * channels + 2]            cur.copyInto(prev)        }        return Triple(w, h, out)    }    private fun rgb(px: IntArray): ByteArray = ByteArray(px.size * 3).also { out ->        px.forEachIndexed { i, p -> out[3 * i] = (p shr 16).toByte(); out[3 * i + 1] = (p shr 8).toByte(); out[3 * i + 2] = p.toByte() }    }    private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }    @Test    fun every_case_matches_the_contract() {        val tol = vectors["tolerance"]!!.jsonObject        val tTol = tol["transform"]!!.jsonPrimitive.double        val byteTol = tol["crop_byte"]!!.jsonPrimitive.double.toInt()        var cases = 0        for (c in vectors["cases"]!!.jsonArray.map { it.jsonObject }.filter { it["error"] == null }) {            val name = c["name"]!!.jsonPrimitive.content            val points = c["points"]!!.jsonArray.flatMap { p -> p.jsonArray.map { it.jsonPrimitive.double } }.toDoubleArray()            val (w, h, src) = argb(c["source"]!!.jsonPrimitive.content)            assertEquals(name, c["source_rgb_sha256"]!!.jsonPrimitive.content, sha256(rgb(src)))            val t = c["transform"]!!.jsonObject            val m = KotlinFeatures.similarity(points, KotlinFeatures.TEMPLATE)!!            listOf("a", "b", "tx", "ty").forEachIndexed { k, key ->                assertEquals("$name $key", t[key]!!.jsonPrimitive.double, m[k], tTol)            }            val crop = KotlinFeatures.alignFace(src, w, h, points)!!            val want = rgb(argb(c["crop"]!!.jsonPrimitive.content).third)            var worst = 0            for (i in want.indices) worst = maxOf(worst, kotlin.math.abs((crop[i].toInt() and 0xFF) - (want[i].toInt() and 0xFF)))            assertTrue("$name: a crop byte $worst off", worst <= byteTol)            cases++        }        assertEquals(6, cases)    }    @Test    fun points_with_no_spread_are_refused() {        val refusal = vectors["cases"]!!.jsonArray.map { it.jsonObject }.single { it["error"] != null }        val points = refusal["points"]!!.jsonArray.flatMap { p -> p.jsonArray.map { it.jsonPrimitive.double } }.toDoubleArray()        assertNull(KotlinFeatures.similarity(points, KotlinFeatures.TEMPLATE))        assertNull(KotlinFeatures.alignFace(IntArray(100 * 100), 100, 100, points))    }    @Test    fun the_agreement_crops_are_the_bytes_the_iphone_model_was_given() {        val agree = Json.parseToJsonElement(File(dir, "hyperface.json").readText()).jsonObject        val cases = agree["cases"]!!.jsonArray.map { it.jsonObject }        assertEquals(14, cases.size)        for (c in cases) {            val (w, h, px) = argb(c["crop"]!!.jsonPrimitive.content)            assertEquals(112, w); assertEquals(112, h)            assertEquals(c["crop"]!!.jsonPrimitive.content, c["crop_rgb_sha256"]!!.jsonPrimitive.content, sha256(rgb(px)))            val v = c["vector"]!!.jsonArray.map { it.jsonPrimitive.double }            assertEquals(512, v.size)            assertEquals(1.0, v.sumOf { it * it }, 1e-4)        }    }}