//! Bina 0.4 Microscopy in Rust: Persian page OCR as one native program. //! Engines: ONNX Runtime (default, fastest) or tract (`--no-default-features --features tract`, pure Rust). //! //! usage: bina-microscopy [--models DIR] [--out DIR] [--single] [--reader FILE] IMAGE... use anyhow::{anyhow, bail, Context, Result}; use serde_json::{json, Value}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::time::Instant; // ------------------------------------------------------------------ inference engines // Default: ONNX Runtime (feature "ort", fastest). `--no-default-features --features tract`: pure Rust (tract). #[cfg(feature = "ort")] mod engine { use anyhow::{Context, Result}; use ort::session::{builder::GraphOptimizationLevel, Session}; use ort::value::Tensor; use std::path::Path; use std::sync::Mutex; pub const NAME: &str = "onnxruntime"; static ENV: std::sync::OnceLock = std::sync::OnceLock::new(); fn e(x: E) -> anyhow::Error { anyhow::anyhow!("onnxruntime: {x}") } fn session(p: &Path, threads: usize) -> Result { let env = ENV.get_or_init(|| ort::init().with_name("bina-microscopy").build().expect("ONNX Runtime initialisation")); let mut b = Session::builder(env).map_err(e)? .with_optimization_level(GraphOptimizationLevel::Level3).map_err(e)? .with_intra_threads(threads).map_err(e)?; b.commit_from_file(p).map_err(e).with_context(|| format!("loading {}", p.display())) } pub struct DetNet(Mutex); impl DetNet { pub fn load(p: &Path, threads: usize) -> Result { Ok(Self(Mutex::new(session(p, threads)?))) } /// x: (1,3,h,w) -> prob (ph, pw, data) pub fn run(&self, x: Vec, h: usize, w: usize) -> Result<(usize, usize, Vec)> { let mut s = self.0.lock().unwrap(); let out = s.run(ort::inputs!["x" => Tensor::from_array(([1usize, 3, h, w], x)).map_err(e)?]).map_err(e)?; let (shape, data) = out["prob"].try_extract_tensor::().map_err(e)?; Ok((shape[2] as usize, shape[3] as usize, data.to_vec())) } } pub struct ReaderNet(Mutex); impl ReaderNet { pub fn load(p: &Path, threads: usize) -> Result { Ok(Self(Mutex::new(session(p, threads)?))) } /// x: (n,1,64,p), widths: (n,) -> log-probabilities (T, C, data) pub fn run(&self, x: Vec, n: usize, p: usize, widths: Vec) -> Result<(usize, usize, Vec)> { let mut s = self.0.lock().unwrap(); let out = s.run(ort::inputs!["x" => Tensor::from_array(([n, 1usize, 64, p], x)).map_err(e)?, "widths" => Tensor::from_array(([n], widths)).map_err(e)?]).map_err(e)?; let (shape, data) = out["logprobs"].try_extract_tensor::().map_err(e)?; Ok((shape[1] as usize, shape[2] as usize, data.to_vec())) } } pub fn init(_threads: usize) {} } #[cfg(all(feature = "tract", not(feature = "ort")))] mod engine { use anyhow::{Context, Result}; use std::cell::RefCell; use std::collections::HashMap; use std::path::Path; use tract_onnx::prelude::*; pub const NAME: &str = "tract"; type Plan = std::sync::Arc; fn load_onnx(p: &Path) -> Result { tract_onnx::onnx().model_for_path(p).with_context(|| format!("loading {}", p.display())) } /// one optimized plan per page size (sizes come in steps of 32 px) pub struct DetNet { model: InferenceModel, plans: RefCell> } impl DetNet { pub fn load(p: &Path, _threads: usize) -> Result { Ok(Self { model: load_onnx(p)?, plans: Default::default() }) } pub fn run(&self, x: Vec, h: usize, w: usize) -> Result<(usize, usize, Vec)> { let plan = { let mut plans = self.plans.borrow_mut(); if !plans.contains_key(&(h, w)) { let m = self.model.clone().with_input_fact(0, f32::fact([1, 3, h, w]).into())?; plans.insert((h, w), m.into_optimized()?.into_runnable()?); } plans[&(h, w)].clone() }; let out = plan.run(tvec!(Tensor::from_shape(&[1, 3, h, w], &x)?.into()))?; let p = out[0].to_plain_array_view::()?; Ok((p.shape()[2], p.shape()[3], p.iter().cloned().collect())) } } pub struct ReaderNet(Plan); impl ReaderNet { pub fn load(p: &Path, _threads: usize) -> Result { let mut r = load_onnx(p)?; let s = r.symbols.clone(); r.set_input_fact(0, f32::fact(&[s.sym("B").to_dim(), 1.into(), 64.into(), s.sym("W").to_dim()]).into())?; r.set_input_fact(1, i64::fact(&[s.sym("B").to_dim()]).into())?; Ok(Self(r.into_optimized()?.into_runnable()?)) } pub fn run(&self, x: Vec, n: usize, p: usize, widths: Vec) -> Result<(usize, usize, Vec)> { let out = self.0.run(tvec!(Tensor::from_shape(&[n, 1, 64, p], &x)?.into(), tensor1(&widths).into()))?; let lp = out[0].to_plain_array_view::()?; Ok((lp.shape()[1], lp.shape()[2], lp.iter().cloned().collect())) } } pub fn init(threads: usize) { if threads > 1 { tract_linalg::multithread::set_default_executor(tract_linalg::multithread::Executor::multithread(threads)); } } } // ------------------------------------------------------------------ resize (OpenCV-compatible) #[derive(Clone, Copy, PartialEq)] enum Interp { Area, Linear } /// Per-output-index source taps (index, weight) along one axis, following cv2.resize. fn axis_taps(sn: usize, dn: usize, interp: Interp, area_ok: bool) -> Vec> { let scale = sn as f64 / dn as f64; let inv = dn as f64 / sn as f64; let mut out = Vec::with_capacity(dn); for d in 0..dn { let mut taps = Vec::new(); if interp == Interp::Area && area_ok { // cv2 computeResizeAreaTab let fsx1 = d as f64 * scale; let fsx2 = fsx1 + scale; let cell = scale.min(sn as f64 - fsx1); let mut sx1 = fsx1.ceil() as usize; let sx2 = (fsx2.floor() as usize).min(sn); sx1 = sx1.min(sx2); if sx1 as f64 - fsx1 > 1e-3 { taps.push((sx1 - 1, ((sx1 as f64 - fsx1) / cell) as f32)); } for k in sx1..sx2 { taps.push((k, (1.0 / cell) as f32)); } if fsx2 - sx2 as f64 > 1e-3 && sx2 < sn { taps.push((sx2, ((fsx2 - sx2 as f64).min(1.0).min(cell) / cell) as f32)); } } else { let (mut s, mut f) = if interp == Interp::Area { let s = (d as f64 * scale).floor(); let mut f = (d + 1) as f64 - (s + 1.0) * inv; f = if f <= 0.0 { 0.0 } else { f - f.floor() }; (s as i64, f) } else { let fx = (d as f64 + 0.5) * scale - 0.5; let s = fx.floor(); (s as i64, fx - s) }; if s < 0 { s = 0; f = 0.0; } if s >= sn as i64 - 1 { s = sn as i64 - 1; f = 0.0; } let s = s as usize; taps.push((s, (1.0 - f) as f32)); if f > 0.0 { taps.push((s + 1, f as f32)); } } out.push(taps); } out } fn resize(src: &[u8], sw: usize, sh: usize, c: usize, dw: usize, dh: usize, interp: Interp) -> Vec { let area_ok = sw >= dw && sh >= dh; let tx = axis_taps(sw, dw, interp, area_ok); let ty = axis_taps(sh, dh, interp, area_ok); let mut tmp = vec![0f32; sh * dw * c]; for y in 0..sh { for (x, taps) in tx.iter().enumerate() { for ch in 0..c { let mut acc = 0f32; for &(s, w) in taps { acc += w * src[(y * sw + s) * c + ch] as f32; } tmp[(y * dw + x) * c + ch] = acc; } } } let mut out = vec![0u8; dh * dw * c]; for (y, taps) in ty.iter().enumerate() { for x in 0..dw { for ch in 0..c { let mut acc = 0f32; for &(s, w) in taps { acc += w * tmp[(s * dw + x) * c + ch]; } out[(y * dw + x) * c + ch] = acc.round_ties_even().clamp(0.0, 255.0) as u8; } } } out } // ------------------------------------------------------------------ geometry fn cross(o: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 { (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0) } fn hull(mut p: Vec<(f64, f64)>) -> Vec<(f64, f64)> { p.sort_by(|a, b| a.partial_cmp(b).unwrap()); p.dedup(); if p.len() < 3 { return p; } // monotone chain (Andrew): lower and upper chains built separately, as in cv2.minAreaRect let (mut lo, mut up): (Vec<(f64, f64)>, Vec<(f64, f64)>) = (Vec::new(), Vec::new()); for &q in p.iter() { while lo.len() >= 2 && cross(lo[lo.len() - 2], lo[lo.len() - 1], q) <= 0.0 { lo.pop(); } lo.push(q); } for &q in p.iter().rev() { while up.len() >= 2 && cross(up[up.len() - 2], up[up.len() - 1], q) <= 0.0 { up.pop(); } up.push(q); } lo.pop(); up.pop(); lo.extend(up); lo } /// Minimum-area rectangle: (cx, cy, side along u, side along v, u direction). fn min_area_rect(pts: Vec<(f64, f64)>) -> (f64, f64, f64, f64, (f64, f64)) { let h = hull(pts); if h.len() == 1 { return (h[0].0, h[0].1, 0.0, 0.0, (1.0, 0.0)); } let mut best: Option<(f64, f64, f64, f64, f64, (f64, f64))> = None; for i in 0..h.len() { let (a, b) = (h[i], h[(i + 1) % h.len()]); let (dx, dy) = (b.0 - a.0, b.1 - a.1); let n = (dx * dx + dy * dy).sqrt(); if n == 0.0 { continue; } let u = (dx / n, dy / n); let v = (-u.1, u.0); let (mut u0, mut u1, mut v0, mut v1) = (f64::MAX, f64::MIN, f64::MAX, f64::MIN); for q in &h { let pu = q.0 * u.0 + q.1 * u.1; let pv = q.0 * v.0 + q.1 * v.1; u0 = u0.min(pu); u1 = u1.max(pu); v0 = v0.min(pv); v1 = v1.max(pv); } let area = (u1 - u0) * (v1 - v0); if best.map_or(true, |b| area < b.0 - 1e-9) { let (cu, cv) = ((u0 + u1) / 2.0, (v0 + v1) / 2.0); best = Some((area, cu * u.0 + cv * v.0, cu * u.1 + cv * v.1, u1 - u0, v1 - v0, u)); } } let b = best.unwrap(); (b.1, b.2, b.3, b.4, b.5) } fn median(mut v: Vec) -> f64 { v.sort_by(|a, b| a.partial_cmp(b).unwrap()); let n = v.len(); if n % 2 == 1 { v[n / 2] } else { (v[n / 2 - 1] + v[n / 2]) / 2.0 } } type BoxF = [f64; 4]; /// Right-to-left reading order: columns at gaps wider than colg line heights, then rows. fn order(boxes: Vec, colg: f64, rowt: f64) -> Vec { fn cut(bs: Vec, colg: f64, rowt: f64) -> Vec { if bs.len() <= 1 { return bs; } let h = median(bs.iter().map(|b| b[3] - b[1]).collect()); let mut ivs: Vec<(f64, f64)> = bs.iter().map(|b| (b[0], b[2])).collect(); ivs.sort_by(|a, b| a.partial_cmp(b).unwrap()); let mut merged = vec![[ivs[0].0, ivs[0].1]]; for &(a, b) in &ivs[1..] { let last = merged.last_mut().unwrap(); if a <= last[1] + colg * h { last[1] = last[1].max(b); } else { merged.push([a, b]); } } if merged.len() > 1 { merged.sort_by(|x, y| y[0].partial_cmp(&x[0]).unwrap()); let mut out = Vec::new(); for m in merged { let sub: Vec = bs.iter().filter(|q| q[0] >= m[0] - 1.0 && q[2] <= m[1] + 1.0).cloned().collect(); out.extend(cut(sub, colg, rowt)); } return out; } let mut sorted = bs.clone(); sorted.sort_by(|a, b| ((a[1] + a[3]) / 2.0).partial_cmp(&((b[1] + b[3]) / 2.0)).unwrap()); let mut rows: Vec<(f64, Vec)> = Vec::new(); for b in sorted { let c = (b[1] + b[3]) / 2.0; if let Some(r) = rows.last_mut() { if c - r.0 < rowt * h { r.1.push(b); r.0 = r.1.iter().map(|q| (q[1] + q[3]) / 2.0).sum::() / r.1.len() as f64; continue; } } rows.push((c, vec![b])); } let mut out = Vec::new(); for (_, mut r) in rows { r.sort_by(|a, b| b[2].partial_cmp(&a[2]).unwrap()); out.extend(r); } out } if boxes.is_empty() { boxes } else { cut(boxes, colg, rowt) } } // ------------------------------------------------------------------ line crops fn percentiles(b: &[u8]) -> [f64; 3] { let mut hist = [0usize; 256]; for &v in b { hist[v as usize] += 1; } let mut cum = [0usize; 256]; let mut s = 0; for i in 0..256 { s += hist[i]; cum[i] = s; } let n = b.len(); let ss = |t: usize| cum.iter().take_while(|&&c| c <= t).count() as f64; // searchsorted side=right let mut out = [0.0; 3]; for (k, q) in [0.02, 0.5, 0.98].iter().enumerate() { let x = q * (n - 1) as f64; let i = x.floor(); let g = x - i; let lo = ss(i as usize); let hi = ss((i as usize + 1).min(n - 1)); out[k] = lo + g * (hi - lo); } out } struct Gray { w: usize, h: usize, px: Vec } fn is_dark_line(g: &Gray, b: &BoxF) -> bool { let (x0, y0) = ((b[0] as i64).max(0) as usize, (b[1] as i64).max(0) as usize); let x1 = ((b[2] as i64 + 1) as usize).min(g.w); let y1 = ((b[3] as i64 + 1) as usize).min(g.h); if x1 <= x0 || y1 <= y0 { return false; } let mut v = Vec::with_capacity((x1 - x0) * (y1 - y0)); for y in y0..y1 { v.extend_from_slice(&g.px[y * g.w + x0..y * g.w + x1]); } let [lo, med, hi] = percentiles(&v); hi - med > 2.0 * (med - lo) + 8.0 } /// 64-px-high ink map (ink = 1) for one line box, as the reader expects. fn crop_line64(g: &Gray, b: &BoxF) -> (Vec, usize) { let height = b[3] - b[1]; let ix0 = (b[0] - 0.3 * height).floor() as i64; let ix1 = (b[2] + 0.3 * height).ceil() as i64; let iy0 = (b[1] - 0.2 * height).floor() as i64; let iy1 = (b[3] + 0.2 * height).ceil() as i64; let (cw, ch) = ((ix1 - ix0) as usize, (iy1 - iy0) as usize); let dark = is_dark_line(g, b); let mut canvas = vec![if dark { 0u8 } else { 255u8 }; cw * ch]; let (sx0, sy0) = (ix0.max(0), iy0.max(0)); let (sx1, sy1) = (ix1.min(g.w as i64), iy1.min(g.h as i64)); if sx1 > sx0 && sy1 > sy0 { for y in sy0..sy1 { let src = &g.px[y as usize * g.w + sx0 as usize..y as usize * g.w + sx1 as usize]; let off = (y - iy0) as usize * cw + (sx0 - ix0) as usize; canvas[off..off + src.len()].copy_from_slice(src); } } let width = ((cw as f64 * 64.0 / ch as f64).round_ties_even() as usize).max(1); let interp = if ch > 64 { Interp::Area } else { Interp::Linear }; let r = resize(&canvas, cw, ch, 1, width, 64, interp); (r.iter().map(|&v| { let f = v as f32 / 255.0; if dark { f } else { 1.0 - f } }).collect(), width) } // ------------------------------------------------------------------ right-to-left text struct Bidi { kind: HashMap, mark: HashMap } impl Bidi { fn k(&self, c: char) -> u8 { *self.kind.get(&c).unwrap_or(&b'N') } fn m(&self, c: char) -> bool { *self.mark.get(&c).unwrap_or(&false) } fn mirror(c: &str) -> String { let (a, b) = ("()[]{}<>«»‹›", ")(][}{><»«›‹"); let mut it = c.chars(); let f = it.next().unwrap(); let m = a.chars().position(|x| x == f).map(|i| b.chars().nth(i).unwrap()).unwrap_or(f); std::iter::once(m).chain(it).collect() } /// bina_rtl.flip(text, base_rtl=True): visual order (as read) to logical order. fn flip(&self, text: &str) -> String { if !text.chars().any(|c| self.k(c) == b'R') { return text.to_string(); } let mut cls: Vec = Vec::new(); for c in text.chars() { if self.m(c) && !cls.is_empty() { cls.last_mut().unwrap().push(c); } else { cls.push(c.to_string()); } } let kinds: Vec = cls.iter().map(|c| self.k(c.chars().next().unwrap())).collect(); let mut spans = Vec::new(); let (mut start, mut last): (Option, usize) = (None, 0); for i in 0..=kinds.len() { let k = if i < kinds.len() { kinds[i] } else { b'#' }; if k == b'L' { if start.is_none() { start = Some(i); } last = i; } else if k == b'R' || k == b'#' { if let Some(s) = start { spans.push((s, last + 1)); } start = None; } } spans.push((cls.len(), cls.len())); let mut units: Vec = Vec::new(); let mut i = 0; for (a, b) in spans { for j in i..a { units.push(Self::mirror(&cls[j])); } if a < b { units.push(cls[a..b].concat()); } i = b; } units.into_iter().rev().collect() } } // ------------------------------------------------------------------ fuzzy duplicate check fn lcs(a: &[char], b: &[char]) -> usize { let mut prev = vec![0usize; b.len() + 1]; for &x in a { let mut cur = vec![0usize; b.len() + 1]; for (j, &y) in b.iter().enumerate() { cur[j + 1] = if x == y { prev[j] + 1 } else { prev[j + 1].max(cur[j]) }; } prev = cur; } prev[b.len()] } /// rapidfuzz.fuzz.partial_ratio: best ratio of the shorter string against windows of the longer. fn partial_ratio(a: &str, b: &str) -> f64 { let (mut s, mut l): (Vec, Vec) = (a.chars().collect(), b.chars().collect()); if s.len() > l.len() { std::mem::swap(&mut s, &mut l); } if s.is_empty() { return if l.is_empty() { 100.0 } else { 0.0 }; } let ratio = |w: &[char]| 200.0 * lcs(&s, w) as f64 / (s.len() + w.len()) as f64; let n = s.len(); let mut best = 0f64; for k in 1..n { best = best.max(ratio(&l[..k])).max(ratio(&l[l.len() - k..])); } for st in 0..=l.len() - n { best = best.max(ratio(&l[st..st + n])); if best >= 100.0 { break; } } best } // ------------------------------------------------------------------ pipeline struct Det { name: &'static str, thr: f32, hf: f64, net: engine::DetNet, reader: engine::ReaderNet } struct Line { bx: BoxF, text: String, conf: f64 } struct Microscopy { dets: Vec, alpha: Vec, bidi: Bidi, parallel: bool } impl Microscopy { fn new(dir: &Path, single: bool, reader_file: &str, threads: usize) -> Result { let vocab: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("vocab.json"))?)?; let alpha: Vec = vocab["chars"].as_array().ok_or(anyhow!("vocab.json: no chars"))? .iter().map(|v| v.as_str().unwrap().to_string()).collect(); let bt: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("vocab_bidi.json"))?)?; let mut kind = HashMap::new(); let mut mark = HashMap::new(); for (k, v) in bt.as_object().unwrap() { let c = k.chars().next().unwrap(); kind.insert(c, v[0].as_str().unwrap().as_bytes()[0]); mark.insert(c, v[1].as_bool().unwrap()); } let mut dets = Vec::new(); let specs: &[(&'static str, f32, f64)] = if single { &[("det_main.onnx", 0.3, 1.6)] } else { &[("det_main.onnx", 0.3, 1.6), ("det_print.onnx", 0.2, 1.9)] }; for &(name, thr, hf) in specs { // each detector branch gets its own reader session, so the two branches can run in parallel dets.push(Det { name, thr, hf, net: engine::DetNet::load(&dir.join(name), threads)?, reader: engine::ReaderNet::load(&dir.join(reader_file), threads)? }); } Ok(Self { dets, alpha, bidi: Bidi { kind, mark }, parallel: std::env::var("BINA_SEQUENTIAL").is_err() }) } fn lines(det: &Det, rgb: &[u8], ow: usize, oh: usize) -> Result> { let sc = (1024.0 / ow.max(oh) as f64).min(1.0); let h = ((oh as f64 * sc / 32.0).round_ties_even() as usize * 32).max(32); let w = ((ow as f64 * sc / 32.0).round_ties_even() as usize * 32).max(32); let small = resize(rgb, ow, oh, 3, w, h, Interp::Area); let mut x = vec![0f32; 3 * h * w]; for i in 0..h * w { for c in 0..3 { x[c * h * w + i] = small[i * 3 + c] as f32 / 127.5 - 1.0; } } let t0 = Instant::now(); let (ph, pw, p) = det.net.run(x, h, w)?; if std::env::var("BINA_TIMING").is_ok() { eprintln!("det {} {}x{} {:.3}s", det.name, h, w, t0.elapsed().as_secs_f64()); } // 8-connected components of the kernel map, labelled in raster order let mut lab = vec![0u32; ph * pw]; let (fx, fy) = (ow as f64 / pw as f64, oh as f64 / ph as f64); let mut boxes = Vec::new(); let mut next = 0u32; for y0 in 0..ph { for x0 in 0..pw { if lab[y0 * pw + x0] != 0 || p[y0 * pw + x0] <= det.thr { continue; } next += 1; let mut stack = vec![(x0, y0)]; lab[y0 * pw + x0] = next; let mut pts = Vec::new(); while let Some((x, y)) = stack.pop() { pts.push((x as f64, y as f64)); for dy in -1i64..=1 { for dx in -1i64..=1 { let (nx, ny) = (x as i64 + dx, y as i64 + dy); if nx < 0 || ny < 0 || nx >= pw as i64 || ny >= ph as i64 { continue; } let k = ny as usize * pw + nx as usize; if lab[k] == 0 && p[ny as usize * pw + nx as usize] > det.thr { lab[k] = next; stack.push((nx as usize, ny as usize)); } }} } if pts.len() < 4 { continue; } let (cx, cy, l1, l2, u) = min_area_rect(pts); let dev = u.1.abs().atan2(u.0.abs()).to_degrees(); // angle of the u side from horizontal let (kh, kw) = if dev >= 45.0 { (l1, l2) } else { (l2, l1) }; let lh = kh * det.hf; let ww = kw + 0.6 * lh; let b = [((cx - ww / 2.0) * fx).max(0.0), ((cy - lh / 2.0) * fy).max(0.0), ((cx + ww / 2.0) * fx).min(ow as f64), ((cy + lh / 2.0) * fy).min(oh as f64)]; if b[2] - b[0] >= 2.0 && b[3] - b[1] >= 2.0 { boxes.push(b); } } } Ok(boxes) } fn read(&self, g: &Gray, boxes: &[BoxF], reader: &engine::ReaderNet) -> Result> { let crops: Vec<(Vec, usize)> = boxes.iter().map(|b| crop_line64(g, b)).collect(); let mut idx: Vec = (0..crops.len()).collect(); idx.sort_by_key(|&i| crops[i].1); let mut res = vec![(String::new(), 0.0); crops.len()]; for ids in idx.chunks(32) { let wmax = ids.iter().map(|&i| crops[i].1).max().unwrap(); let p = (wmax + 7) / 8 * 8; let mut x = vec![0f32; ids.len() * 64 * p]; for (j, &i) in ids.iter().enumerate() { let (c, w) = (&crops[i].0, crops[i].1); for y in 0..64 { x[j * 64 * p + y * p..j * 64 * p + y * p + w].copy_from_slice(&c[y * w..(y + 1) * w]); } } let ws: Vec = ids.iter().map(|&i| crops[i].1 as i64).collect(); let (tt, ncls, lp) = reader.run(x, ids.len(), p, ws.clone())?; for (j, &i) in ids.iter().enumerate() { let len = (ws[j] as usize + 3) / 4; let (mut text, mut cs, mut prev) = (String::new(), Vec::new(), usize::MAX); for t in 0..len.min(tt) { let (mut bi, mut bv) = (0usize, f32::MIN); for k in 0..ncls { let v = lp[(j * tt + t) * ncls + k]; if v > bv { bv = v; bi = k; } } if bi != 0 && bi != prev { text.push_str(&self.alpha[bi - 1]); cs.push(bv.exp() as f64); } prev = bi; } let conf = if cs.is_empty() { 0.0 } else { cs.iter().sum::() / cs.len() as f64 }; res[i] = (self.bidi.flip(&text), conf); } } Ok(res) } fn clean(lines: Vec) -> Vec { if lines.is_empty() { return lines; } let med = median(lines.iter().map(|l| l.bx[3] - l.bx[1]).collect()); let lines: Vec = lines.into_iter().filter(|l| l.bx[3] - l.bx[1] >= 0.4 * med).collect(); let ios = |a: &BoxF, b: &BoxF| { let iw = a[2].min(b[2]) - a[0].max(b[0]); let ih = a[3].min(b[3]) - a[1].max(b[1]); if iw <= 0.0 || ih <= 0.0 { 0.0 } else { iw * ih / ((a[2] - a[0]) * (a[3] - a[1])).min((b[2] - b[0]) * (b[3] - b[1])).max(1e-6) } }; let ns: Vec = lines.iter().map(|l| l.text.replace(' ', "")).collect(); let lens: Vec = lines.iter().map(|l| l.text.chars().count()).collect(); let mut drop = vec![false; lines.len()]; for i in 0..lines.len() { for j in 0..lines.len() { if i == j || drop[j] || lens[i] > lens[j] || (lens[i] == lens[j] && i > j) { continue; } if ios(&lines[i].bx, &lines[j].bx) > 0.5 && partial_ratio(&ns[i], &ns[j]) >= 80.0 { drop[i] = true; break; } } } lines.into_iter().zip(drop).filter(|(_, d)| !d).map(|(l, _)| l).collect() } fn run(&mut self, path: &Path) -> Result { let img = image::open(path).with_context(|| format!("reading {}", path.display()))?.to_rgb8(); let (ow, oh) = (img.width() as usize, img.height() as usize); let rgb = img.into_raw(); // PIL "L" conversion (ITU-R 601-2 luma, fixed point) let gray = Gray { w: ow, h: oh, px: rgb.chunks(3).map(|p| ((p[0] as u32 * 19595 + p[1] as u32 * 38470 + p[2] as u32 * 7471 + 0x8000) >> 16) as u8).collect() }; let branch = |d: &Det| -> Result<(&'static str, Vec)> { let boxes = order(Self::lines(d, &rgb, ow, oh)?, 0.4, 0.55); let tr = Instant::now(); let reads = if boxes.is_empty() { vec![] } else { self.read(&gray, &boxes, &d.reader)? }; if std::env::var("BINA_TIMING").is_ok() { eprintln!("{}: read {} lines {:.3}s", d.name, boxes.len(), tr.elapsed().as_secs_f64()); } let lines: Vec = boxes.into_iter().zip(reads) .filter(|(_, (t, c))| !t.trim().is_empty() && *c >= 0.5) .map(|(b, (t, c))| Line { bx: b.map(|v| (v * 10.0).round() / 10.0), text: t, conf: (c * 1e4).round() / 1e4 }) .collect(); Ok((d.name, Self::clean(lines))) }; // ONNX Runtime engine: the two detector branches run in parallel threads #[cfg(feature = "ort")] let outs: Vec<(&'static str, Vec)> = if self.parallel && self.dets.len() > 1 { std::thread::scope(|sc| { let hs: Vec<_> = self.dets.iter().map(|d| sc.spawn(move || branch(d))).collect(); hs.into_iter().map(|h| h.join().expect("detector branch panicked")).collect::>>() })? } else { self.dets.iter().map(|d| branch(d)).collect::>>()? }; #[cfg(not(feature = "ort"))] let outs: Vec<(&'static str, Vec)> = self.dets.iter().map(|d| branch(d)).collect::>>()?; let score = |ls: &Vec| ls.iter().filter(|l| l.conf >= 0.8).map(|l| l.text.chars().count() as f64 * l.conf).sum::(); let mut best = 0; for k in 1..outs.len() { if score(&outs[k].1) > score(&outs[best].1) { best = k; } } let (name, lines) = &outs[best]; Ok(json!({ "text": lines.iter().map(|l| l.text.as_str()).collect::>().join("\n"), "lines": lines.iter().map(|l| json!({"box": l.bx, "text": l.text, "confidence": l.conf})).collect::>(), "detector": name, })) } } fn main() -> Result<()> { let mut args = std::env::args().skip(1); let exe_dir = std::env::current_exe()?.parent().map(Path::to_path_buf).unwrap_or_default(); let (mut models, mut out, mut single, mut reader, mut inputs) = (None, PathBuf::from("microscopy-out"), false, "reader.onnx".to_string(), Vec::new()); while let Some(a) = args.next() { match a.as_str() { "--models" => models = Some(PathBuf::from(args.next().ok_or(anyhow!("--models DIR"))?)), "--out" => out = PathBuf::from(args.next().ok_or(anyhow!("--out DIR"))?), "--single" => single = true, "--reader" => reader = args.next().ok_or(anyhow!("--reader FILE"))?, "-h" | "--help" => { println!("usage: bina-microscopy [--models DIR] [--out DIR] [--single] [--reader FILE] IMAGE...\n --single: main detector only (about 2x faster; use it unless the page has tables)\n --reader reader.int8.onnx: INT8 reader (ONNX Runtime engine)\n BINA_THREADS=n: CPU threads (default 4)\nengine: {}", engine::NAME); return Ok(()); } _ => inputs.push(PathBuf::from(a)), } } if inputs.is_empty() { bail!("no input images (see --help)"); } let models = models.unwrap_or_else(|| if Path::new("vocab.json").exists() { PathBuf::from(".") } else { exe_dir }); let threads: usize = std::env::var("BINA_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4); engine::init(threads); let mut ocr = Microscopy::new(&models, single, &reader, threads)?; std::fs::create_dir_all(&out)?; for p in inputs { let t = Instant::now(); let r = ocr.run(&p)?; let stem = p.file_stem().unwrap().to_string_lossy().to_string(); std::fs::write(out.join(format!("{stem}.txt")), format!("{}\n", r["text"].as_str().unwrap()))?; std::fs::write(out.join(format!("{stem}.json")), serde_json::to_string_pretty(&r)?)?; println!("{stem}: {} lines, {:.2}s -> {}", r["lines"].as_array().unwrap().len(), t.elapsed().as_secs_f64(), out.join(format!("{stem}.txt")).display()); } Ok(()) }