File size: 14,760 Bytes
8ec2dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Bina 0.4 Microscopy: a 9.56M-parameter Persian page OCR.

Two 0.71M line detectors + one 8.14M CTC line reader, with a parameter-free
reading-order and clean-up stage. Everything runs on ONNX Runtime (CPU) by
default; PyTorch is only needed for --backend torch (e.g. reading on a GPU).

usage:
  python microscopy.py page.jpg [more.png doc.pdf ...] [--out results]
                       [--backend onnx|torch] [--device cpu|cuda] [--single] [--dpi 200]
"""
import argparse, json, math, sys, time
from pathlib import Path

import cv2
import numpy as np
import onnxruntime as ort

try:  # PyTorch is optional: only the "torch" backend needs it
    import torch
    from torch import nn
    from torch.nn import functional as F
except ImportError:
    torch = None

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
from bina_rtl import flip  # noqa: E402


# ---------------------------------------------------------------- reader (PyTorch backend)
class Block(nn.Module if torch else object):
    def __init__(s, w):
        super().__init__()
        s.dw = nn.Conv1d(w, w, 17, padding=8, groups=w)
        s.expand = nn.Conv1d(w, 2 * w, 1)
        s.fc1 = nn.Conv1d(2 * w, w // 2, 1)
        s.fc2 = nn.Conv1d(w // 2, 2 * w, 1)
        s.project = nn.Conv1d(2 * w, w, 1)

    def forward(s, x, mask):
        z = F.hardswish(s.expand(s.dw(x)))
        pool = (z * mask).sum(2, keepdim=True) / mask.sum(2, keepdim=True).clamp_min(1)
        return (x + s.project(z * torch.sigmoid(s.fc2(F.relu(s.fc1(pool)))))) * mask


class Reader(nn.Module if torch else object):
    """64px-high line image -> CTC logits over the 1,617-symbol Bina vocabulary."""

    def __init__(s, classes, w=256, depth=19):
        super().__init__()
        s.stem = nn.Conv2d(1, w, (64, 8), stride=(64, 4))
        s.bn = nn.BatchNorm1d(w)
        s.blocks = nn.ModuleList(Block(w) for _ in range(depth))
        s.head = nn.Conv1d(w, classes, 1)

    def forward(s, x, widths):
        widths = widths.to(device=x.device, dtype=torch.long)
        if x.shape[-1] % 4:
            x = F.pad(x, (0, (-x.shape[-1]) % 4))
        z = s.stem(F.pad(x, (0, 4, 0, 0))).squeeze(2)
        lengths = (widths + 3) // 4
        mask = (torch.arange(z.shape[-1], device=z.device)[None, :] < lengths[:, None])[:, None, :].to(z.dtype)
        z = F.hardswish(s.bn(z)) * mask
        for b in s.blocks:
            z = b(z, mask)
        return s.head(z).transpose(1, 2), lengths


# ---------------------------------------------------------------- line crops
def _percentiles(b, qs=(0.02, 0.5, 0.98)):
    n = b.size
    cum = np.cumsum(np.bincount(b.ravel(), minlength=256))
    out = []
    for q in qs:
        x = q * (n - 1); i = math.floor(x); g = x - i
        lo = float(np.searchsorted(cum, i, side="right"))
        hi = float(np.searchsorted(cum, min(i + 1, n - 1), side="right"))
        out.append(lo + g * (hi - lo))
    return out


def is_dark_line(gray, box):
    """Light text on a dark ground is read inverted."""
    H, W = gray.shape
    x0, y0, x1, y1 = (float(v) for v in box[:4])
    b = gray[max(0, int(y0)):min(H, int(y1) + 1), max(0, int(x0)):min(W, int(x1) + 1)]
    if not b.size:
        return False
    lo, med, hi = _percentiles(b)
    return bool(hi - med > 2 * (med - lo) + 8)


def crop_line64(gray, box, pad_y=.2, pad_x=.3):
    x0, y0, x1, y1 = map(float, box[:4])
    height = y1 - y0
    ix0 = math.floor(x0 - pad_x * height); ix1 = math.ceil(x1 + pad_x * height)
    iy0 = math.floor(y0 - pad_y * height); iy1 = math.ceil(y1 + pad_y * height)
    cw, ch = ix1 - ix0, iy1 - iy0
    H, W = gray.shape
    sx0, sy0, sx1, sy1 = max(0, ix0), max(0, iy0), min(W, ix1), min(H, iy1)
    dark = is_dark_line(gray, box)
    canvas = np.full((ch, cw), 0 if dark else 255, dtype=np.uint8)
    if sx1 > sx0 and sy1 > sy0:
        canvas[sy0 - iy0:sy1 - iy0, sx0 - ix0:sx1 - ix0] = gray[sy0:sy1, sx0:sx1]
    width = max(1, round(cw * 64 / ch))
    r = cv2.resize(canvas, (width, 64), interpolation=cv2.INTER_AREA if ch > 64 else cv2.INTER_LINEAR).astype(np.float32) / 255.
    return r if dark else 1. - r


# ---------------------------------------------------------------- pipeline
class Microscopy:
    """Bina 0.4 Microscopy page OCR.

    single=False (default): the full 9.56M model. Both detectors run and the
    reading whose confident text is larger is kept (handwriting/print router).
    single=True: only the main detector (8.85M); faster, weaker on tables.
    reader: ONNX reader file for the onnx backend (reader.onnx, or reader.int8.onnx: about 1.5x faster).
    """

    MAIN = dict(file="det_main.onnx", thr=.3, hf=1.6)
    PRINT = dict(file="det_print.onnx", thr=.2, hf=1.9)

    def __init__(s, device=None, single=False, threads=4, backend=None, reader="reader.onnx", parallel=True):
        s.alpha = json.loads((ROOT / "vocab.json").read_text())["chars"]
        s.parallel = parallel
        o = ort.SessionOptions(); o.intra_op_num_threads = threads
        if backend is None:  # ONNX on CPU (fastest there); PyTorch when a GPU is asked for or available
            want_gpu = device == "cuda" or (device is None and torch is not None and torch.cuda.is_available())
            backend = "torch" if want_gpu else "onnx"
        s.backend = backend
        if backend == "onnx":
            s.dev = "cpu"
            s.rsess = ort.InferenceSession(str(ROOT / reader), o, providers=["CPUExecutionProvider"])
        else:
            if torch is None:
                raise RuntimeError("backend='torch' needs PyTorch: pip install torch")
            from safetensors.torch import load_file
            s.dev = device or ("cuda" if torch.cuda.is_available() else "cpu")
            sd = load_file(str(ROOT / "reader.safetensors"))
            depth = 1 + max(int(k.split(".")[1]) for k in sd if k.startswith("blocks."))
            s.reader = Reader(len(s.alpha) + 1, depth=depth)
            s.reader.load_state_dict(sd)
            s.reader.to(s.dev).eval()
        s.dets = [dict(s.MAIN, sess=ort.InferenceSession(str(ROOT / s.MAIN["file"]), o, providers=["CPUExecutionProvider"]))]
        if not single:
            s.dets.append(dict(s.PRINT, sess=ort.InferenceSession(str(ROOT / s.PRINT["file"]), o, providers=["CPUExecutionProvider"])))
        if backend == "onnx" and parallel and len(s.dets) > 1:  # one reader session per detector branch
            for d in s.dets:
                d["rsess"] = ort.InferenceSession(str(ROOT / reader), o, providers=["CPUExecutionProvider"])

    # -- detection: DB-style kernel map at 1/2 resolution -> line boxes
    def lines(s, rgb, det, long_side=1024, wf=.6):
        oh, ow = rgb.shape[:2]
        sc = min(1., long_side / max(oh, ow))
        h = max(32, round(oh * sc / 32) * 32); w = max(32, round(ow * sc / 32) * 32)
        x = cv2.resize(rgb, (w, h), interpolation=cv2.INTER_AREA).transpose(2, 0, 1)[None].astype(np.float32) / 127.5 - 1
        p = det["sess"].run(["prob"], {"x": x})[0][0, 0]
        m = (p > det["thr"]).astype(np.uint8)
        n, lab, st, _ = cv2.connectedComponentsWithStats(m, 8)
        fx = ow / p.shape[1]; fy = oh / p.shape[0]; boxes = []
        for i in range(1, n):
            if st[i, cv2.CC_STAT_AREA] < 4:
                continue
            ys, xs = np.nonzero(lab == i)
            (cx, cy), (rw, rh), ang = cv2.minAreaRect(np.stack([xs, ys], 1).astype(np.float32))
            vertical = abs((ang + 90) % 180 - 90) >= 45
            kh = rw if vertical else rh; kw = rh if vertical else rw
            lh = kh * det["hf"]; W = kw + wf * lh
            b = [max(0, (cx - W / 2) * fx), max(0, (cy - lh / 2) * fy), min(ow, (cx + W / 2) * fx), min(oh, (cy + lh / 2) * fy)]
            if b[2] - b[0] >= 2 and b[3] - b[1] >= 2:
                boxes.append(b)
        return boxes

    # -- right-to-left reading order: columns at gaps > 0.4 line heights, then rows
    @staticmethod
    def order(boxes, colg=.4, rowt=.55):
        def cut(bs):
            if len(bs) <= 1:
                return bs
            H = np.median([b[3] - b[1] for b in bs])
            ivs = sorted([(b[0], b[2]) for b in bs]); merged = [list(ivs[0])]
            for a, b in ivs[1:]:
                if a <= merged[-1][1] + colg * H:
                    merged[-1][1] = max(merged[-1][1], b)
                else:
                    merged.append([a, b])
            if len(merged) > 1:
                out = []
                for a, b in sorted(merged, key=lambda m: -m[0]):
                    out += cut([q for q in bs if q[0] >= a - 1 and q[2] <= b + 1])
                return out
            rows = []
            for b in sorted(bs, key=lambda b: (b[1] + b[3]) / 2):
                if rows and (b[1] + b[3]) / 2 - rows[-1]["c"] < rowt * H:
                    rows[-1]["b"].append(b); rows[-1]["c"] = np.mean([(q[1] + q[3]) / 2 for q in rows[-1]["b"]])
                else:
                    rows.append(dict(c=(b[1] + b[3]) / 2, b=[b]))
            return [q for r in rows for q in sorted(r["b"], key=lambda b: -b[2])]
        return cut(boxes) if boxes else []

    def _logits(s, x, ws, rsess=None):
        """Batch of 64px line crops -> (best symbol ids, their probabilities, valid lengths)."""
        if s.backend == "onnx":
            lp, ln = (rsess or s.rsess).run(None, {"x": x, "widths": ws.astype(np.int64)})  # log-probabilities
            return lp.argmax(-1), np.exp(lp.max(-1)), ln
        with torch.inference_mode():
            lg, ln = s.reader(torch.from_numpy(x).to(s.dev), torch.from_numpy(ws))
            pr = lg.float().softmax(-1)
            return pr.argmax(-1).cpu().numpy(), pr.max(-1).values.cpu().numpy(), ln.cpu().numpy()

    def read(s, gray, boxes, batch=32, rsess=None):
        crops = [crop_line64(gray, b) for b in boxes]; res = [None] * len(crops)
        idx = sorted(range(len(crops)), key=lambda i: crops[i].shape[1])
        for k in range(0, len(idx), batch):
            ids = idx[k:k + batch]; ws = np.array([crops[i].shape[1] for i in ids])
            P = int(math.ceil(ws.max() / 8) * 8); x = np.zeros((len(ids), 1, 64, P), np.float32)
            for j, i in enumerate(ids):
                x[j, 0, :, :crops[i].shape[1]] = crops[i]
            best, conf, ln = s._logits(x, ws, rsess)
            for j, i in enumerate(ids):
                z = best[j, :int(ln[j])]; keep = (z != 0) & np.r_[True, z[1:] != z[:-1]]
                text = flip("".join(s.alpha[t - 1] for t in z[keep]), base_rtl=True)
                res[i] = (text, float(conf[j, :int(ln[j])][keep].mean()) if keep.any() else 0.)
        return res

    @staticmethod
    def clean(lines):
        """Drop tiny noise boxes and duplicate reads of the same text."""
        if not lines:
            return lines
        from rapidfuzz import fuzz
        med = float(np.median([l["box"][3] - l["box"][1] for l in lines]))
        lines = [l for l in lines if l["box"][3] - l["box"][1] >= .4 * med]

        def ios(a, b):
            iw = min(a[2], b[2]) - max(a[0], b[0]); ih = min(a[3], b[3]) - max(a[1], b[1])
            return 0. if iw <= 0 or ih <= 0 else iw * ih / max(1e-6, min((a[2] - a[0]) * (a[3] - a[1]), (b[2] - b[0]) * (b[3] - b[1])))
        drop = set()
        for i, a in enumerate(lines):
            for j, b in enumerate(lines):
                if i == j or j in drop or len(a["text"]) > len(b["text"]) or (len(a["text"]) == len(b["text"]) and i > j):
                    continue
                if ios(a["box"], b["box"]) > .5 and fuzz.partial_ratio(a["text"].replace(" ", ""), b["text"].replace(" ", "")) >= 80:
                    drop.add(i); break
        return [l for i, l in enumerate(lines) if i not in drop]

    def _run(s, rgb, gray, det):
        bs = s.order(s.lines(rgb, det))
        rd = s.read(gray, bs, rsess=det.get("rsess")) if bs else []
        lines = [dict(box=[round(float(v), 1) for v in b], text=t, confidence=round(c, 4))
                 for b, (t, c) in zip(bs, rd) if t.strip() and c >= .5]
        lines = s.clean(lines)
        return dict(text="\n".join(l["text"] for l in lines), lines=lines)

    def __call__(s, image):
        rgb = np.asarray(image.convert("RGB")); gray = np.asarray(image.convert("L"))
        branch = lambda d: dict(s._run(rgb, gray, d), detector=d["file"])
        if s.parallel and len(s.dets) > 1:  # ONNX Runtime releases the GIL: both detector branches run at once
            from concurrent.futures import ThreadPoolExecutor
            with ThreadPoolExecutor(len(s.dets)) as ex:
                outs = list(ex.map(branch, s.dets))
        else:
            outs = [branch(d) for d in s.dets]
        score = lambda r: sum(len(l["text"]) * l["confidence"] for l in r["lines"] if l["confidence"] >= .8)
        best = outs[0]
        for r in outs[1:]:
            if score(r) > score(best):
                best = r
        return best


# ---------------------------------------------------------------- CLI
def pages(path, dpi=200):
    p = Path(path)
    if p.suffix.lower() == ".pdf":
        import pypdfium2 as pdfium
        doc = pdfium.PdfDocument(str(p))
        for i in range(len(doc)):
            yield f"{p.stem}-p{i + 1:03d}", doc[i].render(scale=dpi / 72).to_pil().convert("RGB")
    else:
        from PIL import Image
        yield p.stem, Image.open(p).convert("RGB")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("inputs", nargs="+", help="images (png/jpg/webp/tif) or PDFs")
    ap.add_argument("--out", default="microscopy-out")
    ap.add_argument("--backend", default=None, choices=[None, "onnx", "torch"],
                    help="reader runtime (default: onnx on CPU, torch when a GPU is used)")
    ap.add_argument("--reader", default="reader.onnx", help="ONNX reader file, e.g. reader.int8.onnx (onnx backend)")
    ap.add_argument("--device", default=None, choices=[None, "cpu", "cuda"])
    ap.add_argument("--single", action="store_true", help="main detector only (8.85M, faster)")
    ap.add_argument("--dpi", type=int, default=200, help="PDF render resolution")
    a = ap.parse_args()
    ocr = Microscopy(a.device, single=a.single, backend=a.backend, reader=a.reader)
    out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
    for path in a.inputs:
        for name, im in pages(path, a.dpi):
            t = time.time(); r = ocr(im)
            (out / f"{name}.txt").write_text(r["text"] + "\n", encoding="utf-8")
            (out / f"{name}.json").write_text(json.dumps(r, ensure_ascii=False, indent=1), encoding="utf-8")
            print(f"{name}: {len(r['lines'])} lines, {time.time() - t:.2f}s -> {out / name}.txt")


if __name__ == "__main__":
    main()