#!/usr/bin/env python3 """End-to-end Nepali + English OCR for CPU, without PyTorch. Images: line detector (ONNX) -> reading order -> per-line straightening -> recognizer (ONNX, int8) -> confidence filter -> CTC beam search with a compact character language model -> one digit script per number (digits.py). PDFs: each page is routed; a trusted text layer is read directly, any other page is rendered and OCR'd. Two modes with the settings each was validated with: print (pipeline_eval.py, frozen 10 Nov, plus table-aware reading order) and handwriting (nhd_pipeline.py: handwriting line detector at scale 0.35 for ~A4 scans, lines sorted by centre height, no confidence filter). usage: python ocr.py FILE [FILE ...] [--mode print|handwriting] [--no-lm] [--threads 1] [--dpi 150] [--json]""" import argparse, json, math, sys, time from pathlib import Path import numpy as np, cv2, onnxruntime as ort T = Path(__file__).resolve().parent; sys.path[:0] = [str(T), str(T/"third_party")] import decode as D, reading_order as RO, digits as DG from lines import prep CORE = .4 # detector core band = middle 40% of the line height (as in tiny_det.py) MODES = {"print": dict(det="det_fp32.onnx", det_scale=1.0, alpha=.2, beta=2.0, min_conf=.5, order="xycut"), "handwriting": dict(det="det_hw_fp32.onnx", det_scale=.35, alpha=.4, beta=1.0, min_conf=0.0, order="y")} def boxes_from(prob, scale=1.0, stride=2, th=.5, min_area=3): """Line boxes [x0, y0, x1, y1, slope] in input pixels from the detector's core probability map (tiny_det.boxes_from, thick=True, slopes=True).""" n, lab, st, _ = cv2.connectedComponentsWithStats((prob >= th).astype(np.uint8), connectivity=4); out = [] for i in range(1, n): x, y, bw, bh, a = st[i] if a < min_area: continue ch = bh * stride; cy = (y + bh / 2) * stride; t = min(ch, a / bw * stride); H = (ch - t) + t / CORE; m = .25 * t / CORE b = [(x * stride - m) / scale, (cy - H / 2) / scale, ((x + bw) * stride + m) / scale, (cy + H / 2) / scale] ys, xs = np.nonzero(lab[y:y + bh, x:x + bw] == i); k = 0.0 if bw >= 8 and len(xs) > 10 and np.ptp(xs) > 0: k = float(np.polyfit(xs, ys, 1)[0]) out.append(b + [k]) return out class OCR: def __init__(s, model=T/"models", rec="rec_fp32.onnx", lm=T/"models/lm.npz", mode="print", threads=1, digits=True, tables=True, det_th=.5, **over): c = dict(MODES[mode]); c.update(over) # any mode setting can be overridden by keyword model = Path(model); meta = json.load(open(model/"meta.json", encoding="utf-8")); s.chars, s.H, s.norm = meta["chars"], meta["H"], meta["norm"] so = ort.SessionOptions(); so.intra_op_num_threads = threads; so.inter_op_num_threads = 1 s.rec = ort.InferenceSession(str(model/rec), so, providers=["CPUExecutionProvider"]); s.det = ort.InferenceSession(str(model/c["det"]), so, providers=["CPUExecutionProvider"]) s.lm = D.load_lm(lm) if lm else None; s.alpha, s.beta, s.min_conf, s.det_scale, s.order = c["alpha"], c["beta"], c["min_conf"], c["det_scale"], c["order"] s.det_th, s.digits, s.tables, s.mode = det_th, digits, tables, mode def detect(s, g): h, w = g.shape; sc = min(s.det_scale, 2400 / max(h, w)) gg = cv2.resize(g, (max(16, int(w * sc)), max(16, int(h * sc))), interpolation=cv2.INTER_AREA if sc < 1 else cv2.INTER_LINEAR) if sc != 1 else g # AREA: antialiased shrink, like PIL H, Wd = gg.shape; z = np.zeros(((H + 31) // 32 * 32, (Wd + 31) // 32 * 32), np.float32); z[:H, :Wd] = 1 - gg.astype(np.float32) / 255 lg = s.det.run(None, {"x": z[None, None]})[0][0, 0][:H // 2, :Wd // 2]; p = 1 / (1 + np.exp(-lg)) bx = [[max(0, b[0]), max(0, b[1]), min(w, b[2]), min(h, b[3]), b[4]] for b in boxes_from(p, sc, th=s.det_th)] if not bx: return [] if s.order == "y": return sorted(bx, key=lambda b: (b[1] + b[3]) / 2) # top to bottom by line centre, as nhd_pipeline.py return RO.xycut_shear(bx, tables=s.tables) @staticmethod def crop(g, b): """Tight crop of a line box; a tilted line is sheared level and the rise trimmed (pipeline_eval.tight with straighten=1).""" x0, y0, x1, y1 = [int(round(v)) for v in b[:4]]; k = g[max(0, y0):y1, max(0, x0):x1] if not k.size: return g[:8, :8] sl = b[4] if abs(sl) > .004: hh, ww = k.shape; M = np.float32([[1, 0, 0], [sl, 1, -sl * ww / 2]]) im = cv2.warpAffine(k, M, (ww, hh), flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderValue=255) c = int(abs(sl) * ww / 2); k = im[c:hh - c] if hh - 2 * c >= 8 else im return k def read_line(s, k): x = prep(k, s.H, s.norm)[None, None].astype(np.float32); lg = s.rec.run(None, {"x": x})[0][0] lp = lg - lg.max(1, keepdims=True); lp = lp - np.log(np.exp(lp).sum(1, keepdims=True)) t, cf = D.greedy(lp, s.chars) if cf < s.min_conf: return "", cf out = D.beam(lp, s.chars, s.lm, s.alpha, s.beta) if s.lm else t return (DG.unify(out, DG.run_scripts(lp, s.chars)) if s.digits else out), cf def image(s, g): """g: grayscale uint8 page or block. Returns text (lines joined by newlines) and per-line detail.""" t0 = time.perf_counter(); bx = s.detect(g); t1 = time.perf_counter(); L = [] for b in bx: t, cf = s.read_line(s.crop(g, b)); L.append(dict(box=[round(v, 1) for v in b[:4]], text=t, conf=round(cf, 3))) t2 = time.perf_counter() return dict(text="\n".join(l["text"] for l in L if l["text"]), lines=L, ms=dict(detect=round(1000 * (t1 - t0), 1), read=round(1000 * (t2 - t1), 1))) def pdf(s, path, dpi=150, extractor="poppler"): import pypdfium2 as pdfium, pdf_route as PR, pdf_text as PT, subprocess, shutil if extractor == "poppler" and not shutil.which("pdftotext"): extractor = "pdfium" # poppler-utils not installed out = []; doc = pdfium.PdfDocument(str(path)) for i in range(len(doc)): p = doc[i]; t0 = time.perf_counter(); g100 = np.asarray(p.render(scale=100 / 72).to_pil().convert("L")); ok, tl, info = PR.page_text_ok(p, g100, 100 / 72) if ok: txt = PT.page_text(p) if extractor == "pdfium" else subprocess.run(["pdftotext", "-raw", "-f", str(i + 1), "-l", str(i + 1), str(path), "-"], capture_output=True, text=True).stdout.strip() out.append(dict(page=i + 1, route="text", text=txt, ms=round(1000 * (time.perf_counter() - t0), 1))) else: g = np.asarray(p.render(scale=dpi / 72).to_pil().convert("L")); r = s.image(g) out.append(dict(page=i + 1, route="ocr", reason=info.get("reason", ""), text=r["text"], ms=round(1000 * (time.perf_counter() - t0), 1))) p.close() doc.close(); return out if __name__ == "__main__": a = argparse.ArgumentParser(); a.add_argument("files", nargs="+"); a.add_argument("--model", default=str(T/"models")); a.add_argument("--rec", default="rec_fp32.onnx", help="rec_int8.onnx: 1.06 MB, slightly less accurate on worn print") a.add_argument("--lm", default=str(T/"models/lm.npz")); a.add_argument("--no-lm", action="store_true"); a.add_argument("--mode", default="print", choices=list(MODES)) a.add_argument("--threads", type=int, default=1); a.add_argument("--dpi", type=int, default=150); a.add_argument("--json", action="store_true"); x = a.parse_args() o = OCR(x.model, x.rec, None if x.no_lm else x.lm, mode=x.mode, threads=x.threads) for f in x.files: if f.lower().endswith(".pdf"): r = o.pdf(f, x.dpi) else: r = [o.image(cv2.imread(f, cv2.IMREAD_GRAYSCALE))] if x.json: print(json.dumps(dict(file=f, pages=r), ensure_ascii=False)) else: for pg in r: print(pg["text"])