File size: 30,287 Bytes
e18be61
 
a63a9d3
e18be61
a63a9d3
 
 
 
 
 
e18be61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a63a9d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18be61
 
 
 
 
a63a9d3
e18be61
 
 
 
 
 
 
 
a63a9d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18be61
a63a9d3
 
 
e18be61
a63a9d3
 
 
e18be61
a63a9d3
 
 
 
 
 
 
 
 
 
 
 
 
 
e18be61
 
a63a9d3
e18be61
a63a9d3
 
 
 
 
 
 
 
 
 
e18be61
 
a63a9d3
 
 
 
 
 
 
e18be61
a63a9d3
 
 
 
 
 
 
 
 
 
e18be61
a63a9d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18be61
a63a9d3
 
 
 
 
 
 
 
 
 
 
 
 
e18be61
a63a9d3
 
 
e18be61
a63a9d3
e18be61
a63a9d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18be61
 
a63a9d3
e18be61
 
a63a9d3
 
 
 
e18be61
 
 
 
 
 
 
 
 
 
 
 
a63a9d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18be61
a63a9d3
 
 
 
 
 
e18be61
 
a63a9d3
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! 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<ort::environment::Environment> = std::sync::OnceLock::new();
    fn e<E: std::fmt::Display>(x: E) -> anyhow::Error { anyhow::anyhow!("onnxruntime: {x}") }
    fn session(p: &Path, threads: usize) -> Result<Session> {
        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<Session>);
    impl DetNet {
        pub fn load(p: &Path, threads: usize) -> Result<Self> { Ok(Self(Mutex::new(session(p, threads)?))) }
        /// x: (1,3,h,w) -> prob (ph, pw, data)
        pub fn run(&self, x: Vec<f32>, h: usize, w: usize) -> Result<(usize, usize, Vec<f32>)> {
            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::<f32>().map_err(e)?;
            Ok((shape[2] as usize, shape[3] as usize, data.to_vec()))
        }
    }
    pub struct ReaderNet(Mutex<Session>);
    impl ReaderNet {
        pub fn load(p: &Path, threads: usize) -> Result<Self> { 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<f32>, n: usize, p: usize, widths: Vec<i64>) -> Result<(usize, usize, Vec<f32>)> {
            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::<f32>().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<TypedRunnableModel>;
    fn load_onnx(p: &Path) -> Result<InferenceModel> {
        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<HashMap<(usize, usize), Plan>> }
    impl DetNet {
        pub fn load(p: &Path, _threads: usize) -> Result<Self> { Ok(Self { model: load_onnx(p)?, plans: Default::default() }) }
        pub fn run(&self, x: Vec<f32>, h: usize, w: usize) -> Result<(usize, usize, Vec<f32>)> {
            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::<f32>()?;
            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<Self> {
            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<f32>, n: usize, p: usize, widths: Vec<i64>) -> Result<(usize, usize, Vec<f32>)> {
            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::<f32>()?;
            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<Vec<(usize, f32)>> {
    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<u8> {
    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>) -> 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<BoxF>, colg: f64, rowt: f64) -> Vec<BoxF> {
    fn cut(bs: Vec<BoxF>, colg: f64, rowt: f64) -> Vec<BoxF> {
        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<BoxF> = 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<BoxF>)> = 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::<f64>() / 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<u8> }

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<f32>, 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<char, u8>, mark: HashMap<char, bool> }

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<String> = 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<u8> = cls.iter().map(|c| self.k(c.chars().next().unwrap())).collect();
        let mut spans = Vec::new();
        let (mut start, mut last): (Option<usize>, 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<String> = 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<char>, Vec<char>) = (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<Det>, alpha: Vec<String>, bidi: Bidi, parallel: bool }


impl Microscopy {
    fn new(dir: &Path, single: bool, reader_file: &str, threads: usize) -> Result<Self> {
        let vocab: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("vocab.json"))?)?;
        let alpha: Vec<String> = 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<Vec<BoxF>> {
        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<Vec<(String, f64)>> {
        let crops: Vec<(Vec<f32>, usize)> = boxes.iter().map(|b| crop_line64(g, b)).collect();
        let mut idx: Vec<usize> = (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<i64> = 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::<f64>() / cs.len() as f64 };
                res[i] = (self.bidi.flip(&text), conf);
            }
        }
        Ok(res)
    }

    fn clean(lines: Vec<Line>) -> Vec<Line> {
        if lines.is_empty() { return lines; }
        let med = median(lines.iter().map(|l| l.bx[3] - l.bx[1]).collect());
        let lines: Vec<Line> = 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<String> = lines.iter().map(|l| l.text.replace(' ', "")).collect();
        let lens: Vec<usize> = 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<Value> {
        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<Line>)> {
            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<Line> = 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<Line>)> = 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::<Result<Vec<_>>>()
            })?
        } else { self.dets.iter().map(|d| branch(d)).collect::<Result<Vec<_>>>()? };
        #[cfg(not(feature = "ort"))]
        let outs: Vec<(&'static str, Vec<Line>)> = self.dets.iter().map(|d| branch(d)).collect::<Result<Vec<_>>>()?;
        let score = |ls: &Vec<Line>| ls.iter().filter(|l| l.conf >= 0.8).map(|l| l.text.chars().count() as f64 * l.conf).sum::<f64>();
        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::<Vec<_>>().join("\n"),
            "lines": lines.iter().map(|l| json!({"box": l.bx, "text": l.text, "confidence": l.conf})).collect::<Vec<_>>(),
            "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(())
}