|
| 1 | +//! `UNICHARSET` content store — the Rust side of the byte-parity probe |
| 2 | +//! (`PROBE-OGAR-ADAPTER-UNICHARSET`). |
| 3 | +//! |
| 4 | +//! Tesseract's `UNICHARSET` is a variable-length id↔unichar bijection loaded |
| 5 | +//! from a `.unicharset` text file. Per the Core-First doctrine it is NOT |
| 6 | +//! fixed-width per-node state — it rides a **classid-keyed content-store tier** |
| 7 | +//! shaped exactly like `deepnsm::Vocabulary`: a `reverse: Vec<String>` |
| 8 | +//! (id → unichar) plus a `lookup: HashMap<String, u32>` (unichar → id). This |
| 9 | +//! module is that tier plus the two adapter leaves (`id_to_unichar` / |
| 10 | +//! `unichar_to_id`). |
| 11 | +//! |
| 12 | +//! # Why this is the byte-parity surface |
| 13 | +//! |
| 14 | +//! The unicharset path is pure text parsing — it never touches leptonica or |
| 15 | +//! `Pix`. So the Rust side can be built and tested with **zero C dependencies**. |
| 16 | +//! The probe compares this implementation's [`UniCharSet::dump`] of a real |
| 17 | +//! `eng.unicharset` against the C++ `UNICHARSET::id_to_unichar` oracle (a small |
| 18 | +//! libtesseract harness, which only *links* leptonica, never calls it). Byte- |
| 19 | +//! identical dumps promote the doctrine CONJECTURE → FINDING. |
| 20 | +//! |
| 21 | +//! # Format scope |
| 22 | +//! |
| 23 | +//! The `.unicharset` format is: line 1 = entry count `N`; then `N` lines, each |
| 24 | +//! beginning with the unichar as its first whitespace-delimited token (the |
| 25 | +//! remaining columns — properties / script / bounding boxes — do not affect the |
| 26 | +//! id↔unichar bijection and are ignored). The line position (0-based, after the |
| 27 | +//! count line) IS the unichar id. This is the `old_style_included_ == true` |
| 28 | +//! plain-table scope the adapter-shaper bounded; fragment/`CleanupString` |
| 29 | +//! normalization is a separate, later leaf. Any special-token edge case a real |
| 30 | +//! `eng.unicharset` reveals on first diff is refined then — this is built to the |
| 31 | +//! documented format, diff-pending. |
| 32 | +
|
| 33 | +use std::collections::HashMap; |
| 34 | +use std::path::Path; |
| 35 | + |
| 36 | +/// A loaded `UNICHARSET`: the id↔unichar bijection, `deepnsm::Vocabulary`-shaped. |
| 37 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 38 | +pub struct UniCharSet { |
| 39 | + /// id → unichar (index IS the id). |
| 40 | + reverse: Vec<String>, |
| 41 | + /// unichar → id (the inverse of `reverse`). |
| 42 | + lookup: HashMap<String, u32>, |
| 43 | +} |
| 44 | + |
| 45 | +impl UniCharSet { |
| 46 | + /// Parse a `.unicharset` from its text contents. See the module docs for the |
| 47 | + /// format. Properties columns after the leading unichar token are ignored. |
| 48 | + /// |
| 49 | + /// # Errors |
| 50 | + /// |
| 51 | + /// [`UniCharSetError::Empty`] if there is no count line, |
| 52 | + /// [`UniCharSetError::BadCount`] if it is not a non-negative integer, and |
| 53 | + /// [`UniCharSetError::CountMismatch`] if fewer than `count` entry lines |
| 54 | + /// follow. |
| 55 | + pub fn load_from_str(text: &str) -> Result<Self, UniCharSetError> { |
| 56 | + let mut lines = text.lines(); |
| 57 | + let count: usize = lines |
| 58 | + .next() |
| 59 | + .ok_or(UniCharSetError::Empty)? |
| 60 | + .trim() |
| 61 | + .parse() |
| 62 | + .map_err(|_| UniCharSetError::BadCount)?; |
| 63 | + |
| 64 | + let mut reverse = Vec::with_capacity(count); |
| 65 | + let mut lookup = HashMap::with_capacity(count); |
| 66 | + for line in lines.take(count) { |
| 67 | + // The unichar is the first whitespace-delimited token; the id is the |
| 68 | + // entry's position. A unichar repeated in the file keeps its FIRST |
| 69 | + // id in `lookup` (matches a forward-scan loader), but `reverse` keeps |
| 70 | + // every entry so `id_to_unichar` is exact per position. |
| 71 | + let unichar = line.split_whitespace().next().unwrap_or("").to_string(); |
| 72 | + let id = u32::try_from(reverse.len()).map_err(|_| UniCharSetError::BadCount)?; |
| 73 | + lookup.entry(unichar.clone()).or_insert(id); |
| 74 | + reverse.push(unichar); |
| 75 | + } |
| 76 | + |
| 77 | + if reverse.len() != count { |
| 78 | + return Err(UniCharSetError::CountMismatch { |
| 79 | + declared: count, |
| 80 | + found: reverse.len(), |
| 81 | + }); |
| 82 | + } |
| 83 | + Ok(Self { reverse, lookup }) |
| 84 | + } |
| 85 | + |
| 86 | + /// Parse a `.unicharset` file from disk (a thin wrapper over |
| 87 | + /// [`Self::load_from_str`]). |
| 88 | + /// |
| 89 | + /// # Errors |
| 90 | + /// |
| 91 | + /// [`UniCharSetError::Io`] if the file cannot be read, else the parse errors |
| 92 | + /// of [`Self::load_from_str`]. |
| 93 | + pub fn load_from_file(path: &Path) -> Result<Self, UniCharSetError> { |
| 94 | + let text = std::fs::read_to_string(path).map_err(|e| UniCharSetError::Io(e.to_string()))?; |
| 95 | + Self::load_from_str(&text) |
| 96 | + } |
| 97 | + |
| 98 | + /// Number of entries (the declared count). |
| 99 | + #[must_use] |
| 100 | + pub fn size(&self) -> usize { |
| 101 | + self.reverse.len() |
| 102 | + } |
| 103 | + |
| 104 | + /// The unichar string at `id`, or `None` if out of range. The C++ oracle |
| 105 | + /// for the byte-parity diff. |
| 106 | + #[must_use] |
| 107 | + pub fn id_to_unichar(&self, id: u32) -> Option<&str> { |
| 108 | + self.reverse.get(id as usize).map(String::as_str) |
| 109 | + } |
| 110 | + |
| 111 | + /// The id of `unichar`, or `None` if absent (the C++ `INVALID_UNICHAR_ID` |
| 112 | + /// sentinel maps to `None`; the OGAR adapter boundary re-applies the |
| 113 | + /// sentinel). |
| 114 | + #[must_use] |
| 115 | + pub fn unichar_to_id(&self, unichar: &str) -> Option<u32> { |
| 116 | + self.lookup.get(unichar).copied() |
| 117 | + } |
| 118 | + |
| 119 | + /// Render the id→unichar table as `"<id>\t<unichar>\n"` lines — the exact |
| 120 | + /// shape the C++ oracle harness prints, so a byte-parity diff is |
| 121 | + /// `diff oracle_dump.tsv rust_dump.tsv`. |
| 122 | + #[must_use] |
| 123 | + pub fn dump(&self) -> String { |
| 124 | + let mut out = String::new(); |
| 125 | + for (id, unichar) in self.reverse.iter().enumerate() { |
| 126 | + out.push_str(&id.to_string()); |
| 127 | + out.push('\t'); |
| 128 | + out.push_str(unichar); |
| 129 | + out.push('\n'); |
| 130 | + } |
| 131 | + out |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +/// A failure loading a `UNICHARSET`. |
| 136 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 137 | +pub enum UniCharSetError { |
| 138 | + /// The input had no count line. |
| 139 | + Empty, |
| 140 | + /// The count line was not a non-negative integer. |
| 141 | + BadCount, |
| 142 | + /// Fewer entry lines than the declared count. |
| 143 | + CountMismatch { |
| 144 | + /// The count declared on line 1. |
| 145 | + declared: usize, |
| 146 | + /// The number of entry lines actually found. |
| 147 | + found: usize, |
| 148 | + }, |
| 149 | + /// The file could not be read (message from the underlying I/O error). |
| 150 | + Io(String), |
| 151 | +} |
| 152 | + |
| 153 | +impl std::fmt::Display for UniCharSetError { |
| 154 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 155 | + match self { |
| 156 | + Self::Empty => write!(f, "empty unicharset (no count line)"), |
| 157 | + Self::BadCount => write!(f, "first line is not a valid entry count"), |
| 158 | + Self::CountMismatch { declared, found } => { |
| 159 | + write!(f, "declared {declared} entries but found {found}") |
| 160 | + } |
| 161 | + Self::Io(msg) => write!(f, "unicharset read failed: {msg}"), |
| 162 | + } |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +impl std::error::Error for UniCharSetError {} |
| 167 | + |
| 168 | +#[cfg(test)] |
| 169 | +mod tests { |
| 170 | + use super::*; |
| 171 | + |
| 172 | + const SAMPLE: &str = "\ |
| 173 | +3 |
| 174 | +a 3 0,255,0,255,0,255,0,255,0,255 0 a Left a a |
| 175 | +b 3 0,255,0,255,0,255,0,255,0,255 0 b Left b b |
| 176 | +cd 5 0,255,0,255,0,255,0,255,0,255 0 cd Left cd cd |
| 177 | +"; |
| 178 | + |
| 179 | + #[test] |
| 180 | + fn parses_count_and_first_token_per_line() { |
| 181 | + let u = UniCharSet::load_from_str(SAMPLE).expect("valid"); |
| 182 | + assert_eq!(u.size(), 3); |
| 183 | + assert_eq!(u.id_to_unichar(0), Some("a")); |
| 184 | + assert_eq!(u.id_to_unichar(2), Some("cd")); // multi-char unichar token |
| 185 | + assert_eq!(u.id_to_unichar(3), None); // out of range |
| 186 | + } |
| 187 | + |
| 188 | + #[test] |
| 189 | + fn bijection_round_trips() { |
| 190 | + let u = UniCharSet::load_from_str(SAMPLE).expect("valid"); |
| 191 | + for id in 0..u.size() as u32 { |
| 192 | + let s = u.id_to_unichar(id).unwrap(); |
| 193 | + assert_eq!(u.unichar_to_id(s), Some(id), "id {id} must round-trip"); |
| 194 | + } |
| 195 | + assert_eq!(u.unichar_to_id("zzz"), None, "absent unichar -> None"); |
| 196 | + } |
| 197 | + |
| 198 | + #[test] |
| 199 | + fn dump_matches_oracle_line_shape() { |
| 200 | + let u = UniCharSet::load_from_str(SAMPLE).expect("valid"); |
| 201 | + assert_eq!(u.dump(), "0\ta\n1\tb\n2\tcd\n"); |
| 202 | + } |
| 203 | + |
| 204 | + #[test] |
| 205 | + fn errors_are_typed() { |
| 206 | + assert_eq!(UniCharSet::load_from_str(""), Err(UniCharSetError::Empty)); |
| 207 | + assert_eq!( |
| 208 | + UniCharSet::load_from_str("notanumber\n"), |
| 209 | + Err(UniCharSetError::BadCount) |
| 210 | + ); |
| 211 | + assert_eq!( |
| 212 | + UniCharSet::load_from_str("5\na\nb\n"), |
| 213 | + Err(UniCharSetError::CountMismatch { |
| 214 | + declared: 5, |
| 215 | + found: 2 |
| 216 | + }) |
| 217 | + ); |
| 218 | + } |
| 219 | +} |
0 commit comments