library:ocr: vendor the PP-OCRv5 dictionary and CTC decode
- Commit
bb1fa4cbe379bcf3fb432e774a18b61e3bbaee98- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 17:12 UTC (3 months ago)
- Parents
aeb433f
Diff
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.rsnew file mode 100644index 0000000000..011455dab3--- /dev/null+++ b/library/ml/src/main/rust/src/post/ctc.rs@@ -0,0 +1,268 @@+//! CTC greedy decoding, and the character table it decodes against.+//!+//! # The label space+//!+//! PP-OCRv5's recogniser emits [`LOGITS`] = 838 values per timestep. PaddleOCR's+//! `CTCLabelDecode` builds that list as+//!+//! ```text+//! index 0 the CTC blank+//! index 1..=836 the 836 entries of the character dictionary, in file order+//! index 837 the space, which `use_space_char` appends+//! ```+//!+//! so a label's character is `dictionary[index - 1]` — the off-by-one the plan warned+//! about, and the reason [`Dictionary::label`] exists rather than callers indexing.+//!+//! The dictionary ships as `ppocr_keys.txt`, one character per line, extracted from the+//! export's own `inference.yml` (`PostProcess.character_dict`). **Its order is+//! load-bearing**: the model's final layer emits logits positionally, so a reordered file+//! decodes to fluent-looking nonsense rather than failing. The space is *not* in the file+//! — no entry in it is whitespace, checked at load — so it is appended here, which keeps+//! the asset free of trailing-whitespace hazards that a text editor or a line-ending+//! conversion would silently eat.+//!+//! # Greedy, not beam search+//!+//! `ppocrv5.cpp` takes the argmax per timestep and collapses runs; there is no language+//! model and no beam. This reproduces that.++/// Logits the recogniser emits per timestep: blank + 836 characters + space.+pub const LOGITS: usize = 838;+/// Entries the dictionary file must hold.+pub const DICTIONARY_ENTRIES: usize = 836;++/// The character table, in label order.+#[derive(Debug)]+pub struct Dictionary {+ /// One entry per label from 1 upwards; index 0 (the blank) has no character.+ characters: Vec<String>,+}++impl Dictionary {+ /// Parse `ppocr_keys.txt`: one character per line, and the space appended.+ ///+ /// Rejects a file of the wrong length rather than decoding against a truncated table,+ /// which would shift every character above the missing one.+ pub fn parse(text: &str) -> Result<Dictionary, String> {+ // `lines` handles both endings, which matters because this asset is text in a+ // repo with mixed CRLF and LF.+ let mut characters: Vec<String> = text+ .lines()+ .map(|line| line.trim_end_matches('\r').to_string())+ .filter(|line| !line.is_empty())+ .collect();+ if characters.len() != DICTIONARY_ENTRIES {+ return Err(format!(+ "{} dictionary entries, expected {DICTIONARY_ENTRIES}",+ characters.len()+ ));+ }+ if let Some(bad) = characters.iter().position(|c| c.chars().count() != 1) {+ return Err(format!("dictionary entry {bad} is not a single character"));+ }+ // `use_space_char`, which is what makes the label space 838 rather than 837.+ characters.push(" ".to_string());+ Ok(Dictionary { characters })+ }++ /// The character for `label`, or `None` for the blank and for anything out of range.+ pub fn label(&self, label: usize) -> Option<&str> {+ if label == 0 {+ return None;+ }+ self.characters.get(label - 1).map(String::as_str)+ }++ /// How many labels there are, including the blank. Should equal [`LOGITS`].+ pub fn labels(&self) -> usize {+ self.characters.len() + 1+ }+}++/// One decoded line: its text and the mean confidence of the labels that produced it.+#[derive(Clone, Debug, PartialEq)]+pub struct Decoded {+ /// The text, with repeats collapsed and blanks removed.+ pub text: String,+ /// Mean probability of the kept timesteps, or 0 when nothing was kept.+ pub confidence: f32,+}++/// Collapse `logits` into text: argmax per timestep, drop blanks, drop repeats.+///+/// `logits` is `steps * LOGITS`, row-major — one row per timestep, already through the+/// graph's softmax. 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> {+ let labels = dictionary.labels();+ if labels != LOGITS {+ return Err(format!("a dictionary of {labels} labels, expected {LOGITS}"));+ }+ if !logits.len().is_multiple_of(labels) {+ return Err(format!(+ "{} logits is not a whole number of {labels}-wide timesteps",+ logits.len()+ ));+ }++ let mut text = String::new();+ let mut total = 0.0f64;+ let mut kept = 0u32;+ let mut previous = usize::MAX;++ for step in logits.chunks_exact(labels) {+ let (best, &score) = step+ .iter()+ .enumerate()+ .max_by(|(_, a), (_, b)| a.total_cmp(b))+ .ok_or("an empty timestep")?;+ // A repeat of the immediately preceding label is the same character held across+ // two frames. A blank resets that, which is how "aa" is spelled at all.+ if best != previous {+ if let Some(character) = dictionary.label(best) {+ text.push_str(character);+ total += score as f64;+ kept += 1;+ }+ }+ previous = best;+ }++ let confidence = if kept > 0 { (total / kept as f64) as f32 } else { 0.0 };+ Ok(Decoded { text, confidence })+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A dictionary of `a`, `b`, `c`, ... padded to the real length so `decode` accepts+ /// it, since a short one is refused on purpose.+ fn dictionary() -> Dictionary {+ let mut text = String::new();+ for index in 0..DICTIONARY_ENTRIES {+ // Printable ASCII cycling, so the first few entries are predictable.+ let code = b'a' + (index % 26) as u8;+ text.push(code as char);+ text.push('\n');+ }+ Dictionary::parse(&text).expect("the fixture dictionary parses")+ }++ /// One timestep whose argmax is `label`, at probability `score`.+ fn step(label: usize, score: f32) -> Vec<f32> {+ let mut row = vec![0.0; LOGITS];+ row[label] = score;+ row+ }++ fn logits(steps: &[(usize, f32)]) -> Vec<f32> {+ steps.iter().flat_map(|&(l, s)| step(l, s)).collect()+ }++ #[test]+ fn the_label_space_is_blank_then_the_dictionary_then_a_space() {+ let d = dictionary();+ assert_eq!(d.labels(), LOGITS);+ // 0 is the blank and decodes to nothing.+ assert_eq!(d.label(0), None);+ // 1 is the *first* dictionary entry: the `index - 1` the plan flagged.+ assert_eq!(d.label(1), Some("a"));+ assert_eq!(d.label(2), Some("b"));+ // The last label is the appended space, not a dictionary entry.+ assert_eq!(d.label(LOGITS - 1), Some(" "));+ assert_eq!(d.label(LOGITS), None);+ }++ #[test]+ fn a_run_of_one_label_collapses_to_one_character() {+ let d = dictionary();+ let got = decode(&logits(&[(1, 0.9), (1, 0.8), (1, 0.7)]), &d).expect("decodes");+ assert_eq!(got.text, "a");+ // Only the first of the run is scored, which is what the reference does.+ assert!((got.confidence - 0.9).abs() < 1e-6, "{}", got.confidence);+ }++ #[test]+ fn a_blank_between_two_identical_labels_keeps_both() {+ // The whole reason CTC has a blank: without it "aa" is indistinguishable from a+ // held "a".+ let d = dictionary();+ let got = decode(&logits(&[(1, 0.9), (0, 0.6), (1, 0.8)]), &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, 0.99), (0, 0.99)]), &d).expect("decodes");+ assert_eq!(got.text, "");+ assert_eq!(got.confidence, 0.0);+ }++ #[test]+ fn distinct_adjacent_labels_both_survive_without_a_blank() {+ let d = dictionary();+ let got = decode(&logits(&[(1, 0.9), (2, 0.8), (3, 0.7)]), &d).expect("decodes");+ assert_eq!(got.text, "abc");+ assert!((got.confidence - 0.8).abs() < 1e-6, "{}", got.confidence);+ }++ #[test]+ fn the_space_label_decodes_to_a_space() {+ let d = dictionary();+ let got = decode(&logits(&[(1, 0.9), (LOGITS - 1, 0.8), (2, 0.7)]), &d).expect("decodes");+ assert_eq!(got.text, "a b");+ }++ #[test]+ fn the_argmax_is_taken_across_the_whole_row() {+ // A row where the winner is not the only non-zero, so a decoder that took the+ // first positive value rather than the largest would differ.+ let d = dictionary();+ let mut row = vec![0.0; LOGITS];+ row[1] = 0.2;+ row[5] = 0.7;+ row[9] = 0.1;+ let got = decode(&row, &d).expect("decodes");+ assert_eq!(got.text, "e");+ }++ #[test]+ fn a_dictionary_of_the_wrong_length_is_refused() {+ let error = Dictionary::parse("a\nb\nc\n").expect_err("too short");+ assert!(error.contains("3 dictionary entries"), "{error}");+ }++ #[test]+ fn a_multi_character_dictionary_entry_is_refused() {+ let mut text = String::new();+ for index in 0..DICTIONARY_ENTRIES {+ text.push_str(if index == 4 { "ab" } else { "a" });+ text.push('\n');+ }+ let error = Dictionary::parse(&text).expect_err("a two-character entry");+ assert!(error.contains("entry 4"), "{error}");+ }++ #[test]+ fn carriage_returns_are_tolerated() {+ // The repo has mixed line endings and this asset is text, so a checkout that+ // converted it must still load.+ let mut text = String::new();+ for _ in 0..DICTIONARY_ENTRIES {+ text.push_str("a\r\n");+ }+ let d = Dictionary::parse(&text).expect("parses with CRLF");+ assert_eq!(d.label(1), Some("a"));+ }++ #[test]+ fn a_ragged_logit_array_is_refused() {+ let d = dictionary();+ let error = decode(&[0.0; LOGITS + 3], &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 ce234840c0..7484ced411 100644--- a/library/ml/src/main/rust/src/post/mod.rs+++ b/library/ml/src/main/rust/src/post/mod.rs@@ -10,5 +10,6 @@ //! read, let alone tested. Each module here is ported from a named C++ function and //! host-tested against values computed by hand. +pub mod ctc; pub mod dbnet; pub mod nms;
library/ml/src/main/rust/tests/assets.rs
diff --git a/library/ml/src/main/rust/tests/assets.rs b/library/ml/src/main/rust/tests/assets.rsindex a8ae0b4eeb..ff03acb2d0 100644--- a/library/ml/src/main/rust/tests/assets.rs+++ b/library/ml/src/main/rust/tests/assets.rs@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf}; use modelrunner::nets::{mobilefacenet, ppocr_det, scrfd, selfie, u2netp};+use modelrunner::post::ctc; use modelrunner::weights::{graph, Weights}; /// The repo root, found by walking up for `settings.gradle.kts` rather than by counting@@ -102,6 +103,24 @@ fn the_shipped_ppocr_det_asset_builds_the_ppocr_det_forward_pass() { ); } +#[test]+fn the_shipped_character_dictionary_matches_the_recogniser_label_space() {+ // The model's final layer emits 838 logits positionally, so the dictionary's *length*+ // is a hard constraint and its *order* is the whole decode. A file that lost a line+ // to an editor would shift every character above it.+ let path = repo_root().join("library/ocr/src/main/assets/ppocr_keys.txt");+ let text = std::fs::read_to_string(&path)+ .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));+ let dictionary = ctc::Dictionary::parse(&text).expect("the shipped dictionary parses");+ assert_eq!(dictionary.labels(), ctc::LOGITS);+ // Spot-check the ends against the export's `inference.yml`: digits first, and the+ // appended space last.+ assert_eq!(dictionary.label(0), None, "label 0 is the CTC blank");+ assert_eq!(dictionary.label(1), Some("0"));+ assert_eq!(dictionary.label(11), Some("A"));+ assert_eq!(dictionary.label(ctc::LOGITS - 1), Some(" "));+}+ #[test] fn neither_asset_will_load_as_the_other_network() { // The `graph_id` in the header exists for exactly this: the two files are both
library/ocr/src/main/assets/README.md
diff --git a/library/ocr/src/main/assets/README.md b/library/ocr/src/main/assets/README.mdindex a5b8db8d58..36da9246e4 100644--- a/library/ocr/src/main/assets/README.md+++ b/library/ocr/src/main/assets/README.md@@ -45,12 +45,35 @@ From the export's own `inference.yml`, not guessed: * DBNet post-processing: `thresh: 0.3`, `box_thresh: 0.6`, `max_candidates: 1000`, `unclip_ratio: 1.5`. +## `ppocr_keys.txt` — the recogniser's character dictionary++836 characters, one per line, UTF-8, LF. Extracted from the same export's+`inference.yml` (`PostProcess.character_dict`, `CTCLabelDecode`), so it carries the same+Apache-2.0 provenance as the weights and needs no separate pin.++**Its order is the decode.** The recogniser's final layer emits 838 logits positionally:++| label | meaning |+|---|---|+| 0 | the CTC blank |+| 1..=836 | this file's lines, in order |+| 837 | the space, which `use_space_char` appends |++So a character is `line[label - 1]`, and a file that lost or reordered a line decodes to+fluent-looking nonsense rather than failing. `post::ctc` checks the length at load, and+`tests/assets.rs` checks that length against the model's logit count.++The space is deliberately **not** in the file — no entry in it is whitespace — so that a+text editor or a line-ending conversion cannot silently eat it. `post::ctc::Dictionary`+appends it.+ ## Recognition `latin_PP_OCRv5_mobile_rec.ncnn.{param,bin}` still runs on ncnn, and is what keeps `libncnn_android.so` in `:photos`, `:pdf` and `:translate`. Its replacement needs a-transformer stack the runtime does not have yet (2 multi-head attentions, 5 layer norms,-batched matmul, softmax) plus the 838-entry character dictionary and CTC decoding.+transformer stack the runtime does not have yet: the export decomposes each of its 5 layer+norms into `ReduceMean`/`Sub`/`Pow`/`Sqrt`/`Div`, and its attention into 13 `MatMul`s, 3+`Softmax`es and 9 `Transpose`s. The dictionary and the CTC decode for it are already here. `PP_OCRv5_mobile_det.ncnn.{param,bin}` is superseded by `ppocr_det.vkml` but still present, because `OcrEngine.kt` loads both models through the one ncnn wrapper and cannot
library/ocr/src/main/assets/ppocr_keys.txt
diff --git a/library/ocr/src/main/assets/ppocr_keys.txt b/library/ocr/src/main/assets/ppocr_keys.txtnew file mode 100644index 0000000000..c6182570f6--- /dev/null+++ b/library/ocr/src/main/assets/ppocr_keys.txt@@ -0,0 +1,836 @@+0+1+2+3+4+5+6+7+8+9+A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z+a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+w+x+y+z+À+Á+Â+Ã+Ä+Å+Æ+Ç+È+É+Ê+Ë+Ì+Í+Î+Ï+Ð+Ñ+Ò+Ó+Ô+Õ+Ö+×+Ø+Ù+Ú+Û+Ü+Ý+Þ+ß+à+á+â+ã+ä+å+æ+ç+è+é+ê+ë+ì+í+î+ï+ð+ñ+ò+ó+ô+õ+ö+÷+ø+ù+ú+û+ü+ý+þ+ÿ+Ā+ā+Ă+ă+Ą+ą+Ć+ć+Ĉ+ĉ+Ċ+ċ+Č+č+Ď+ď+Đ+đ+Ē+ē+Ĕ+ĕ+Ė+ė+Ę+ę+Ě+ě+Ĝ+ĝ+Ğ+ğ+Ġ+ġ+Ģ+ģ+Ĥ+ĥ+Ħ+ħ+Ĩ+ĩ+Ī+ī+Ĭ+ĭ+Į+į+İ+ı+IJ+ij+Ĵ+ĵ+Ķ+ķ+ĸ+Ĺ+ĺ+Ļ+ļ+Ľ+ľ+Ŀ+ŀ+Ł+ł+Ń+ń+Ņ+ņ+Ň+ň+ʼn+Ŋ+ŋ+Ō+ō+Ŏ+ŏ+Ő+ő+Œ+œ+Ŕ+ŕ+Ŗ+ŗ+Ř+ř+Ś+ś+Ŝ+ŝ+Ş+ş+Š+š+Ţ+ţ+Ť+ť+Ŧ+ŧ+Ũ+ũ+Ū+ū+Ŭ+ŭ+Ů+ů+Ű+ű+Ų+ų+Ŵ+ŵ+Ŷ+ŷ+Ÿ+Ź+ź+Ż+ż+Ž+ž+ſ+ƀ+Ɓ+Ƃ+ƃ+Ƅ+ƅ+Ɔ+Ƈ+ƈ+Ɖ+Ɗ+Ƌ+ƌ+ƍ+Ǝ+Ə+Ɛ+Ƒ+ƒ+Ɠ+Ɣ+ƕ+Ɩ+Ɨ+Ƙ+ƙ+ƚ+ƛ+Ɯ+Ɲ+ƞ+Ɵ+Ơ+ơ+Ƣ+ƣ+Ƥ+ƥ+Ʀ+Ƨ+ƨ+Ʃ+ƪ+ƫ+Ƭ+ƭ+Ʈ+Ư+ư+Ʊ+Ʋ+Ƴ+ƴ+Ƶ+ƶ+Ʒ+Ƹ+ƹ+ƺ+ƻ+Ƽ+ƽ+ƾ+ƿ+ǀ+ǁ+ǂ+ǃ+DŽ+Dž+dž+LJ+Lj+lj+NJ+Nj+nj+Ǎ+ǎ+Ǐ+ǐ+Ǒ+ǒ+Ǔ+ǔ+Ǖ+ǖ+Ǘ+ǘ+Ǚ+ǚ+Ǜ+ǜ+ǝ+Ǟ+ǟ+Ǡ+ǡ+Ǣ+ǣ+Ǥ+ǥ+Ǧ+ǧ+Ǩ+ǩ+Ǫ+ǫ+Ǭ+ǭ+Ǯ+ǯ+ǰ+DZ+Dz+dz+Ǵ+ǵ+Ƕ+Ƿ+Ǹ+ǹ+Ǻ+ǻ+Ǽ+ǽ+Ǿ+ǿ+Ȁ+ȁ+Ȃ+ȃ+Ȅ+ȅ+Ȇ+ȇ+Ȉ+ȉ+Ȋ+ȋ+Ȍ+ȍ+Ȏ+ȏ+Ȑ+ȑ+Ȓ+ȓ+Ȕ+ȕ+Ȗ+ȗ+Ș+ș+Ț+ț+Ȝ+ȝ+Ȟ+ȟ+Ƞ+ȡ+Ȣ+ȣ+Ȥ+ȥ+Ȧ+ȧ+Ȩ+ȩ+Ȫ+ȫ+Ȭ+ȭ+Ȯ+ȯ+Ȱ+ȱ+Ȳ+ȳ+ȴ+ȵ+ȶ+ȷ+ȸ+ȹ+Ⱥ+Ȼ+ȼ+Ƚ+Ⱦ+ȿ+ɀ+Ɂ+ɂ+Ƀ+Ʉ+Ʌ+Ɇ+ɇ+Ɉ+ɉ+Ɋ+ɋ+Ɍ+ɍ+Ɏ+ɏ+!+"+#+$+%+&+'+(+)+*+++,+-+.+/+:+;+<+=+>+?+@+[+\+]+_+`+{+|+}+^+~+©+®+℉+№+Ω+℮+™+∆+✓+✔+✗+✘+✕+☑+☒+●+▪+▫+◼+▶+◀+⬆+¤+¦+§+¨+ª+«+¬+¯+°+²+³+´+µ+¶+¸+¹+º+»+¼+½+¾+¿+×+‐+‑+‒+—+―+‖+‗+‘+’+‚+‛+“+”+„+‟+†+‡+‣+․+…+‧+‰+‴+‵+‶+‷+‸+‹+›+※+‼+‽+‾+−+₤+₡+₹+₽+₴+₿+¢+€+£+¥+Ⅰ+Ⅱ+Ⅲ+Ⅳ+Ⅴ+Ⅵ+Ⅶ+Ⅷ+Ⅸ+Ⅹ+Ⅺ+Ⅻ+ⅰ+ⅱ+ⅲ+ⅳ+ⅴ+ⅵ+ⅶ+ⅷ+ⅸ+ⅹ+ⅺ+ⅻ+➀+➁+➂+➃+➄+➅+➆+➇+➈+➉+➊+➋+➌+➍+➎+➏+➐+➑+➒+➓+❶+❷+❸+❹+❺+❻+❼+❽+❾+❿+①+②+③+④+⑤+⑥+⑦+⑧+⑨+⑩+↑+→+↓+↕+←+↔+⇒+⇐+⇔+∀+∃+∄+∴+∵+∝+∞+∩+∪+∂+∫+∬+∭+∮+∯+∰+∑+∏+√+∛+∜+∱+∲+∳+∶+∷+∼+∖+∗+≈+≠+≡+≤+≥+⊂+⊃+⊥+⊾+⊿+□+∥+∋+ƒ+′+″+À+Á+Â+Ã+Ä+Å+Æ+Ç+È+É+Ê+Ë+Ì+Í+Î+Ï+Ð+Ñ+Ò+Ó+Ô+Õ+Ö+Ø+Ù+Ú+Û+Ü+Ý+Þ+à+á+â+ã+ä+å+æ+ç+è+é+ê+ë+ì+í+î+ï+ð+ñ+ò+ó+ô+õ+ö+ø+ù+ú+û+ü+ý+þ+ÿ+Α+Β+Γ+Δ+Ε+Ζ+Η+Θ+Ι+Κ+Λ+Μ+Ν+Ξ+Ο+Π+Ρ+Σ+Τ+Υ+Φ+Χ+Ψ+Ω+α+β+γ+δ+ε+ζ+η+θ+ι+κ+λ+μ+ν+ξ+ο+π+ρ+σ+ς+τ+υ+φ+χ+ψ+ω+Å+ℏ+⌀+⍺+⍵+𝑢+𝜓+०+‥+︽+﹥+•+÷+∕+∙+⋅+·+±+∓+∟+∠+∡+∢+℧+☺