145 lines · 8.0 KB · KotlinRaw
package com.cottondb.albumsimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.graphics.Bitmapimport android.graphics.BitmapFactoryimport android.os.Debugimport android.util.Logimport android.util.Sizeimport com.cottondb.albums.analysis.AnalysisWorkerimport com.cottondb.albums.analysis.HyperFaceimport com.cottondb.albums.analysis.LookPictureimport com.cottondb.albums.analysis.Paceimport com.cottondb.albums.analysis.ResolverPicturesimport com.cottondb.albums.library.MediaLibraryimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.doubleimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport java.io.Fileimport java.security.MessageDigestimport kotlin.concurrent.thread/** * ALBUMS DEV'S BENCH (src/albumsDev only): `--ei n N` times every stage of looking over the newest N photos, nothing * written, and logs one summary line (tag albums.pass, "albums.bench summary") with each stage's p50 and p95, also * appended to no_backup/albums-bench-summary.txt. `--ez pass true` starts (resumes) the pass now; `--ez pause true` * pauses it, as the home's Pause does. * * `--ez agree true`: THE TWO-PHONE AGREEMENT CHECK (tag albums.agree, also no_backup/albums-agree.txt): each crop of * assets/design/albums/align/hyperface.json through this phone's HyperFace (LiteRT), its cosine to the iPhone model's * vector logged one by one, then the least of them against the stated minimum, and the ms per face (p50, p95). * * `--ez thumbs true` (`--ei per K`, default 40): WHAT THE PLATFORM'S THUMBNAIL REALLY GIVES (tag albums.thumbs): for up * to K items of each kind, loadThumbnail asked at 512 and the long edge it came back at, and what LookPicture then * takes (the closer decode, or owed a closer look). */class AlbumsBench : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val n = intent.getIntExtra("n", 0) if (n > 0) { Log.i("albums.pass", "bench asked: $n photos") AnalysisWorker.bench(context, n) } if (intent.getBooleanExtra("pause", false)) { Log.i("albums.pass", "pause asked from adb") AnalysisWorker.pause(context) } if (intent.getBooleanExtra("pass", false)) { Log.i("albums.pass", "pass asked from adb") AnalysisWorker.resume(context) } val app = context.applicationContext if (intent.getBooleanExtra("agree", false)) thread(name = "albums-agree") { runCatching { agree(app) }.onFailure { Log.e(AGREE, "agree failed", it) } } if (intent.getBooleanExtra("thumbs", false)) { val per = intent.getIntExtra("per", 40) thread(name = "albums-thumbs") { runCatching { thumbs(app, per) }.onFailure { Log.e(THUMBS, "thumbs failed", it) } } } } private fun agree(app: Context) { val out = File(app.noBackupFilesDir, "albums-agree.txt").apply { writeText("") } fun say(line: String) { Log.i(AGREE, line); out.appendText(line + "\n") } val spec = Json.parseToJsonElement(app.assets.open("albums/agreement/hyperface.json").use { it.readBytes().decodeToString() }).jsonObject val min = spec["tolerance"]!!.jsonObject["cosine_min"]!!.jsonPrimitive.double val nativeBefore = Debug.getNativeHeapAllocatedSize() val t0 = System.nanoTime() val model = HyperFace(app) val loadMs = (System.nanoTime() - t0) / 1e6 val times = ArrayList<Double>() var worst = 1.0 var bytesOk = 0 val cases = spec["cases"]!!.jsonArray.map { it.jsonObject } for (c in cases) { val name = c["crop"]!!.jsonPrimitive.content val bmp = app.assets.open("albums/agreement/$name").use { BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inScaled = false; inPreferredConfig = Bitmap.Config.ARGB_8888; inPremultiplied = false })!! } val px = IntArray(112 * 112).also { bmp.getPixels(it, 0, 112, 0, 0, 112, 112) } val rgb = ByteArray(px.size * 3).also { b -> px.forEachIndexed { i, p -> b[3 * i] = (p shr 16).toByte(); b[3 * i + 1] = (p shr 8).toByte(); b[3 * i + 2] = p.toByte() } } val sha = MessageDigest.getInstance("SHA-256").digest(rgb).joinToString("") { "%02x".format(it) } if (sha == c["crop_rgb_sha256"]!!.jsonPrimitive.content) bytesOk++ else say("agree $name: its bytes differ from the iPhone's ($sha)") val want = c["vector"]!!.jsonArray.map { it.jsonPrimitive.double.toFloat() }.toFloatArray() var v = FloatArray(0) repeat(REPS) { val s = System.nanoTime() v = model.vector(rgb) times += (System.nanoTime() - s) / 1e6 } val cos = HyperFace.cosine(v, HyperFace.unit(want)).toDouble() worst = minOf(worst, cos) say("agree $name: cosine %.6f".format(cos)) } val nativeAfter = Debug.getNativeHeapAllocatedSize() model.close() val t = times.toDoubleArray() say("agree summary: ${cases.size} crops (${bytesOk} with the iPhone's very bytes), min cosine %.6f, needed %.4f: %s | ms per face p50 %.1f p95 %.1f over %d | load %.0f ms, native heap +%d MB" .format(worst, min, if (worst >= min && bytesOk == cases.size) "MATCH" else "NO MATCH", Pace.percentile(t, .5), Pace.percentile(t, .95), t.size, loadMs, (nativeAfter - nativeBefore) / 1_000_000)) } private fun thumbs(app: Context, per: Int) { val items = MediaLibrary(app).readAll().items.filter { !it.trashed } val reader = ResolverPictures(app) val kinds = items.groupBy { i -> when { i.video -> "video" i.mime == "image/png" -> "png" i.mime.contains("dng") || i.name.endsWith(".dng", true) -> "raw" i.relativePath.contains("WhatsApp", true) -> "jpeg-whatsapp" else -> "jpeg-camera" } } for ((kind, all) in kinds.toSortedMap()) { val sample = all.sortedBy { it.id }.let { l -> if (l.size <= per) l else l.filterIndexed { k, _ -> k % (l.size / per) == 0 }.take(per) } val got = ArrayList<Int>(); val src = ArrayList<Int>(); var under = 0; var closer = 0; var owed = 0; var failed = 0 val sizes = HashMap<String, Int>() for (i in sample) { val q = runCatching { app.contentResolver.loadThumbnail(i.uri(), Size(LookPicture.ASK, LookPicture.ASK), null) }.getOrNull() if (q == null) { failed++ } else { val long = maxOf(q.width, q.height) got += long; sizes.merge("${q.width}x${q.height}", 1, Int::plus); q.recycle() if (long < LookPicture.need(i)) under++ } src += maxOf(i.width, i.height) val f = runCatching { LookPicture.fetch(reader, i) }.getOrNull() when { f == null -> Unit f.owed != null -> owed++ q == null || maxOf(q.width, q.height) < LookPicture.need(i) -> closer++ } } val g = got.map { it.toDouble() }.toDoubleArray(); val s = src.map { it.toDouble() }.toDoubleArray() Log.i(THUMBS, "thumbs $kind: n=${sample.size} of ${all.size}, asked ${LookPicture.ASK}: long edge min ${got.minOrNull()} p50 ${Pace.percentile(g, .5).toInt()} max ${got.maxOrNull()} " + "(original's p50 ${Pace.percentile(s, .5).toInt()}); under the look's need $under, none at all $failed; LookPicture: closer decode $closer, owed $owed | sizes ${sizes.entries.sortedByDescending { it.value }.take(4).joinToString { "${it.key}×${it.value}" }}") } } companion object { private const val AGREE = "albums.agree" private const val THUMBS = "albums.thumbs" private const val REPS = 5 }}