library:ocr: PP-OCRv5 on :library:ml, and ncnn out of photos and pdf
- Commit
9c6a2363d79ebefd657f817a9e2e35a28546b9ea- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 20:59 UTC (3 months ago)
- Parents
2f8f3a8
Diff
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex f4b55305cd..bb4f6ee2dd 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -64,7 +64,7 @@ So a clean install transcribes with no network, but speaking still needs one voi Both are **build-host** dependencies only, pinned by upstream revision *and* file SHA-256 in `scripts/ml/fetch_and_convert.sh`, with provenance in a `README.md` beside each asset and the source ONNX SHA-256 baked into each `.vkml` header. If either vanished, shipped builds keep working. The ONNX itself is not vendored: it is twice the size and nothing reads it at run time. -The trade-off accepted is **GPU-only**: `:library:ml` needs Vulkan 1.1 plus `VK_KHR_shader_float16_int8`, which was promoted to core only in Vulkan 1.2 and so is optional at the 1.1 floor minSdk 31 guarantees. On a device without it, portrait bokeh and auto-select-subject turn off rather than falling back to CPU. `camera` sheds ncnn entirely as a result — `libncnn_android.so` is no longer in that APK — while `photos` keeps it for its two face models.+The trade-off accepted is **GPU-only**: `:library:ml` needs Vulkan 1.1 plus `VK_KHR_shader_float16_int8`, which was promoted to core only in Vulkan 1.2 and so is optional at the 1.1 floor minSdk 31 guarantees. On a device without it, portrait bokeh, auto-select-subject and OCR turn off rather than falling back to CPU. `camera`, `photos` and `pdf` shed ncnn entirely as a result, so `libncnn_android.so` is in none of those APKs, leaving `speech` and `translate` as its only consumers. Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `contacts` (only `libphonenumber` locally), `files`, `notes` (Room + Ink), `things`, `camera` (on-device MediaPipe Selfie Segmentation on `:library:ml`), `pdf` (Rust `libpdf_render.so`), `music` (Media3 ExoPlayer + local scan), `games/*`, `passwords` (biometric + KeePass), `library/*`, `health` (including food search, which ships its database in the APK). @@ -74,11 +74,11 @@ Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `conta ### Build Infrastructure -- **Maven repositories**: `google()` (filtered), `mavenCentral()`, `gradlePluginPortal()` in `build-logic/settings`, plus **`https://jitpack.io`** in root `settings.gradle.kts`. JitPack builds **two** personal forks: `Stockfish-Library` (games:chess) and `ncnn-android` (`library:ocr`, `photos`, `speech`, `translate` — no longer `camera`, which moved to `:library:ml`). `nanojson` was vendored to `:third_party:nanojson` (✅ mitigation #2). JitPack remains a reproducible-build SPOF for both.+- **Maven repositories**: `google()` (filtered), `mavenCentral()`, `gradlePluginPortal()` in `build-logic/settings`, plus **`https://jitpack.io`** in root `settings.gradle.kts`. JitPack builds **two** personal forks: `Stockfish-Library` (games:chess) and `ncnn-android` (`speech` and `translate` only, now that `camera`, `photos`, `pdf` and `library:ocr` have all moved to `:library:ml`). `nanojson` was vendored to `:third_party:nanojson` (✅ mitigation #2). JitPack remains a reproducible-build SPOF for both. - **Launch icon generator**: `build-logic/src/main/kotlin/LauncherIconGen.kt` downloads `https://raw.githubusercontent.com/google/material-design-icons/819d786.../symbols/android/{icon}/...24px.xml` at build time, cached under `~/.gradle/material-symbols-cache`. Build needs GitHub availability on first (uncached) build. ⚠️ Not yet mitigated. - **Alpha toolchain**: `agp = 9.4.0-alpha04`, `composeBom = 2026.06.01` (future-dated), `navigation3 = 1.2.0-alpha05`, `material3 = 1.5.0-alpha23`, `biometric = 1.4.0-alpha07`, `camerax = 1.7.0-alpha02`, `datastore = 1.3.0-alpha09`. ⚠️ Stable release branch should pin stable versions (not yet done). - **Version drift**: `okhttp 4.12.0` (2y old, 5.x exists) ⚠️ still pinned. `ktor` fully removed (`:messages` migrated to `:library:network` ✅) and `mediapipe tasks-vision` unified at `0.10.35` (camera inline `0.10.14` removed ✅).-- **Vendored third_party**: `third_party/nanojson/` (vendored `TeamNewPipe/nanojson`, was JitPack — ✅ mitigation #2), `third_party/om-file-format-sys/` (C + Rust bindings for `open-meteo/om-file-format` GPL-2.0-only) patched for reproducible `readdir` sort, `maps/src/main/cpp/sqlite3.c` amalgamation (SQLite NDK workaround), `youpipe/extractor/` full NewPipe Extractor GPLv3, `library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.{param,bin}` + `latin_PP_OCRv5_mobile_rec.ncnn.{param,bin}` from `RapidAI/RapidOCR` Apache-2.0 (ncnn conversions — `:library:ocr` ships no `.onnx`).+- **Vendored third_party**: `third_party/nanojson/` (vendored `TeamNewPipe/nanojson`, was JitPack — ✅ mitigation #2), `third_party/om-file-format-sys/` (C + Rust bindings for `open-meteo/om-file-format` GPL-2.0-only) patched for reproducible `readdir` sort, `maps/src/main/cpp/sqlite3.c` amalgamation (SQLite NDK workaround), `youpipe/extractor/` full NewPipe Extractor GPLv3. The two unattributable `RapidAI/RapidOCR` ncnn conversions that were in `library/ocr/src/main/assets/` are **gone**: PP-OCRv5 detection and recognition are now `.vkml`, converted from PaddlePaddle's own Apache-2.0 ONNX exports and each SHA-256-pinned in `scripts/ml/fetch_and_convert.sh`. All versions in `gradle/libs.versions.toml`. Rust versions unified in root `/Cargo.toml` (workspace resolver 2, mirrors Gradle catalog) – see `/scripts/rust-deps-count.sh`.
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 057cec8ed6..0dc2bf4929 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -48,6 +48,38 @@ internal object MlNative { /** Bring up MobileFaceNet face embedding. Returns 0 on failure, as [createSelfie]. */ external fun createMobilefacenet(weights: ByteArray): Long+ /**+ * Bring up both PP-OCRv5 networks and the character table. Returns 0 on failure.+ *+ * Three assets because they are three files: DBNet detection, CTC recognition, and the+ * 836-line dictionary the labels index. Detection runs at a fixed 960x960 square and+ * recognition at a fixed 48x320, so each records its command buffer once.+ *+ * The returned handle is **not** interchangeable with the others: it is freed by+ * [destroyOcr], not [destroy].+ */+ external fun createPpocr(detection: ByteArray, recognition: ByteArray, keys: String): Long+ /**+ * Recognise every line in [pixels] and return them tab-separated, or null on failure.+ *+ * One region per line of the result: the text, then eight quad coordinates in+ * source-bitmap pixels, then the confidence, then `1` or `0` for vertical - ten+ * tab-separated fields after the text.+ *+ * Detection, the rotated crops, recognition of each, the CTC collapse and reading+ * order all happen natively, so this crosses the boundary once per bitmap rather than+ * once per line. An empty string means no text, which is not a failure.+ *+ * Packing text and geometry into one string is safe rather than lucky: the dictionary+ * holds 836 single non-whitespace characters plus a space, so no decoded line can+ * contain a tab or a newline.+ */+ external fun recognizeText(+ handle: Long,+ pixels: IntArray,+ width: Int,+ height: Int,+ ): String? /** * Detect faces in [pixels] and return them flattened, nine floats per face.@@ -90,4 +122,13 @@ internal object MlNative { * closed. */ external fun destroy(handle: Long)+ /**+ * Free both PP-OCRv5 networks and the dictionary. Exactly once per non-zero handle+ * from [createPpocr].+ *+ * Separate from [destroy] because the handle is a different native type. Passing one to+ * the other is undefined, which is why there are two functions rather than one that+ * guesses.+ */+ external fun destroyOcr(handle: Long) }
library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.ktnew file mode 100644index 0000000000..864c390cf0--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt@@ -0,0 +1,154 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap+import android.util.Log++/**+ * One recognised line of text, in source-bitmap pixel coordinates.+ *+ * [corners] are the four corners of the region's oriented quad, ordered so that corner 0 to+ * 1 runs along the text and 0 to 3 spans its height. A detected region is a *rotated*+ * rectangle, not an upright one, so the quad carries information a rect would lose - and+ * [left]/[top]/[right]/[bottom] are its axis-aligned bounds for callers that only need one.+ */+data class RecognizedLine(+ val text: String,+ val confidence: Float,+ val corners: List<Pair<Float, Float>>,+ val vertical: Boolean,+) {+ val left: Float get() = corners.minOf { it.first }+ val top: Float get() = corners.minOf { it.second }+ val right: Float get() = corners.maxOf { it.first }+ val bottom: Float get() = corners.maxOf { it.second }+}++/**+ * On-device text recognition: PP-OCRv5 mobile detection and recognition on Vulkan compute.+ *+ * Replaces the ncnn PP-OCR path. The detector is DBNet over a PP-HGNetV2 backbone and the+ * recogniser is a PP-LCNetV3 backbone into a two-block transformer with a CTC head, both+ * converted to `.vkml` by `scripts/ml/ppocr_fold.py`. The recogniser is the **latin** model+ * - 836 characters covering Latin-script languages, no CJK - which is what keeps it under+ * 4 MB.+ *+ * Everything between the two networks happens natively: the rotated crop out of each+ * detected quad, the CTC collapse, and reading order. So [recognize] crosses the JNI+ * boundary once per bitmap rather than once per line.+ *+ * # Availability+ *+ * The constructor never throws. [isAvailable] is false when `libmodelrunner.so` is missing+ * for this ABI, when an asset is absent, or when the device cannot give us a Vulkan device+ * with fp16 compute - and then [recognize] returns an empty list. Vulkan 1.1 with+ * `shaderFloat16` is available across the minSdk 31 fleet, so this is a guard rather than+ * an expected path.+ *+ * # Threading+ *+ * Not thread-safe, and holding a lock across the whole of [recognize] and [close] is+ * required rather than advisable: the native handle is freed by [close] and reading it+ * afterwards is a use-after-free. See `BokehAnalyzer`, whose comments record what that+ * looked like when it happened.+ *+ * Not cheap to construct either - two nets, two arenas, two command buffers - so build one+ * per batch of images and [close] it, rather than one per image.+ */+class TextRecognizer(+ context: Context,+ detectionAsset: String = DETECTION_ASSET,+ recognitionAsset: String = RECOGNITION_ASSET,+ dictionaryAsset: String = DICTIONARY_ASSET,+) : AutoCloseable {+ private var handle: Long = 0L+ private var pixels: IntArray? = null++ init {+ handle = if (!MlNative.isAvailable) {+ 0L+ } else {+ try {+ val assets = context.assets+ val detection = assets.open(detectionAsset).use { it.readBytes() }+ val recognition = assets.open(recognitionAsset).use { it.readBytes() }+ val keys = assets.open(dictionaryAsset).use { it.readBytes() }.decodeToString()+ MlNative.createPpocr(detection, recognition, keys)+ } catch (e: Throwable) {+ Log.e(TAG, "cannot open the PP-OCRv5 assets", e)+ 0L+ }+ }+ }++ /** True if both networks came up and the dictionary parsed. */+ val isAvailable: Boolean get() = handle != 0L++ /**+ * Recognise every line in [bitmap], in reading order.+ *+ * Returns an empty list when there is no text, when the engine is unavailable, or when+ * the pass failed - all three are "no text here" to a caller, and the reason is in+ * logcat under `ModelRunner`. The caller's [bitmap] is not recycled.+ */+ fun recognize(bitmap: Bitmap): List<RecognizedLine> {+ if (handle == 0L) return emptyList()+ // `HARDWARE` bitmaps cannot be read with getPixels, and a null config means the+ // bitmap was already recycled.+ val readable = if (bitmap.config == Bitmap.Config.ARGB_8888) {+ bitmap+ } else {+ bitmap.copy(Bitmap.Config.ARGB_8888, false) ?: return emptyList()+ }+ try {+ val count = readable.width * readable.height+ val buffer = pixels?.takeIf { it.size == count } ?: IntArray(count).also { pixels = it }+ readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)+ val packed = MlNative.recognizeText(handle, buffer, readable.width, readable.height)+ ?: return emptyList()+ return parse(packed)+ } finally {+ if (readable !== bitmap) readable.recycle()+ }+ }++ /** Free both networks. Idempotent. */+ override fun close() {+ val live = handle+ handle = 0L+ pixels = null+ if (live != 0L) MlNative.destroyOcr(live)+ }++ private companion object {+ private const val TAG = "TextRecognizer"+ const val DETECTION_ASSET = "ppocr_det.vkml"+ const val RECOGNITION_ASSET = "ppocr_rec.vkml"+ const val DICTIONARY_ASSET = "ppocr_keys.txt"++ /** Text, then eight quad coordinates, then confidence, then the vertical flag. */+ private const val FIELDS = 11++ /**+ * Unpack what `MlNative.recognizeText` returns.+ *+ * A malformed region is dropped rather than throwing: the native side and this+ * function have to agree about eleven fields, and losing one line is a better+ * failure than losing the image.+ */+ fun parse(packed: String): List<RecognizedLine> {+ if (packed.isEmpty()) return emptyList()+ return packed.split('\n').mapNotNull { row ->+ val fields = row.split('\t')+ if (fields.size != FIELDS) return@mapNotNull null+ val numbers = fields.drop(1).map { it.toFloatOrNull() ?: return@mapNotNull null }+ RecognizedLine(+ text = fields[0],+ confidence = numbers[8],+ corners = List(4) { Pair(numbers[it * 2], numbers[it * 2 + 1]) },+ vertical = numbers[9] != 0f,+ )+ }+ }+ }+}
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 83a0b0d2b3..e354244902 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -26,13 +26,17 @@ //! and every entry point tolerates it, so a device without fp16 compute degrades to "no //! bokeh" rather than to a crash. -use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray};-use jni::sys::{jfloatArray, jint, jlong};+use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JString};+use jni::sys::{jfloatArray, jint, jlong, jstring}; use jni::JNIEnv; -use crate::nets::{mobilefacenet, scrfd, selfie, u2netp};+use crate::nets::{mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp};+use crate::post::ctc::Dictionary; use crate::post::nms::{self, Face, Maps};-use crate::preprocess::{Letterbox, FACE_EMBED, IMAGENET, RESCALE_ONLY, SCRFD};+use crate::post::ocr::{self, Line};+use crate::preprocess::{+ Letterbox, FACE_EMBED, IMAGENET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD,+}; use crate::vulkan::context; use crate::vulkan::run::Net; use crate::weights::{graph, Weights};@@ -315,6 +319,197 @@ fn detect(state: &mut Handle, width: u32, height: u32) -> Result<Vec<f32>, Strin Ok(flat) } +/// Both PP-OCRv5 networks and the dictionary between them. A separate handle type from+/// [`Handle`] because it owns two `Net`s, and separately destroyed for the same reason:+/// one `destroy` that guessed which kind of pointer it had been given would be a+/// type-confusion bug waiting for a caller to mix them up.+struct OcrHandle {+ det: Net,+ rec: Net,+ dictionary: Dictionary,+ pixels: Vec<i32>,+}++/// `TextRecognizer`'s constructor: detection at a fixed square, recognition at a fixed+/// width, and the character table. Returns 0 on failure, having logged why.+///+/// Three assets rather than one because they are three files in the APK, and the dictionary+/// arrives as a `String` rather than bytes because Kotlin already has to decode it as UTF-8+/// to know it is text.+///+/// # Safety+///+/// Called only by the JVM, with a valid `env` and arrays it owns.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createPpocr<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ detection: JByteArray<'l>,+ recognition: JByteArray<'l>,+ keys: JString<'l>,+) -> jlong {+ match build_ocr(&mut env, detection, recognition, keys) {+ Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+ Err(e) => {+ log(&format!("ppocr is unavailable: {e}"));+ 0+ }+ }+}++fn build_ocr<'l>(+ env: &mut JNIEnv<'l>,+ detection: JByteArray<'l>,+ recognition: JByteArray<'l>,+ keys: JString<'l>,+) -> Result<OcrHandle, String> {+ let det_bytes = env+ .convert_byte_array(&detection)+ .map_err(|e| format!("cannot read the detection weights: {e}"))?;+ let rec_bytes = env+ .convert_byte_array(&recognition)+ .map_err(|e| format!("cannot read the recognition weights: {e}"))?;+ let text: String = env+ .get_string(&keys)+ .map_err(|e| format!("cannot read the dictionary: {e}"))?+ .into();+ let dictionary = Dictionary::parse(&text)?;++ let det_weights = Weights::parse(&det_bytes, graph::PPOCR_DET)?;+ let rec_weights = Weights::parse(&rec_bytes, graph::PPOCR_REC)?;+ let shared = context::shared()?;+ // Both at fixed shapes so each records its command buffer once; see `post::ocr`.+ let det_plan = ppocr_det::build(&det_weights, ppocr_det::LONG_SIDE, ppocr_det::LONG_SIDE)?;+ let rec_plan = ppocr_rec::build(&rec_weights, ocr::REC_WIDTH)?;+ Ok(OcrHandle {+ det: Net::new(shared.clone(), det_plan, &det_weights, PPOCR_DET)?,+ rec: Net::new(shared, rec_plan, &rec_weights, PPOCR_REC)?,+ dictionary,+ pixels: Vec::new(),+ })+}++/// Recognise every line in `pixels` and return them as tab-separated text.+///+/// One line per region: `text`, then eight quad coordinates in source-bitmap pixels, then+/// the confidence, then `1` or `0` for vertical — ten fields after the text, tab-separated,+/// regions separated by newlines.+///+/// A string rather than a `float[]` plus a `String[]`, because the geometry and the text+/// belong to the same region and two arrays would have to be kept in step across the+/// boundary. It is safe to pack this way rather than lucky: the dictionary is 836 single+/// non-whitespace characters plus a space, so a decoded line can contain neither a tab nor+/// a newline, and `ctc::Dictionary::parse` rejects a file that broke that.+///+/// Returns null on failure or on a `0` handle. An empty string means no text, which is not+/// an error.+///+/// # Safety+///+/// `handle` must be `0` or a value returned by+/// [`Java_com_vayunmathur_library_ml_MlNative_createPpocr`] and not yet destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_recognizeText<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ pixels: JIntArray<'l>,+ width: jint,+ height: jint,+) -> jstring {+ let null = std::ptr::null_mut();+ if handle == 0 || width <= 0 || height <= 0 {+ return null;+ }+ // SAFETY: as `segment` — the caller guarantees the handle is live and serialises this+ // against `destroyOcr`.+ let state = unsafe { &mut *(handle as *mut OcrHandle) };++ if let Err(e) = read_pixels(&mut env, &pixels, width, height, &mut state.pixels) {+ log(&e);+ return null;+ }+ let lines = match read_text(state, width as u32, height as u32) {+ Ok(lines) => lines,+ Err(e) => {+ log(&format!("OCR failed: {e}"));+ return null;+ }+ };+ match env.new_string(encode(&lines)) {+ Ok(text) => text.into_raw(),+ Err(e) => {+ log(&format!("cannot return the text: {e}"));+ null+ }+ }+}++/// Detect, crop, recognise and order. The Vulkan half of `post::ocr::lines`.+fn read_text(state: &mut OcrHandle, width: u32, height: u32) -> Result<Vec<Line>, String> {+ let fit = Letterbox::square(width, height, ppocr_det::LONG_SIDE)?;+ let maps = state.det.infer_letterboxed(&state.pixels, width, height, &fit)?;+ let probability = match maps.as_slice() {+ [only] => only,+ other => return Err(format!("detection returned {} maps, not one", other.len())),+ };+ let (map_w, map_h) = state.det.output_size()?;+ // Disjoint field borrows: the recogniser is taken mutably while the pixels and the+ // dictionary are read, which is why this is not `state.rec.infer(...)` inline.+ let OcrHandle { rec, dictionary, pixels, .. } = state;+ ocr::lines(+ &ocr::Detection { probability, width: map_w, height: map_h, fit: &fit },+ &ocr::Source { pixels, width, height },+ dictionary,+ |crop, crop_w, crop_h| rec.infer(crop, crop_w, crop_h),+ )+}++/// Pack the lines into the tab-separated form described on `recognizeText`.+fn encode(lines: &[Line]) -> String {+ let mut out = String::new();+ for line in lines {+ if !out.is_empty() {+ out.push('\n');+ }+ out.push_str(&line.text);+ for (x, y) in &line.corners {+ out.push('\t');+ out.push_str(&format!("{x}"));+ out.push('\t');+ out.push_str(&format!("{y}"));+ }+ out.push('\t');+ out.push_str(&format!("{}", line.confidence));+ out.push('\t');+ out.push(if line.vertical { '1' } else { '0' });+ }+ out+}++/// Free both networks and the dictionary.+///+/// Separate from [`Java_com_vayunmathur_library_ml_MlNative_destroy`] because the handle is+/// a different type; passing one to the other is undefined.+///+/// # Safety+///+/// `handle` must be `0` or a value returned by+/// [`Java_com_vayunmathur_library_ml_MlNative_createPpocr`], and must not be used again.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyOcr<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if handle == 0 {+ return;+ }+ // SAFETY: the caller guarantees this came from `createPpocr` and has not been+ // destroyed. Each `Net`'s Drop waits for the device to go idle.+ drop(unsafe { Box::from_raw(handle as *mut OcrHandle) });+}+ /// Copy a Java `int[]` of ARGB pixels into `into`, checking it against `width` x `height`. fn read_pixels<'l>( env: &mut JNIEnv<'l>,
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex 043bbb7fd4..596dc69acb 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -1737,7 +1737,7 @@ mod tests { keys.push('\n'); } let dictionary = crate::post::ctc::Dictionary::parse(&keys).expect("parses");- let decoded = crate::post::ctc::decode(&logits, &dictionary).expect("decodes");+ let decoded = crate::post::ctc::decode(&logits, steps, &dictionary).expect("decodes"); println!("ppocr_rec: {:?} at {:.4}", decoded.text, decoded.confidence); assert!( (0.0..=1.0).contains(&decoded.confidence),
library/ml/src/main/rust/src/post/ctc.rs
diff --git a/library/ml/src/main/rust/src/post/ctc.rs b/library/ml/src/main/rust/src/post/ctc.rsindex ab1c9d7f2e..60379f4b4d 100644--- a/library/ml/src/main/rust/src/post/ctc.rs+++ b/library/ml/src/main/rust/src/post/ctc.rs@@ -93,10 +93,17 @@ pub struct Decoded { /// /// # Layout: class-major, and raw ///-/// `logits` is [`LOGITS`] * `steps` values in **class-major** order — every timestep's+/// `logits` is [`LOGITS`] * `timesteps` values in **class-major** order — every timestep's /// value for label 0, then every one for label 1, and so on. That is `[LOGITS, 1, T]`, /// exactly what [`crate::nets::ppocr_rec`] writes, so nothing transposes anything. ///+/// `used` is how many leading timesteps to read, which is not always all of them.+/// Recognition runs at one fixed width so that a single compiled plan serves every line, so+/// a short crop sits in the left of the input and mid-grey padding fills the rest. Upstream+/// PaddleOCR avoids the question by batching lines of similar aspect ratio, which makes its+/// padding narrow; here it can be most of the strip, and decoding it invites a hallucinated+/// character on the end of every short word.+/// /// The values are **raw logits**, not probabilities. The export ends in a `Softmax` over /// the 838 classes and this runtime deliberately does not run it, because the decode does /// not need it:@@ -111,7 +118,7 @@ pub struct Decoded { /// /// The classic CTC collapse: a label repeated across consecutive timesteps is one /// character, and a blank between two identical labels is what separates them into two.-pub fn decode(logits: &[f32], dictionary: &Dictionary) -> Result<Decoded, String> {+pub fn decode(logits: &[f32], used: usize, dictionary: &Dictionary) -> Result<Decoded, String> { let labels = dictionary.labels(); if labels != LOGITS { return Err(format!("a dictionary of {labels} labels, expected {LOGITS}"));@@ -125,10 +132,13 @@ pub fn decode(logits: &[f32], dictionary: &Dictionary) -> Result<Decoded, String logits.len() )); }- let steps = logits.len() / labels;+ let timesteps = logits.len() / labels;+ if used > timesteps {+ return Err(format!("{used} of {timesteps} timesteps requested"));+ } let at = |label: usize, step: usize| -> Result<f32, String> { logits- .get(label * steps + step)+ .get(label * timesteps + step) .copied() .ok_or_else(|| format!("label {label} of timestep {step} is outside the map")) };@@ -138,7 +148,7 @@ pub fn decode(logits: &[f32], dictionary: &Dictionary) -> Result<Decoded, String let mut kept = 0u32; let mut previous = usize::MAX; - for step in 0..steps {+ for step in 0..used { let mut best = 0; let mut peak = at(0, step)?; for label in 1..labels {@@ -204,6 +214,11 @@ mod tests { map } + /// [`decode`] over every timestep in the map, which is what most fixtures want.+ fn all(logits: &[f32], dictionary: &Dictionary) -> Result<Decoded, String> {+ decode(logits, logits.len() / LOGITS, dictionary)+ }+ /// The softmax probability of a winner at `logit` when every other label is zero: /// `1 / (1 + 837 * exp(-logit))`. ///@@ -233,7 +248,7 @@ mod tests { fn a_run_of_one_label_collapses_to_one_character() { let d = dictionary(); // Different logits across the run, so "only the first is scored" is observable.- let got = decode(&logits(&[(1, 10.0), (1, 8.0), (1, 12.0)]), &d).expect("decodes");+ let got = all(&logits(&[(1, 10.0), (1, 8.0), (1, 12.0)]), &d).expect("decodes"); assert_eq!(got.text, "a"); let want = probability(10.0) as f32; assert!((got.confidence - want).abs() < 1e-6, "{} vs {want}", got.confidence);@@ -245,7 +260,7 @@ mod tests { // probability comes from. A decoder that returned the logit itself would report // 10.0, and one that forgot the 836 other zero-logit classes would report 1/2. let d = dictionary();- let got = decode(&logits(&[(3, 10.0)]), &d).expect("decodes");+ let got = all(&logits(&[(3, 10.0)]), &d).expect("decodes"); let want = (1.0 / (1.0 + 837.0 * (-10.0f64).exp())) as f32; assert!((got.confidence - want).abs() < 1e-6, "{} vs {want}", got.confidence); // Sanity: 837 competitors at logit zero against one at 10 is confident but not@@ -258,7 +273,7 @@ mod tests { // Every label equally likely is 1/838, and it is the blank that wins a tie at // label 0 — so nothing is emitted and the confidence falls back to zero. let d = dictionary();- let got = decode(&vec![0.5; LOGITS], &d).expect("decodes");+ let got = all(&vec![0.5; LOGITS], &d).expect("decodes"); assert_eq!(got.text, ""); assert_eq!(got.confidence, 0.0); // With a non-blank winner the same flat field gives chance plus a little.@@ -266,7 +281,7 @@ mod tests { if let Some(slot) = map.get_mut(2) { *slot = f32::MIN_POSITIVE; }- let got = decode(&map, &d).expect("decodes");+ let got = all(&map, &d).expect("decodes"); assert_eq!(got.text, "b"); let chance = 1.0 / LOGITS as f32; assert!((got.confidence - chance).abs() < 1e-6, "{} vs {chance}", got.confidence);@@ -277,14 +292,14 @@ mod tests { // The whole reason CTC has a blank: without it "aa" is indistinguishable from a // held "a". let d = dictionary();- let got = decode(&logits(&[(1, 10.0), (0, 8.0), (1, 9.0)]), &d).expect("decodes");+ let got = all(&logits(&[(1, 10.0), (0, 8.0), (1, 9.0)]), &d).expect("decodes"); assert_eq!(got.text, "aa"); } #[test] fn blanks_contribute_no_characters_and_no_confidence() { let d = dictionary();- let got = decode(&logits(&[(0, 12.0), (0, 12.0)]), &d).expect("decodes");+ let got = all(&logits(&[(0, 12.0), (0, 12.0)]), &d).expect("decodes"); assert_eq!(got.text, ""); assert_eq!(got.confidence, 0.0); }@@ -292,7 +307,7 @@ mod tests { #[test] fn distinct_adjacent_labels_both_survive_without_a_blank() { let d = dictionary();- let got = decode(&logits(&[(1, 10.0), (2, 8.0), (3, 12.0)]), &d).expect("decodes");+ let got = all(&logits(&[(1, 10.0), (2, 8.0), (3, 12.0)]), &d).expect("decodes"); assert_eq!(got.text, "abc"); // The mean of all three, since none is a repeat. let want =@@ -303,7 +318,7 @@ mod tests { #[test] fn the_space_label_decodes_to_a_space() { let d = dictionary();- let got = decode(&logits(&[(1, 10.0), (LOGITS - 1, 9.0), (2, 8.0)]), &d)+ let got = all(&logits(&[(1, 10.0), (LOGITS - 1, 9.0), (2, 8.0)]), &d) .expect("decodes"); assert_eq!(got.text, "a b"); }@@ -322,7 +337,7 @@ mod tests { *slot = 10.0; } }- let got = decode(&map, &d).expect("decodes");+ let got = all(&map, &d).expect("decodes"); assert_eq!(got.text, "a"); } @@ -337,17 +352,41 @@ mod tests { *slot = value; } }- let got = decode(&column, &d).expect("decodes");+ let got = all(&column, &d).expect("decodes"); assert_eq!(got.text, "e"); } + #[test]+ fn only_the_used_timesteps_are_decoded() {+ // Recognition pads a short crop out to a fixed width, and the padded strip is not+ // image. Reading it invents a character on the end of every short word, which is+ // exactly the failure a fixed-width plan introduces and upstream's aspect-ratio+ // batching avoids.+ let d = dictionary();+ let map = logits(&[(1, 10.0), (2, 10.0), (3, 10.0), (4, 10.0)]);+ assert_eq!(all(&map, &d).expect("decodes").text, "abcd");+ assert_eq!(decode(&map, 2, &d).expect("decodes").text, "ab");+ // Zero used timesteps is a crop with no content, not an error.+ let empty = decode(&map, 0, &d).expect("decodes");+ assert_eq!(empty.text, "");+ assert_eq!(empty.confidence, 0.0);+ }++ #[test]+ fn asking_for_more_timesteps_than_the_map_holds_is_refused() {+ let d = dictionary();+ let map = logits(&[(1, 10.0), (2, 10.0)]);+ let error = decode(&map, 3, &d).expect_err("three of two");+ assert!(error.contains("3 of 2 timesteps"), "{error}");+ }+ #[test] fn an_empty_logit_map_is_refused_rather_than_decoding_to_nothing() { // A zero-timestep map means the recogniser produced nothing, which is a failure // upstream. Returning empty text would make it indistinguishable from a crop that // genuinely holds no characters. let d = dictionary();- let error = decode(&[], &d).expect_err("an empty map");+ let error = decode(&[], 0, &d).expect_err("an empty map"); assert!(error.contains("no logits"), "{error}"); } @@ -383,7 +422,7 @@ mod tests { #[test] fn a_ragged_logit_array_is_refused() { let d = dictionary();- let error = decode(&[0.0; LOGITS + 3], &d).expect_err("ragged");+ let error = decode(&[0.0; LOGITS + 3], 1, &d).expect_err("ragged"); assert!(error.contains("not a whole number"), "{error}"); } }
library/ml/src/main/rust/src/post/mod.rs
diff --git a/library/ml/src/main/rust/src/post/mod.rs b/library/ml/src/main/rust/src/post/mod.rsindex 23ae660c23..82455f2a65 100644--- a/library/ml/src/main/rust/src/post/mod.rs+++ b/library/ml/src/main/rust/src/post/mod.rs@@ -14,3 +14,4 @@ pub mod crop; pub mod ctc; pub mod dbnet; pub mod nms;+pub mod ocr;
library/ml/src/main/rust/src/post/ocr.rs
diff --git a/library/ml/src/main/rust/src/post/ocr.rs b/library/ml/src/main/rust/src/post/ocr.rsnew file mode 100644index 0000000000..2b12d385e4--- /dev/null+++ b/library/ml/src/main/rust/src/post/ocr.rs@@ -0,0 +1,404 @@+//! Detection, cropping, recognition and reading order — the whole OCR request.+//!+//! # Why this is not in `bridge.rs`+//!+//! Everything between the two networks is arithmetic on tens of candidates: threshold the+//! probability map, take each region's oriented rectangle, warp a strip out of the source,+//! collapse the logits, sort the results. None of it touches Vulkan, and all of it is the+//! part that used to live inside the ncnn fork's `ppocrv5.cpp` where it could not be read+//! or tested.+//!+//! So recognition arrives as a **closure**. [`lines`] takes a probability map and a way to+//! turn a crop into logits, which means the sequencing is exercised on the host against a+//! stub recogniser, and `bridge.rs` supplies the real one. The alternative — a function+//! that owns two `Net`s — would be untestable anywhere but a device.+//!+//! # The two fixed shapes+//!+//! Detection runs at a fixed 960x960 square and recognition at a fixed 48x[`REC_WIDTH`], so+//! one compiled plan serves every request. `vulkan::run::Net` records its command buffer+//! once at construction, so a per-image shape would mean compiling a plan and re-recording+//! per request; PaddleOCR pads to a batch's shape for the same reason.+//!+//! The cost is padding. A tall thin photograph wastes detection work on the letterbox, and+//! a short word wastes recognition work on the right of its strip — which is why+//! [`super::ctc::decode`] is told how many timesteps are real.++use super::crop;+use super::ctc::{self, Decoded, Dictionary};+use super::dbnet;+use crate::nets::ppocr_rec;+use crate::preprocess::Letterbox;++/// The width every recognition crop is padded to. 320 is the export's own+/// `image_shape [3, 48, 320]`, so a full-width line is neither squeezed nor stretched.+pub const REC_WIDTH: u32 = 320;++/// What the padding around a crop is filled with, as an 8-bit level.+///+/// PaddleOCR's `resize_norm_img` pads with **zero after normalisation**, and recognition's+/// normalisation is `(v / 255 - 0.5) / 0.5`, so its zero is the raw level 127.5. 128 is the+/// nearest byte — a 0.4% offset on the padded strip, against filling with black, which the+/// net would read as a stroke and turn into characters.+const PAD_LEVEL: u32 = 128;++/// One recognised line, in source-image pixels.+#[derive(Clone, Debug, PartialEq)]+pub struct Line {+ /// The text, already collapsed by [`ctc::decode`].+ pub text: String,+ /// Mean probability of the timesteps that produced it.+ pub confidence: f32,+ /// The region's four corners, `0 -> 1` along the text and `0 -> 3` across it.+ pub corners: [(f32, f32); 4],+ /// True when the run was read as vertical script.+ pub vertical: bool,+}++/// Detection's output: the probability map, its extent, and how the source was fitted into+/// it. Grouped like [`super::nms::Maps`], because the four travel together and mean nothing+/// apart.+pub struct Detection<'a> {+ /// The net's single channel, `width` x `height`, row-major, in `0..1`.+ pub probability: &'a [f32],+ /// The map's width.+ pub width: u32,+ /// The map's height.+ pub height: u32,+ /// How the source was letterboxed in, so the regions come back in source pixels.+ pub fit: &'a Letterbox,+}++/// The image the crops are cut from, as `ARGB_8888`.+pub struct Source<'a> {+ /// `width * height` entries of `0xAARRGGBB`, row-major.+ pub pixels: &'a [i32],+ /// The image's width.+ pub width: u32,+ /// The image's height.+ pub height: u32,+}++/// Detect, crop, recognise and order every line in one image.+///+/// `recognise` is handed a crop as `(pixels, width, height)` and must return the logit map+/// [`ctc::decode`] wants — class-major `[838, T]`. A crop it fails on is skipped rather+/// than abandoning the image: one unreadable region should not lose the other twenty.+pub fn lines(+ detection: &Detection,+ source: &Source,+ dictionary: &Dictionary,+ mut recognise: impl FnMut(&[i32], u32, u32) -> Result<Vec<f32>, String>,+) -> Result<Vec<Line>, String> {+ let regions = dbnet::regions(+ detection.probability,+ detection.width,+ detection.height,+ detection.fit,+ (source.width, source.height),+ )?;+ let mut lines = Vec::with_capacity(regions.len());+ for region in ®ions {+ let corners = crop::corners(®ion.rect);+ let content =+ crop::crop_width(region, ppocr_rec::HEIGHT, ppocr_rec::WIDTH_MULTIPLE, REC_WIDTH);+ let strip = match strip(source, &corners, content) {+ Ok(s) => s,+ Err(_) => continue,+ };+ let logits = match recognise(&strip, REC_WIDTH, ppocr_rec::HEIGHT) {+ Ok(l) => l,+ Err(_) => continue,+ };+ // Only the timesteps the crop actually filled; the rest is padding.+ let used = (content / ppocr_rec::WIDTH_MULTIPLE) as usize;+ let Decoded { text, confidence } = match ctc::decode(&logits, used, dictionary) {+ Ok(d) => d,+ Err(_) => continue,+ };+ let text = text.trim().to_string();+ if text.is_empty() {+ continue;+ }+ lines.push(Line { text, confidence, corners, vertical: region.vertical });+ }+ order(&mut lines);+ Ok(lines)+}++/// Warp `corners` into the left `content` columns of a [`REC_WIDTH`]-wide strip.+///+/// The strip is the recogniser's whole input, so the columns past `content` are the padding+/// described on [`PAD_LEVEL`]. Warping straight into the padded buffer rather than warping+/// and then copying is one pass and no intermediate.+fn strip(+ source: &Source,+ corners: &[(f32, f32); 4],+ content: u32,+) -> Result<Vec<i32>, String> {+ let content = content.clamp(ppocr_rec::WIDTH_MULTIPLE, REC_WIDTH);+ let cropped = crop::warp(+ source.pixels,+ source.width,+ source.height,+ corners,+ content,+ ppocr_rec::HEIGHT,+ )?;+ if content == REC_WIDTH {+ return Ok(cropped);+ }+ let pad = ((0xffu32 << 24) | (PAD_LEVEL << 16) | (PAD_LEVEL << 8) | PAD_LEVEL) as i32;+ let mut out = vec![pad; (REC_WIDTH as usize) * (ppocr_rec::HEIGHT as usize)];+ for row in 0..ppocr_rec::HEIGHT as usize {+ let from = row * content as usize;+ let to = row * REC_WIDTH as usize;+ let source = cropped+ .get(from..from + content as usize)+ .ok_or("the crop is shorter than its own width")?;+ let destination = out+ .get_mut(to..to + content as usize)+ .ok_or("the strip is shorter than the crop")?;+ destination.copy_from_slice(source);+ }+ Ok(out)+}++/// How many pixels of vertical drift still counts as the same row.+///+/// The same band the ncnn path used, so a two-column page keeps its columns rather than+/// interleaving them line by line.+const ROW_BAND: f32 = 16.0;++/// Sort into reading order: down the page, then across each row band.+///+/// Banding on the quad's *centre* rather than its top edge is what keeps a tilted line's+/// regions together — a 3-degree tilt across a page moves the top edge further than the+/// band is wide, and the line comes back shuffled.+fn order(lines: &mut [Line]) {+ let centre = |line: &Line| {+ let sum = line.corners.iter().fold((0.0f32, 0.0f32), |a, p| (a.0 + p.0, a.1 + p.1));+ (sum.0 / 4.0, sum.1 / 4.0)+ };+ lines.sort_by(|a, b| {+ let (ax, ay) = centre(a);+ let (bx, by) = centre(b);+ let band = |y: f32| (y / ROW_BAND).floor() as i64;+ band(ay)+ .cmp(&band(by))+ .then(ax.total_cmp(&bx))+ });+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::post::ctc::LOGITS;++ /// A dictionary of `a`, `b`, `c`, ... at the real length.+ fn dictionary() -> Dictionary {+ let mut text = String::new();+ for index in 0..ctc::DICTIONARY_ENTRIES {+ text.push((b'a' + (index % 26) as u8) as char);+ text.push('\n');+ }+ Dictionary::parse(&text).expect("the fixture dictionary parses")+ }++ /// A logit map whose timestep `t` picks label `labels[t]`, class-major over `steps`.+ fn logits(labels: &[usize], steps: usize) -> Vec<f32> {+ let mut map = vec![0.0f32; LOGITS * steps];+ for (step, &label) in labels.iter().enumerate() {+ if let Some(slot) = map.get_mut(label * steps + step) {+ *slot = 20.0;+ }+ }+ map+ }++ /// A probability map with a filled rectangle, which `dbnet` reads as one region.+ fn blob(map: u32, left: u32, top: u32, right: u32, bottom: u32) -> Vec<f32> {+ let mut values = vec![0.0f32; (map * map) as usize];+ for y in top..bottom {+ for x in left..right {+ if let Some(slot) = values.get_mut((y * map + x) as usize) {+ *slot = 1.0;+ }+ }+ }+ values+ }++ #[test]+ fn a_detected_region_is_cropped_recognised_and_returned() {+ let map = 64u32;+ let probability = blob(map, 8, 24, 56, 36);+ let fit = Letterbox::square(map, map, map).expect("a 1:1 letterbox");+ let pixels = vec![0xffff_ffffu32 as i32; (map * map) as usize];+ let dictionary = dictionary();++ let mut widths = Vec::new();+ let got = lines(+ &Detection { probability: &probability, width: map, height: map, fit: &fit },+ &Source { pixels: &pixels, width: map, height: map },+ &dictionary,+ |crop, w, h| {+ widths.push((w, h, crop.len()));+ Ok(logits(&[1, 2, 3], (REC_WIDTH / ppocr_rec::WIDTH_MULTIPLE) as usize))+ },+ )+ .expect("the pipeline runs");++ assert_eq!(got.len(), 1, "{got:?}");+ assert_eq!(got[0].text, "abc");+ assert!(!got[0].vertical);+ // Recognition always sees the one fixed shape, whatever the region's own size.+ assert_eq!(+ widths,+ vec![(+ REC_WIDTH,+ ppocr_rec::HEIGHT,+ (REC_WIDTH * ppocr_rec::HEIGHT) as usize+ )]+ );+ }++ #[test]+ fn a_crop_shorter_than_the_strip_is_padded_and_only_its_own_timesteps_decoded() {+ // A nearly square region wants far less than 320 columns, so most of the strip is+ // padding. Decoding it would put a character on the end that no pixel supports.+ let map = 64u32;+ let probability = blob(map, 24, 24, 40, 40);+ let fit = Letterbox::square(map, map, map).expect("a 1:1 letterbox");+ let pixels = vec![0xff00_0000u32 as i32; (map * map) as usize];+ let dictionary = dictionary();++ let steps = (REC_WIDTH / ppocr_rec::WIDTH_MULTIPLE) as usize;+ // Every timestep would decode to a distinct letter, so the answer's length is+ // exactly the number of timesteps the pipeline chose to read.+ let labels: Vec<usize> = (0..steps).map(|i| 1 + i % 26).collect();+ let mut seen = None;+ let got = lines(+ &Detection { probability: &probability, width: map, height: map, fit: &fit },+ &Source { pixels: &pixels, width: map, height: map },+ &dictionary,+ |crop, w, _| {+ // The right of the strip is the pad level, not the black source.+ let last = crop.get((w - 1) as usize).copied().unwrap_or(0) as u32;+ seen = Some(last & 0xff);+ Ok(logits(&labels, steps))+ },+ )+ .expect("the pipeline runs");++ assert_eq!(seen, Some(PAD_LEVEL), "the strip was not padded");+ assert_eq!(got.len(), 1, "{got:?}");+ assert!(+ got[0].text.chars().count() < steps,+ "decoded all {steps} timesteps: {:?}",+ got[0].text+ );+ assert!(!got[0].text.is_empty());+ }++ #[test]+ fn a_region_the_recogniser_fails_on_is_skipped_rather_than_losing_the_image() {+ let map = 64u32;+ // Two well-separated runs, so `dbnet` finds two components.+ let mut probability = blob(map, 4, 10, 60, 20);+ for (i, v) in blob(map, 4, 44, 60, 54).iter().enumerate() {+ if *v > 0.0 {+ probability[i] = *v;+ }+ }+ let fit = Letterbox::square(map, map, map).expect("a 1:1 letterbox");+ let pixels = vec![0xffff_ffffu32 as i32; (map * map) as usize];+ let dictionary = dictionary();+ let steps = (REC_WIDTH / ppocr_rec::WIDTH_MULTIPLE) as usize;++ let mut call = 0;+ let got = lines(+ &Detection { probability: &probability, width: map, height: map, fit: &fit },+ &Source { pixels: &pixels, width: map, height: map },+ &dictionary,+ |_, _, _| {+ call += 1;+ if call == 1 {+ Err("this crop failed".to_string())+ } else {+ Ok(logits(&[2], steps))+ }+ },+ )+ .expect("the pipeline runs");+ assert_eq!(call, 2, "the second region was not attempted");+ assert_eq!(got.len(), 1, "{got:?}");+ assert_eq!(got[0].text, "b");+ }++ #[test]+ fn a_blank_recognition_contributes_no_line() {+ // A region whose logits are all blank is a false positive from detection, not an+ // empty string in the output.+ let map = 64u32;+ let probability = blob(map, 8, 24, 56, 36);+ let fit = Letterbox::square(map, map, map).expect("a 1:1 letterbox");+ let pixels = vec![0xffff_ffffu32 as i32; (map * map) as usize];+ let steps = (REC_WIDTH / ppocr_rec::WIDTH_MULTIPLE) as usize;+ let got = lines(+ &Detection { probability: &probability, width: map, height: map, fit: &fit },+ &Source { pixels: &pixels, width: map, height: map },+ &dictionary(),+ |_, _, _| Ok(logits(&[0], steps)),+ )+ .expect("the pipeline runs");+ assert!(got.is_empty(), "{got:?}");+ }++ #[test]+ fn reading_order_goes_down_the_page_then_across_each_band() {+ let line = |text: &str, cx: f32, cy: f32| Line {+ text: text.to_string(),+ confidence: 1.0,+ corners: [+ (cx - 5.0, cy - 2.0),+ (cx + 5.0, cy - 2.0),+ (cx + 5.0, cy + 2.0),+ (cx - 5.0, cy + 2.0),+ ],+ vertical: false,+ };+ // Deliberately out of order, and with two regions in one band.+ let mut got = vec![+ line("second-right", 100.0, 8.0),+ line("third", 10.0, 200.0),+ line("second-left", 20.0, 8.0),+ line("first", 10.0, 1.0),+ ];+ order(&mut got);+ let texts: Vec<&str> = got.iter().map(|l| l.text.as_str()).collect();+ // Bands are 16 tall, so y = 1 and y = 8 share one and sort by x within it.+ assert_eq!(texts, vec!["first", "second-left", "second-right", "third"]);+ }++ #[test]+ fn banding_uses_the_quad_centre_so_a_tilted_line_stays_together() {+ // Two halves of one line across a page, tilted enough that their top edges land in+ // different 16-pixel bands while their centres do not. Banding on the top edge+ // returns them in the wrong order relative to the line below.+ let tilted = |text: &str, x: f32, y: f32, drop: f32| Line {+ text: text.to_string(),+ confidence: 1.0,+ corners: [(x, y), (x + 200.0, y + drop), (x + 200.0, y + drop + 20.0), (x, y + 20.0)],+ vertical: false,+ };+ let mut got = vec![+ tilted("below", 0.0, 60.0, 0.0),+ tilted("right", 200.0, 14.0, 0.0),+ tilted("left", 0.0, 0.0, 14.0),+ ];+ order(&mut got);+ let texts: Vec<&str> = got.iter().map(|l| l.text.as_str()).collect();+ assert_eq!(texts, vec!["left", "right", "below"]);+ }+}
library/ocr/build.gradle.kts
diff --git a/library/ocr/build.gradle.kts b/library/ocr/build.gradle.ktsindex c9f9322e99..74ce66d745 100644--- a/library/ocr/build.gradle.kts+++ b/library/ocr/build.gradle.kts@@ -1,11 +1,14 @@ plugins { id("common-conventions-library") }- dependencies {- // On-device OCR via PP-OCRv5 on ncnn (BSD-3, FOSS, no Play Services / no ML- // Kit). The models + native pipeline ship inside this AAR; consumers only- // see the OcrEngine API.- implementation(libs.ncnn.android)+ // On-device OCR via PP-OCRv5 on the Vulkan compute runtime in `:library:ml`. Both+ // models ship as `.vkml` in this module's assets and the whole detect-crop-recognise+ // pipeline is Rust; consumers only see the OcrEngine API.+ //+ // `implementation` is enough even though `:library:ml` supplies `libmodelrunner.so`:+ // an Android library's jniLibs are packaged into the consuming APK transitively, and+ // OcrEngine maps `RecognizedLine` into its own TextBox rather than re-exporting it.+ implementation(project(":library:ml")) implementation(libs.kotlinx.coroutines.android) }
library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.bin
diff --git a/library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.bin b/library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.bindeleted file mode 100644index 18b2c3d27d..0000000000Binary files a/library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.bin and /dev/null differ
library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.param
diff --git a/library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.param b/library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.paramdeleted file mode 100644index eae40ed0d9..0000000000--- a/library/ocr/src/main/assets/PP_OCRv5_mobile_det.ncnn.param+++ /dev/null@@ -1,279 +0,0 @@-7767517-277 301-Input in0 0 1 in0-Convolution conv_63 1 1 in0 1 0=16 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=432-ConvolutionDepthWise convdw_123 1 1 1 2 0=16 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=144 7=16-BinaryOp mul_0 1 1 2 3 0=2 1=1 2=1.212596e+00-BinaryOp add_1 1 1 3 4 0=0 1=1 2=4.688590e-01-HardSwish hswish_20 1 1 4 5 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_2 1 1 5 6 0=2 1=1 2=5.235000e-03-BinaryOp add_3 1 1 6 7 0=0 1=1 2=2.370000e-04-Convolution conv_64 1 1 7 8 0=32 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=512-BinaryOp mul_4 1 1 8 9 0=2 1=1 2=1.887550e+00-BinaryOp add_5 1 1 9 10 0=0 1=1 2=7.187490e-01-HardSwish hswish_21 1 1 10 11 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_6 1 1 11 12 0=2 1=1 2=6.775130e-01-BinaryOp add_7 1 1 12 13 0=0 1=1 2=-2.291480e-01-ConvolutionDepthWise convdw_124 1 1 13 14 0=32 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=288 7=32-BinaryOp mul_8 1 1 14 15 0=2 1=1 2=5.175000e-03-BinaryOp add_9 1 1 15 16 0=0 1=1 2=3.700000e-04-Convolution conv_65 1 1 16 17 0=48 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=1536-BinaryOp mul_10 1 1 17 18 0=2 1=1 2=8.821770e-01-BinaryOp add_11 1 1 18 19 0=0 1=1 2=1.721456e+00-HardSwish hswish_22 1 1 19 20 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_12 1 1 20 21 0=2 1=1 2=3.677130e-01-BinaryOp add_13 1 1 21 22 0=0 1=1 2=-8.711380e-01-ConvolutionDepthWise convdw_125 1 1 22 23 0=48 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=432 7=48-BinaryOp mul_14 1 1 23 24 0=2 1=1 2=2.412795e+00-BinaryOp add_15 1 1 24 25 0=0 1=1 2=3.955300e-01-HardSwish hswish_23 1 1 25 26 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_16 1 1 26 27 0=2 1=1 2=5.902000e-03-BinaryOp add_17 1 1 27 28 0=0 1=1 2=-3.100000e-05-Convolution conv_66 1 1 28 29 0=48 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304-BinaryOp mul_18 1 1 29 30 0=2 1=1 2=1.333340e+00-BinaryOp add_19 1 1 30 31 0=0 1=1 2=8.556940e-01-HardSwish hswish_24 1 1 31 32 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_20 1 1 32 33 0=2 1=1 2=1.498921e+00-BinaryOp add_21 1 1 33 34 0=0 1=1 2=-5.550210e-01-Split splitncnn_0 1 2 34 35 36-ConvolutionDepthWise convdw_126 1 1 36 37 0=48 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=432 7=48-BinaryOp mul_22 1 1 37 38 0=2 1=1 2=3.545000e-03-BinaryOp add_23 1 1 38 39 0=0 1=1 2=-2.630000e-04-Convolution conv_67 1 1 39 40 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=4608-BinaryOp mul_24 1 1 40 41 0=2 1=1 2=6.118250e-01-BinaryOp add_25 1 1 41 42 0=0 1=1 2=1.892514e+00-HardSwish hswish_25 1 1 42 43 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_26 1 1 43 44 0=2 1=1 2=5.583890e-01-BinaryOp add_27 1 1 44 45 0=0 1=1 2=-9.510200e-01-ConvolutionDepthWise convdw_127 1 1 45 46 0=96 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=864 7=96-BinaryOp mul_28 1 1 46 47 0=2 1=1 2=1.172581e+00-BinaryOp add_29 1 1 47 48 0=0 1=1 2=5.413250e-01-HardSwish hswish_26 1 1 48 49 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_30 1 1 49 50 0=2 1=1 2=9.678300e-02-BinaryOp add_31 1 1 50 51 0=0 1=1 2=2.500000e-05-Convolution conv_68 1 1 51 52 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=9216-BinaryOp mul_32 1 1 52 53 0=2 1=1 2=9.085920e-01-BinaryOp add_33 1 1 53 54 0=0 1=1 2=-6.707300e-02-HardSwish hswish_27 1 1 54 55 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_34 1 1 55 56 0=2 1=1 2=1.541732e+00-BinaryOp add_35 1 1 56 57 0=0 1=1 2=-5.748400e-02-Split splitncnn_1 1 2 57 58 59-ConvolutionDepthWise convdw_128 1 1 59 60 0=96 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=864 7=96-BinaryOp mul_36 1 1 60 61 0=2 1=1 2=2.514000e-03-BinaryOp add_37 1 1 61 62 0=0 1=1 2=5.210000e-04-Convolution conv_69 1 1 62 63 0=192 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=18432-BinaryOp mul_38 1 1 63 64 0=2 1=1 2=7.788890e-01-BinaryOp add_39 1 1 64 65 0=0 1=1 2=1.381536e+00-HardSwish hswish_28 1 1 65 66 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_40 1 1 66 67 0=2 1=1 2=6.538820e-01-BinaryOp add_41 1 1 67 68 0=0 1=1 2=-8.154510e-01-ConvolutionDepthWise convdw_129 1 1 68 69 0=192 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=4800 7=192-BinaryOp mul_42 1 1 69 70 0=2 1=1 2=1.060829e+00-BinaryOp add_43 1 1 70 71 0=0 1=1 2=3.656440e-01-HardSwish hswish_29 1 1 71 72 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_44 1 1 72 73 0=2 1=1 2=4.624000e-03-BinaryOp add_45 1 1 73 74 0=0 1=1 2=7.030000e-04-Convolution conv_70 1 1 74 75 0=192 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=36864-BinaryOp mul_46 1 1 75 76 0=2 1=1 2=1.122729e+00-BinaryOp add_47 1 1 76 77 0=0 1=1 2=4.671230e-01-HardSwish hswish_30 1 1 77 78 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_48 1 1 78 79 0=2 1=1 2=7.904570e-01-BinaryOp add_49 1 1 79 80 0=0 1=1 2=-1.132520e-01-ConvolutionDepthWise convdw_130 1 1 80 81 0=192 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=4800 7=192-BinaryOp mul_50 1 1 81 82 0=2 1=1 2=1.079211e+00-BinaryOp add_51 1 1 82 83 0=0 1=1 2=8.959260e-01-HardSwish hswish_31 1 1 83 84 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_52 1 1 84 85 0=2 1=1 2=2.692300e-02-BinaryOp add_53 1 1 85 86 0=0 1=1 2=-2.730000e-04-Convolution conv_71 1 1 86 87 0=192 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=36864-BinaryOp mul_54 1 1 87 88 0=2 1=1 2=1.026575e+00-BinaryOp add_55 1 1 88 89 0=0 1=1 2=7.920500e-02-HardSwish hswish_32 1 1 89 90 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_56 1 1 90 91 0=2 1=1 2=7.297640e-01-BinaryOp add_57 1 1 91 92 0=0 1=1 2=4.859200e-02-ConvolutionDepthWise convdw_131 1 1 92 93 0=192 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=4800 7=192-BinaryOp mul_58 1 1 93 94 0=2 1=1 2=9.088570e-01-BinaryOp add_59 1 1 94 95 0=0 1=1 2=8.949150e-01-HardSwish hswish_33 1 1 95 96 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_60 1 1 96 97 0=2 1=1 2=5.055000e-03-BinaryOp add_61 1 1 97 98 0=0 1=1 2=9.670000e-04-Convolution conv_72 1 1 98 99 0=192 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=36864-BinaryOp mul_62 1 1 99 100 0=2 1=1 2=1.161839e+00-BinaryOp add_63 1 1 100 101 0=0 1=1 2=-9.637900e-02-HardSwish hswish_34 1 1 101 102 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_64 1 1 102 103 0=2 1=1 2=8.216480e-01-BinaryOp add_65 1 1 103 104 0=0 1=1 2=1.775170e-01-ConvolutionDepthWise convdw_132 1 1 104 105 0=192 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=4800 7=192-BinaryOp mul_66 1 1 105 106 0=2 1=1 2=8.761670e-01-BinaryOp add_67 1 1 106 107 0=0 1=1 2=1.145742e+00-HardSwish hswish_35 1 1 107 108 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_68 1 1 108 109 0=2 1=1 2=7.916000e-03-BinaryOp add_69 1 1 109 110 0=0 1=1 2=9.330000e-04-Convolution conv_73 1 1 110 111 0=192 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=36864-BinaryOp mul_70 1 1 111 112 0=2 1=1 2=8.913130e-01-BinaryOp add_71 1 1 112 113 0=0 1=1 2=-9.041330e-01-HardSwish hswish_36 1 1 113 114 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_72 1 1 114 115 0=2 1=1 2=1.361367e+00-BinaryOp add_73 1 1 115 116 0=0 1=1 2=1.822500e-01-Split splitncnn_2 1 2 116 117 118-ConvolutionDepthWise convdw_133 1 1 118 119 0=192 1=5 11=5 12=1 13=2 14=2 2=1 3=2 4=2 5=1 6=4800 7=192-BinaryOp mul_74 1 1 119 120 0=2 1=1 2=7.035180e-01-BinaryOp add_75 1 1 120 121 0=0 1=1 2=-9.663700e-02-Split splitncnn_3 1 2 121 122 123-Pooling gap_0 1 1 123 124 0=1 4=1-Convolution convrelu_0 1 1 124 125 0=48 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=9216 9=1-Convolution conv_75 1 1 125 126 0=192 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=9216-HardSigmoid hsigmoid_10 1 1 126 127 0=1.666667e-01 1=5.000000e-01-Reshape reshape_113 1 1 127 128 0=1 1=1 2=-1-BinaryOp mul_76 2 1 122 128 129 0=2-Convolution conv_76 1 1 129 130 0=384 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=73728-BinaryOp mul_77 1 1 130 131 0=2 1=1 2=1.177498e+00-BinaryOp add_78 1 1 131 132 0=0 1=1 2=2.513300e-02-HardSwish hswish_37 1 1 132 133 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_79 1 1 133 134 0=2 1=1 2=9.679640e-01-BinaryOp add_80 1 1 134 135 0=0 1=1 2=1.379930e-01-ConvolutionDepthWise convdw_134 1 1 135 136 0=384 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=9600 7=384-BinaryOp mul_81 1 1 136 137 0=2 1=1 2=1.555377e+00-BinaryOp add_82 1 1 137 138 0=0 1=1 2=8.333650e-01-HardSwish hswish_38 1 1 138 139 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_83 1 1 139 140 0=2 1=1 2=1.253523e+00-BinaryOp add_84 1 1 140 141 0=0 1=1 2=-1.035149e+00-Split splitncnn_4 1 2 141 142 143-Pooling gap_1 1 1 143 144 0=1 4=1-Convolution convrelu_1 1 1 144 145 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=36864 9=1-Convolution conv_78 1 1 145 146 0=384 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=36864-HardSigmoid hsigmoid_11 1 1 146 147 0=1.666667e-01 1=5.000000e-01-Reshape reshape_114 1 1 147 148 0=1 1=1 2=-1-BinaryOp mul_85 2 1 142 148 149 0=2-Convolution conv_79 1 1 149 150 0=384 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=147456-BinaryOp mul_86 1 1 150 151 0=2 1=1 2=8.759720e-01-BinaryOp add_87 1 1 151 152 0=0 1=1 2=-5.355660e-01-HardSwish hswish_39 1 1 152 153 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_88 1 1 153 154 0=2 1=1 2=9.194060e-01-BinaryOp add_89 1 1 154 155 0=0 1=1 2=2.582260e-01-ConvolutionDepthWise convdw_135 1 1 155 156 0=384 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=9600 7=384-BinaryOp mul_90 1 1 156 157 0=2 1=1 2=9.464590e-01-BinaryOp add_91 1 1 157 158 0=0 1=1 2=7.093490e-01-HardSwish hswish_40 1 1 158 159 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_92 1 1 159 160 0=2 1=1 2=1.461620e-01-BinaryOp add_93 1 1 160 161 0=0 1=1 2=-1.060000e-04-Convolution conv_80 1 1 161 162 0=384 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=147456-BinaryOp mul_94 1 1 162 163 0=2 1=1 2=9.040130e-01-BinaryOp add_95 1 1 163 164 0=0 1=1 2=-2.947330e-01-HardSwish hswish_41 1 1 164 165 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_96 1 1 165 166 0=2 1=1 2=9.359390e-01-BinaryOp add_97 1 1 166 167 0=0 1=1 2=1.659010e-01-ConvolutionDepthWise convdw_136 1 1 167 168 0=384 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=9600 7=384-BinaryOp mul_98 1 1 168 169 0=2 1=1 2=1.019253e+00-BinaryOp add_99 1 1 169 170 0=0 1=1 2=4.081630e-01-HardSwish hswish_42 1 1 170 171 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_100 1 1 171 172 0=2 1=1 2=1.695260e-01-BinaryOp add_101 1 1 172 173 0=0 1=1 2=-6.200000e-05-Convolution conv_81 1 1 173 174 0=384 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=147456-BinaryOp mul_102 1 1 174 175 0=2 1=1 2=6.251600e-01-BinaryOp add_103 1 1 175 176 0=0 1=1 2=-1.136591e+00-HardSwish hswish_43 1 1 176 177 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_104 1 1 177 178 0=2 1=1 2=4.537565e+00-BinaryOp add_105 1 1 178 179 0=0 1=1 2=1.288086e+00-Convolution conv_82 1 1 35 180 0=12 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=576-Convolution conv_83 1 1 58 181 0=18 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=1728-Convolution conv_84 1 1 117 182 0=42 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=8064-Convolution conv_85 1 1 179 183 0=360 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=138240-Convolution conv_86 1 1 183 184 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=0 6=34560-Split splitncnn_5 1 3 184 185 186 187-Pooling gap_2 1 1 187 188 0=1 4=1-Convolution convrelu_2 1 1 188 189 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304 9=1-Convolution conv_88 1 1 189 190 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304-Reshape reshape_115 1 1 190 191 0=1 1=1 2=-1-BinaryOp mul_106 1 1 191 192 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_12 1 1 192 193 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_107 2 1 185 193 194 0=2-BinaryOp add_108 2 1 186 194 195 0=0-Split splitncnn_6 1 2 195 196 197-Convolution conv_89 1 1 182 198 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=0 6=4032-Split splitncnn_7 1 3 198 199 200 201-Pooling gap_3 1 1 201 202 0=1 4=1-Convolution convrelu_3 1 1 202 203 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304 9=1-Convolution conv_91 1 1 203 204 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304-Reshape reshape_116 1 1 204 205 0=1 1=1 2=-1-BinaryOp mul_109 1 1 205 206 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_13 1 1 206 207 0=1.666667e-01 1=5.000000e-01-Convolution conv_92 1 1 181 208 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=0 6=1728-Split splitncnn_8 1 3 208 209 210 211-Pooling gap_4 1 1 211 212 0=1 4=1-Convolution convrelu_4 1 1 212 213 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304 9=1-Convolution conv_94 1 1 213 214 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304-Reshape reshape_117 1 1 214 215 0=1 1=1 2=-1-BinaryOp mul_110 1 1 215 216 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_14 1 1 216 217 0=1.666667e-01 1=5.000000e-01-Convolution conv_95 1 1 180 218 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=0 6=1152-Split splitncnn_9 1 3 218 219 220 221-Pooling gap_5 1 1 221 222 0=1 4=1-Convolution convrelu_5 1 1 222 223 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304 9=1-Convolution conv_97 1 1 223 224 0=96 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2304-Reshape reshape_118 1 1 224 225 0=1 1=1 2=-1-BinaryOp mul_111 1 1 225 226 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_15 1 1 226 227 0=1.666667e-01 1=5.000000e-01-Interp interpolate_44 1 1 196 228 0=1 1=2.000000e+00 2=2.000000e+00 6=0-BinaryOp mul_112 2 1 199 207 229 0=2-BinaryOp add_113 2 1 200 229 230 0=0-BinaryOp add_114 2 1 230 228 231 0=0-Split splitncnn_10 1 2 231 232 233-Interp interpolate_45 1 1 232 234 0=1 1=2.000000e+00 2=2.000000e+00 6=0-BinaryOp mul_115 2 1 209 217 235 0=2-BinaryOp add_116 2 1 210 235 236 0=0-BinaryOp add_117 2 1 236 234 237 0=0-Split splitncnn_11 1 2 237 238 239-Interp interpolate_46 1 1 238 240 0=1 1=2.000000e+00 2=2.000000e+00 6=0-BinaryOp mul_118 2 1 219 227 241 0=2-BinaryOp add_119 2 1 220 241 242 0=0-BinaryOp add_120 2 1 242 240 243 0=0-Convolution conv_98 1 1 197 244 0=24 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=20736-Split splitncnn_12 1 3 244 245 246 247-Pooling gap_6 1 1 247 248 0=1 4=1-Convolution convrelu_6 1 1 248 249 0=6 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144 9=1-Convolution conv_100 1 1 249 250 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144-Reshape reshape_119 1 1 250 251 0=1 1=1 2=-1-BinaryOp mul_121 1 1 251 252 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_16 1 1 252 253 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_122 2 1 245 253 254 0=2-BinaryOp add_123 2 1 246 254 255 0=0-Convolution conv_101 1 1 233 256 0=24 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=20736-Split splitncnn_13 1 3 256 257 258 259-Pooling gap_7 1 1 259 260 0=1 4=1-Convolution convrelu_7 1 1 260 261 0=6 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144 9=1-Convolution conv_103 1 1 261 262 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144-Reshape reshape_120 1 1 262 263 0=1 1=1 2=-1-BinaryOp mul_124 1 1 263 264 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_17 1 1 264 265 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_125 2 1 257 265 266 0=2-BinaryOp add_126 2 1 258 266 267 0=0-Convolution conv_104 1 1 239 268 0=24 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=20736-Split splitncnn_14 1 3 268 269 270 271-Pooling gap_8 1 1 271 272 0=1 4=1-Convolution convrelu_8 1 1 272 273 0=6 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144 9=1-Convolution conv_106 1 1 273 274 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144-Reshape reshape_121 1 1 274 275 0=1 1=1 2=-1-BinaryOp mul_127 1 1 275 276 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_18 1 1 276 277 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_128 2 1 269 277 278 0=2-BinaryOp add_129 2 1 270 278 279 0=0-Convolution conv_107 1 1 243 280 0=24 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=0 6=20736-Split splitncnn_15 1 3 280 281 282 283-Pooling gap_9 1 1 283 284 0=1 4=1-Convolution convrelu_9 1 1 284 285 0=6 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144 9=1-Convolution conv_109 1 1 285 286 0=24 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=144-Reshape reshape_122 1 1 286 287 0=1 1=1 2=-1-BinaryOp mul_130 1 1 287 288 0=2 1=1 2=1.200000e+00-HardSigmoid hsigmoid_19 1 1 288 289 0=1.666667e-01 1=5.000000e-01-BinaryOp mul_131 2 1 281 289 290 0=2-BinaryOp add_132 2 1 282 290 291 0=0-Interp interpolate_47 1 1 255 292 0=1 1=8.000000e+00 2=8.000000e+00 6=0-Interp interpolate_48 1 1 267 293 0=1 1=4.000000e+00 2=4.000000e+00 6=0-Interp interpolate_49 1 1 279 294 0=1 1=2.000000e+00 2=2.000000e+00 6=0-Concat cat_0 4 1 292 293 294 291 295 0=0-Convolution convrelu_10 1 1 295 296 0=24 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=20736 9=1-Deconvolution deconvrelu_0 1 1 296 297 0=24 1=2 11=2 12=1 13=2 14=0 18=0 19=0 2=1 3=2 4=0 5=1 6=2304 9=1-Deconvolution deconv_112 1 1 297 298 0=1 1=2 11=2 12=1 13=2 14=0 18=0 19=0 2=1 3=2 4=0 5=0 6=96-BinaryOp add_133 1 1 298 299 0=0 1=1 2=-2.333490e-01-Sigmoid sigmoid_62 1 1 299 out0
library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.bin
diff --git a/library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.bin b/library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.bindeleted file mode 100644index f11c59f367..0000000000Binary files a/library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.bin and /dev/null differ
library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.param
diff --git a/library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.param b/library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.paramdeleted file mode 100644index 1aee93c3fd..0000000000--- a/library/ocr/src/main/assets/latin_PP_OCRv5_mobile_rec.ncnn.param+++ /dev/null@@ -1,228 +0,0 @@-7767517-226 233-Input in0 0 1 in0-Convolution conv_48 1 1 in0 1 0=16 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=432-ConvolutionDepthWise convdw_87 1 1 1 2 0=16 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=144 7=16-BinaryOp mul_0 1 1 2 3 0=2 1=1 2=0.564065158-BinaryOp add_1 1 1 3 4 0=0 1=1 2=0.175233975-HardSwish hswish_10 1 1 4 5 0=0.166666672 1=0.5-BinaryOp mul_2 1 1 5 6 0=2 1=1 2=1.16000036e-2-BinaryOp add_3 1 1 6 7 0=0 1=1 2=1.96562716e-4-Convolution conv_49 1 1 7 8 0=32 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=512-BinaryOp mul_4 1 1 8 9 0=2 1=1 2=0.697574914-BinaryOp add_5 1 1 9 10 0=0 1=1 2=0.209528193-HardSwish hswish_11 1 1 10 11 0=0.166666672 1=0.5-BinaryOp mul_6 1 1 11 12 0=2 1=1 2=0.153161153-BinaryOp add_7 1 1 12 13 0=0 1=1 2=-0.252474844-ConvolutionDepthWise convdw_88 1 1 13 14 0=32 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=288 7=32-BinaryOp mul_8 1 1 14 15 0=2 1=1 2=0.527992189-BinaryOp add_9 1 1 15 16 0=0 1=1 2=0.257374197-HardSwish hswish_12 1 1 16 17 0=0.166666672 1=0.5-BinaryOp mul_10 1 1 17 18 0=2 1=1 2=0.13261123-BinaryOp add_11 1 1 18 19 0=0 1=1 2=-1.949697e-5-Convolution conv_50 1 1 19 20 0=64 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=2048-BinaryOp mul_12 1 1 20 21 0=2 1=1 2=0.718611717-BinaryOp add_13 1 1 21 22 0=0 1=1 2=0.192481279-HardSwish hswish_13 1 1 22 23 0=0.166666672 1=0.5-BinaryOp mul_14 1 1 23 24 0=2 1=1 2=0.165840194-BinaryOp add_15 1 1 24 25 0=0 1=1 2=-0.410497665-ConvolutionDepthWise convdw_89 1 1 25 26 0=64 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=576 7=64-BinaryOp mul_16 1 1 26 27 0=2 1=1 2=1.20116627-BinaryOp add_17 1 1 27 28 0=0 1=1 2=3.26557606e-2-HardSwish hswish_14 1 1 28 29 0=0.166666672 1=0.5-BinaryOp mul_18 1 1 29 30 0=2 1=1 2=8.26387107e-3-BinaryOp add_19 1 1 30 31 0=0 1=1 2=-1.66935846e-4-Convolution conv_51 1 1 31 32 0=64 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=4096-BinaryOp mul_20 1 1 32 33 0=2 1=1 2=0.796040177-BinaryOp add_21 1 1 33 34 0=0 1=1 2=0.106059641-HardSwish hswish_15 1 1 34 35 0=0.166666672 1=0.5-BinaryOp mul_22 1 1 35 36 0=2 1=1 2=0.215806693-BinaryOp add_23 1 1 36 37 0=0 1=1 2=-0.133243456-ConvolutionDepthWise convdw_90 1 1 37 38 0=64 1=3 11=3 12=1 13=2 14=1 2=1 3=1 4=1 5=1 6=576 7=64-BinaryOp mul_24 1 1 38 39 0=2 1=1 2=0.45115-BinaryOp add_25 1 1 39 40 0=0 1=1 2=0.276121974-HardSwish hswish_16 1 1 40 41 0=0.166666672 1=0.5-BinaryOp mul_26 1 1 41 42 0=2 1=1 2=3.12436856e-2-BinaryOp add_27 1 1 42 43 0=0 1=1 2=-4.68897124e-5-Convolution conv_52 1 1 43 44 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=8192-BinaryOp mul_28 1 1 44 45 0=2 1=1 2=0.607312143-BinaryOp add_29 1 1 45 46 0=0 1=1 2=0.342687666-HardSwish hswish_17 1 1 46 47 0=0.166666672 1=0.5-BinaryOp mul_30 1 1 47 48 0=2 1=1 2=0.25548476-BinaryOp add_31 1 1 48 49 0=0 1=1 2=-0.373523891-ConvolutionDepthWise convdw_91 1 1 49 50 0=128 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=1152 7=128-BinaryOp mul_32 1 1 50 51 0=2 1=1 2=0.974350572-BinaryOp add_33 1 1 51 52 0=0 1=1 2=9.04594436e-2-HardSwish hswish_18 1 1 52 53 0=0.166666672 1=0.5-BinaryOp mul_34 1 1 53 54 0=2 1=1 2=1.98780857e-2-BinaryOp add_35 1 1 54 55 0=0 1=1 2=-8.21673348e-6-Convolution conv_53 1 1 55 56 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-BinaryOp mul_36 1 1 56 57 0=2 1=1 2=0.665341735-BinaryOp add_37 1 1 57 58 0=0 1=1 2=0.137440905-HardSwish hswish_19 1 1 58 59 0=0.166666672 1=0.5-BinaryOp mul_38 1 1 59 60 0=2 1=1 2=0.364029646-BinaryOp add_39 1 1 60 61 0=0 1=1 2=-3.51698361e-2-ConvolutionDepthWise convdw_92 1 1 61 62 0=128 1=3 11=3 12=1 13=1 14=1 2=1 3=2 4=1 5=1 6=1152 7=128-BinaryOp mul_40 1 1 62 63 0=2 1=1 2=0.418737531-BinaryOp add_41 1 1 63 64 0=0 1=1 2=0.200494915-HardSwish hswish_20 1 1 64 65 0=0.166666672 1=0.5-BinaryOp mul_42 1 1 65 66 0=2 1=1 2=2.85614897e-2-BinaryOp add_43 1 1 66 67 0=0 1=1 2=2.77619329e-5-Convolution conv_54 1 1 67 68 0=240 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=30720-BinaryOp mul_44 1 1 68 69 0=2 1=1 2=0.619697154-BinaryOp add_45 1 1 69 70 0=0 1=1 2=0.242107689-HardSwish hswish_21 1 1 70 71 0=0.166666672 1=0.5-BinaryOp mul_46 1 1 71 72 0=2 1=1 2=0.445594162-BinaryOp add_47 1 1 72 73 0=0 1=1 2=-0.274067551-ConvolutionDepthWise convdw_93 1 1 73 74 0=240 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=6000 7=240-BinaryOp mul_48 1 1 74 75 0=2 1=1 2=0.464560062-BinaryOp add_49 1 1 75 76 0=0 1=1 2=-2.21147407e-2-HardSwish hswish_22 1 1 76 77 0=0.166666672 1=0.5-BinaryOp mul_50 1 1 77 78 0=2 1=1 2=1.20686451e-2-BinaryOp add_51 1 1 78 79 0=0 1=1 2=1.05241234e-5-Convolution conv_55 1 1 79 80 0=240 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=57600-BinaryOp mul_52 1 1 80 81 0=2 1=1 2=0.63324666-BinaryOp add_53 1 1 81 82 0=0 1=1 2=0.131356105-HardSwish hswish_23 1 1 82 83 0=0.166666672 1=0.5-BinaryOp mul_54 1 1 83 84 0=2 1=1 2=0.457933396-BinaryOp add_55 1 1 84 85 0=0 1=1 2=-0.156199783-ConvolutionDepthWise convdw_94 1 1 85 86 0=240 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=6000 7=240-BinaryOp mul_56 1 1 86 87 0=2 1=1 2=0.357361823-BinaryOp add_57 1 1 87 88 0=0 1=1 2=-4.75566238e-2-HardSwish hswish_24 1 1 88 89 0=0.166666672 1=0.5-BinaryOp mul_58 1 1 89 90 0=2 1=1 2=1.41586512e-2-BinaryOp add_59 1 1 90 91 0=0 1=1 2=-2.29760280e-5-Convolution conv_56 1 1 91 92 0=240 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=57600-BinaryOp mul_60 1 1 92 93 0=2 1=1 2=0.634905279-BinaryOp add_61 1 1 93 94 0=0 1=1 2=-5.01220934e-2-HardSwish hswish_25 1 1 94 95 0=0.166666672 1=0.5-BinaryOp mul_62 1 1 95 96 0=2 1=1 2=0.566476345-BinaryOp add_63 1 1 96 97 0=0 1=1 2=7.45525658e-2-ConvolutionDepthWise convdw_95 1 1 97 98 0=240 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=6000 7=240-BinaryOp mul_64 1 1 98 99 0=2 1=1 2=0.296121091-BinaryOp add_65 1 1 99 100 0=0 1=1 2=0.303118765-HardSwish hswish_26 1 1 100 101 0=0.166666672 1=0.5-BinaryOp mul_66 1 1 101 102 0=2 1=1 2=1.40156187e-2-BinaryOp add_67 1 1 102 103 0=0 1=1 2=-3.70499256e-5-Convolution conv_57 1 1 103 104 0=240 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=57600-BinaryOp mul_68 1 1 104 105 0=2 1=1 2=0.619623959-BinaryOp add_69 1 1 105 106 0=0 1=1 2=-0.159811422-HardSwish hswish_27 1 1 106 107 0=0.166666672 1=0.5-BinaryOp mul_70 1 1 107 108 0=2 1=1 2=0.624986708-BinaryOp add_71 1 1 108 109 0=0 1=1 2=0.170280099-ConvolutionDepthWise convdw_96 1 1 109 110 0=240 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=6000 7=240-BinaryOp mul_72 1 1 110 111 0=2 1=1 2=0.306288451-BinaryOp add_73 1 1 111 112 0=0 1=1 2=0.374543428-HardSwish hswish_28 1 1 112 113 0=0.166666672 1=0.5-BinaryOp mul_74 1 1 113 114 0=2 1=1 2=1.29208583e-2-BinaryOp add_75 1 1 114 115 0=0 1=1 2=-3.641025e-5-Convolution conv_58 1 1 115 116 0=240 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=57600-BinaryOp mul_76 1 1 116 117 0=2 1=1 2=0.556821108-BinaryOp add_77 1 1 117 118 0=0 1=1 2=-0.229975745-HardSwish hswish_29 1 1 118 119 0=0.166666672 1=0.5-BinaryOp mul_78 1 1 119 120 0=2 1=1 2=0.532315969-BinaryOp add_79 1 1 120 121 0=0 1=1 2=0.174008518-ConvolutionDepthWise convdw_97 1 1 121 122 0=240 1=5 11=5 12=1 13=2 14=2 2=1 3=1 4=2 5=1 6=6000 7=240-BinaryOp mul_80 1 1 122 123 0=2 1=1 2=0.773038447-BinaryOp add_81 1 1 123 124 0=0 1=1 2=0.26654312-HardSwish hswish_30 1 1 124 125 0=0.166666672 1=0.5-BinaryOp mul_82 1 1 125 126 0=2 1=1 2=1.08317482-BinaryOp add_83 1 1 126 127 0=0 1=1 2=-1.01971662-Split splitncnn_0 1 2 127 128 129-Pooling gap_5 1 1 129 130 0=1 4=1-Convolution convrelu_0 1 1 130 131 0=60 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=14400 9=1-Convolution conv_60 1 1 131 132 0=240 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=14400-HardSigmoid hsigmoid_8 1 1 132 133 0=0.166666672 1=0.5-Reshape reshape_82 1 1 133 134 0=1 1=1 2=-1-BinaryOp mul_84 2 1 128 134 135 0=2-Convolution conv_61 1 1 135 136 0=480 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=115200-BinaryOp mul_85 1 1 136 137 0=2 1=1 2=0.588281751-BinaryOp add_86 1 1 137 138 0=0 1=1 2=-0.135463476-HardSwish hswish_31 1 1 138 139 0=0.166666672 1=0.5-BinaryOp mul_87 1 1 139 140 0=2 1=1 2=0.651209533-BinaryOp add_88 1 1 140 141 0=0 1=1 2=5.21442518e-2-ConvolutionDepthWise convdw_98 1 1 141 142 0=480 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=12000 7=480-BinaryOp mul_89 1 1 142 143 0=2 1=1 2=1.12332749-BinaryOp add_90 1 1 143 144 0=0 1=1 2=1.51137337e-2-HardSwish hswish_32 1 1 144 145 0=0.166666672 1=0.5-BinaryOp mul_91 1 1 145 146 0=2 1=1 2=1.57725167-BinaryOp add_92 1 1 146 147 0=0 1=1 2=-1.71445942-Split splitncnn_1 1 2 147 148 149-Pooling gap_6 1 1 149 150 0=1 4=1-Convolution convrelu_1 1 1 150 151 0=120 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=57600 9=1-Convolution conv_63 1 1 151 152 0=480 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=57600-HardSigmoid hsigmoid_9 1 1 152 153 0=0.166666672 1=0.5-Reshape reshape_83 1 1 153 154 0=1 1=1 2=-1-BinaryOp mul_93 2 1 148 154 155 0=2-Convolution conv_64 1 1 155 156 0=480 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=230400-BinaryOp mul_94 1 1 156 157 0=2 1=1 2=0.589806437-BinaryOp add_95 1 1 157 158 0=0 1=1 2=-0.38106215-HardSwish hswish_33 1 1 158 159 0=0.166666672 1=0.5-BinaryOp mul_96 1 1 159 160 0=2 1=1 2=0.597411573-BinaryOp add_97 1 1 160 161 0=0 1=1 2=0.171211079-ConvolutionDepthWise convdw_99 1 1 161 162 0=480 1=5 11=5 12=1 13=2 14=2 2=1 3=1 4=2 5=1 6=12000 7=480-BinaryOp mul_98 1 1 162 163 0=2 1=1 2=0.265684277-BinaryOp add_99 1 1 163 164 0=0 1=1 2=0.611183345-HardSwish hswish_34 1 1 164 165 0=0.166666672 1=0.5-BinaryOp mul_100 1 1 165 166 0=2 1=1 2=7.38201709e-3-BinaryOp add_101 1 1 166 167 0=0 1=1 2=-2.41943344e-5-Convolution conv_65 1 1 167 168 0=480 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=230400-BinaryOp mul_102 1 1 168 169 0=2 1=1 2=0.832095-BinaryOp add_103 1 1 169 170 0=0 1=1 2=-0.31415984-HardSwish hswish_35 1 1 170 171 0=0.166666672 1=0.5-BinaryOp mul_104 1 1 171 172 0=2 1=1 2=0.366937637-BinaryOp add_105 1 1 172 173 0=0 1=1 2=0.116793968-ConvolutionDepthWise convdw_100 1 1 173 174 0=480 1=5 11=5 12=1 13=1 14=2 2=1 3=1 4=2 5=1 6=12000 7=480-BinaryOp mul_106 1 1 174 175 0=2 1=1 2=0.390624-BinaryOp add_107 1 1 175 176 0=0 1=1 2=0.331913829-HardSwish hswish_36 1 1 176 177 0=0.166666672 1=0.5-BinaryOp mul_108 1 1 177 178 0=2 1=1 2=0.033816915-BinaryOp add_109 1 1 178 179 0=0 1=1 2=4.72881220e-4-Convolution conv_66 1 1 179 180 0=480 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=230400-BinaryOp mul_110 1 1 180 181 0=2 1=1 2=2.23218036-BinaryOp add_111 1 1 181 182 0=0 1=1 2=-0.244224131-HardSwish hswish_37 1 1 182 183 0=0.166666672 1=0.5-BinaryOp mul_112 1 1 183 184 0=2 1=1 2=3.71384-BinaryOp add_113 1 1 184 185 0=0 1=1 2=-0.296149343-Pooling avgpool2d_7 1 1 185 186 0=1 1=2 11=3 12=3 13=0 2=2 3=0 5=1 6=0-Split splitncnn_2 1 2 186 187 188-Convolution conv_67 1 1 188 189 0=60 1=3 11=1 12=1 13=1 14=0 2=1 3=1 4=1 5=1 6=86400-Swish silu_40 1 1 189 190-Convolution conv_68 1 1 190 191 0=120 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=7200-Swish silu_41 1 1 191 192-Reshape reshape_84 1 1 192 193 0=-1 1=120-Permute permute_79 1 1 193 194 0=1-Split splitncnn_3 1 2 194 195 196-LayerNorm ln_72 1 1 196 197 0=120 1=1.000000e-5 2=1-MultiHeadAttention attention_77 1 1 197 198 0=120 1=8 2=14400 3=120 4=120-BinaryOp add_114 2 1 195 198 199 0=0-Split splitncnn_4 1 2 199 200 201-LayerNorm ln_73 1 1 201 202 0=120 1=1.000000e-5 2=1-Gemm gemm_0 1 1 202 203 10=4 2=0 3=1 4=0 5=1 6=1 7=0 8=240 9=120-Swish silu_42 1 1 203 204-Gemm gemm_1 1 1 204 205 10=4 2=0 3=1 4=0 5=1 6=1 7=0 8=120 9=240-BinaryOp add_115 2 1 200 205 206 0=0-Split splitncnn_5 1 2 206 207 208-LayerNorm ln_74 1 1 208 209 0=120 1=1.000000e-5 2=1-MultiHeadAttention attention_78 1 1 209 210 0=120 1=8 2=14400 3=120 4=120-BinaryOp add_116 2 1 207 210 211 0=0-Split splitncnn_6 1 2 211 212 213-LayerNorm ln_75 1 1 213 214 0=120 1=1.000000e-5 2=1-Gemm gemm_2 1 1 214 215 10=4 2=0 3=1 4=0 5=1 6=1 7=0 8=240 9=120-Swish silu_43 1 1 215 216-Gemm gemm_3 1 1 216 217 10=4 2=0 3=1 4=0 5=1 6=1 7=0 8=120 9=240-BinaryOp add_117 2 1 212 217 218 0=0-LayerNorm ln_76 1 1 218 219 0=120 1=1.000000e-6 2=1-Reshape reshape_85 1 1 219 220 0=120 1=-1 2=1-Permute permute_80 1 1 220 221 0=4-Convolution conv_69 1 1 221 222 0=480 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=57600-Swish silu_44 1 1 222 223-Concat cat_0 2 1 187 223 224 0=0-Convolution conv_70 1 1 224 225 0=60 1=3 11=1 12=1 13=1 14=0 2=1 3=1 4=1 5=1 6=172800-Swish silu_45 1 1 225 226-Convolution conv_71 1 1 226 227 0=120 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=7200-Swish silu_46 1 1 227 228-Squeeze squeeze_86 1 1 228 229 -23303=1,1-Permute permute_81 1 1 229 230 0=1-Gemm gemm_4 1 1 230 231 10=4 2=0 3=1 4=0 5=1 6=1 7=0 8=838 9=120-Softmax softmax_47 1 1 231 out0 0=1 1=1
library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt
diff --git a/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt b/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.ktindex 8738cb0ce2..0d8fbbbc76 100644--- a/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt+++ b/library/ocr/src/main/java/com/vayunmathur/library/ocr/OcrEngine.kt@@ -1,34 +1,39 @@ package com.vayunmathur.library.ocr- import android.content.Context import android.graphics.Bitmap-import android.util.Log-import com.vayunmathur.ncnn.PpOcr+import com.vayunmathur.library.ml.RecognizedLine+import com.vayunmathur.library.ml.TextRecognizer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext- /**- * Shared on-device OCR engine using Baidu **PP-OCRv5 mobile** running on- * **ncnn** (Tencent, BSD-3, CPU-only — no Google Play Services, no ML Kit). The- * detection (DBNet) + recognition (CTC) pipeline runs entirely inside the- * `com.github.vayun-mathur:ncnn-android` AAR (native, OpenCV-free — DB- * post-processing is a hand-rolled connected-components pass). The recognizer- * uses the **latin** PP-OCRv5 model (836-char dict covering 47 Latin-script- * languages; no CJK) for a much smaller footprint. The det + rec model files are- * supplied by this module's assets and their paths passed to [PpOcr]. Both the- * Photos and PDF apps depend on this one module so they share the engine.+ * Shared on-device OCR engine using Baidu **PP-OCRv5 mobile**, running on the Vulkan+ * compute runtime in `:library:ml`. *- * The whole detect+recognize pass runs natively in one call; this class adapts- * the result to the [OcrResult]/[TextBox] shape consumers expect and orders the- * lines top-to-bottom for readable output.+ * Detection is DBNet over a PP-HGNetV2 backbone; recognition is a PP-LCNetV3 backbone into a+ * two-block transformer with a CTC head. Both are converted ahead of time to `.vkml` by+ * `scripts/ml/ppocr_fold.py` and shipped in this module's assets. The recogniser is the+ * **latin** model (836-char dict covering 47 Latin-script languages; no CJK) for a much+ * smaller footprint. *- * If the native library/models are unavailable the engine is inert (returns- * empty text, never crashes) — call [isAvailable] to check up front.+ * # What replaced what *- * All heavy work runs off the main thread (Dispatchers.Default). Instances are- * safe to reuse sequentially; concurrent calls are serialised internally.+ * This used to call into the `com.github.vayun-mathur:ncnn-android` AAR, where the whole+ * detect-crop-recognise pipeline lived inside `ppocrv5.cpp` and could not be read or tested.+ * All of it is now Rust in `:library:ml`: the DBNet post-processing in `post::dbnet`, the+ * rotated crop in `post::crop`, the CTC collapse in `post::ctc`, and the sequencing in+ * `post::ocr` - each host-tested against values computed by hand, and both models checked+ * numerically against onnxruntime by `scripts/ml/onnx_parity.py`.+ *+ * The engine still adapts the result to the [OcrResult]/[TextBox] shape consumers expect.+ * Reading order is decided natively now, so this no longer sorts.+ *+ * If Vulkan fp16 compute or an asset is unavailable the engine is inert (returns empty text,+ * never crashes) - call [isAvailable] to check up front.+ *+ * All heavy work runs off the main thread (Dispatchers.Default). Instances are safe to reuse+ * sequentially; concurrent calls are serialised internally. * * Usage: * ```@@ -38,10 +43,8 @@ import kotlinx.coroutines.withContext * ``` */ class OcrEngine(private val context: Context) {- /** A corner of a [TextBox] quad, in source-bitmap pixel coordinates. */ data class Corner(val x: Float, val y: Float)- /** * One recognised text region in source-bitmap pixel coordinates. *@@ -69,85 +72,71 @@ class OcrEngine(private val context: Context) { val centerY: Float get() = corners.sumOf { it.y.toDouble() }.toFloat() / corners.size val centerX: Float get() = corners.sumOf { it.x.toDouble() }.toFloat() / corners.size }- /** Full result: the joined [text] plus the individual [boxes] it came from. */ data class OcrResult(val text: String, val boxes: List<TextBox>)- private val lock = Mutex()- private var ocr: PpOcr? = null+ private var recognizer: TextRecognizer? = null private var initTried = false-- /** True if the native library + models are present and could be loaded. */+ /** True if the runtime and the models are present and could be loaded. */ suspend fun isAvailable(): Boolean = lock.withLock { ensureInit() }- /** * Recognise all text in [bitmap] and return it as a single string (lines * joined by newlines), or an empty string if nothing is found or the engine * is unavailable. The caller's [bitmap] is not recycled. */ suspend fun recognize(bitmap: Bitmap): String = recognizeDetailed(bitmap).text- /** Like [recognize] but also returns the per-region [TextBox]es. */ suspend fun recognizeDetailed(bitmap: Bitmap): OcrResult = withContext(Dispatchers.Default) {+ // The lock is held across the whole native call, not just the handle read: `close`+ // frees the Vulkan handle and reading it afterwards is a use-after-free. lock.withLock { if (!ensureInit()) return@withContext OcrResult("", emptyList())- val engine = ocr ?: return@withContext OcrResult("", emptyList())- try {- val boxes = engine.recognize(bitmap)- .asSequence()- .filter { it.text.isNotBlank() && it.right > it.left && it.bottom > it.top }- .map { line ->- TextBox(- text = line.text.trim(),- left = line.left,- top = line.top,- right = line.right,- bottom = line.bottom,- corners = List(4) { Corner(line.quad[it * 2], line.quad[it * 2 + 1]) },- vertical = line.vertical,- )- }- // Reading order: top-to-bottom, then left-to-right within a- // row band. Banding on the quad centre rather than its top- // edge keeps a tilted line's regions in one band.- .sortedWith(compareBy({ it.centerY.toInt() / READING_ROW_BAND }, { it.centerX }))- .toList()- OcrResult(boxes.joinToString("\n") { it.text }.trim(), boxes)- } catch (e: Exception) {- Log.e(TAG, "OCR failed", e)- OcrResult("", emptyList())- }+ val engine = recognizer ?: return@withContext OcrResult("", emptyList())+ val boxes = engine.recognize(bitmap)+ .asSequence()+ .filter { it.text.isNotBlank() }+ .map { toTextBox(it) }+ .filter { it.right > it.left && it.bottom > it.top }+ .toList()+ OcrResult(boxes.joinToString("\n") { it.text }.trim(), boxes) } }-- /** Release the native models. */+ /** Release the models. */ fun close() {- try { ocr?.close() } catch (_: Exception) {}- ocr = null+ try { recognizer?.close() } catch (_: Exception) {}+ recognizer = null initTried = false }-- /** Create the native PP-OCRv5 engine once. */+ /** Create the engine once. */ private fun ensureInit(): Boolean {- if (ocr != null) return true+ recognizer?.let { return it.isAvailable } if (initTried) return false initTried = true- return try {- ocr = PpOcr(- context,- "PP_OCRv5_mobile_det.ncnn.param", "PP_OCRv5_mobile_det.ncnn.bin",- "latin_PP_OCRv5_mobile_rec.ncnn.param", "latin_PP_OCRv5_mobile_rec.ncnn.bin",- )- true- } catch (e: Throwable) {- Log.e(TAG, "Failed to initialise ncnn PP-OCRv5", e)- ocr = null- false+ val created = TextRecognizer(context.applicationContext)+ if (!created.isAvailable) {+ // Already logged natively under the `ModelRunner` tag, with the reason.+ created.close()+ return false }+ recognizer = created+ return true }-- companion object {- private const val TAG = "OcrEngine"- private const val READING_ROW_BAND = 16+ private companion object {+ /**+ * A [RecognizedLine]'s quad and its axis-aligned bounds.+ *+ * The bounds are rounded outwards rather than truncated: a caller that draws the+ * rect should cover the glyphs rather than clip them, and `toInt()` on a float+ * pixel edge loses up to a pixel on each side.+ */+ fun toTextBox(line: RecognizedLine): OcrEngine.TextBox = OcrEngine.TextBox(+ text = line.text.trim(),+ left = kotlin.math.floor(line.left).toInt(),+ top = kotlin.math.floor(line.top).toInt(),+ right = kotlin.math.ceil(line.right).toInt(),+ bottom = kotlin.math.ceil(line.bottom).toInt(),+ corners = line.corners.map { OcrEngine.Corner(it.first, it.second) },+ vertical = line.vertical,+ ) } }
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex 59db0d33a9..1b826683f4 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -43,12 +43,9 @@ dependencies { implementation(project(":library:map")) implementation(project(":library:image")) implementation(libs.androidx.exifinterface)- // No direct ncnn dependency any more: face detection (SCRFD 500M), face embedding- // (MobileFaceNet) and subject segmentation (U²-Net portable) all run on :library:ml,- // our own Vulkan compute runtime.- //- // `libncnn_android.so` is still in this APK, though, because :library:ocr below pulls- // it in for PP-OCRv5 text recognition. It leaves when OCR moves across.+ // No ncnn anywhere in this APK. Face detection (SCRFD 500M), face embedding+ // (MobileFaceNet), subject segmentation (U²-Net portable) and PP-OCRv5 text+ // recognition all run on :library:ml, our own Vulkan compute runtime. implementation(project(":library:ml")) implementRoom(libs)