sumoocr 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sumoocr/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """SumoOCR tiny: fast CPU OCR for business documents in Latin-script languages.
2
+
3
+ from sumoocr import SumoOCR
4
+ ocr = SumoOCR()
5
+ for line in ocr("invoice.png"):
6
+ print(line.text, line.conf, line.box)
7
+ """
8
+ from .ocr import Line, SumoOCR
9
+
10
+ __all__ = ["SumoOCR", "Line"]
11
+ __version__ = "1.0.0"
sumoocr/backend.py ADDED
@@ -0,0 +1,64 @@
1
+ """Model runtimes: ONNX Runtime (default) or OpenVINO (`pip install sumoocr[openvino]`), CPU."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from typing import Optional
6
+
7
+ import numpy as np
8
+
9
+ BACKENDS = ("onnxruntime", "openvino")
10
+
11
+
12
+ class ORTModel:
13
+ def __init__(self, path: str, threads: Optional[int] = None, arena: bool = True):
14
+ import onnxruntime as ort
15
+
16
+ so = ort.SessionOptions()
17
+ so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
18
+ if threads:
19
+ so.intra_op_num_threads = int(threads)
20
+ so.inter_op_num_threads = 1
21
+ if int(threads) == 1:
22
+ so.add_session_config_entry("session.intra_op.allow_spinning", "0")
23
+ so.enable_cpu_mem_arena = bool(arena)
24
+ so.log_severity_level = 3
25
+ self.sess = ort.InferenceSession(path, so, providers=["CPUExecutionProvider"])
26
+ self._in = self.sess.get_inputs()[0].name
27
+
28
+ def __call__(self, x: np.ndarray) -> np.ndarray:
29
+ return self.sess.run(None, {self._in: np.ascontiguousarray(x, dtype=np.float32)})[0]
30
+
31
+
32
+ class OVModel:
33
+ def __init__(self, path: str, threads: Optional[int] = None, fix_height: int = 0):
34
+ os.environ.setdefault("CI", "true") # openvino_telemetry: never prompt
35
+ import platform
36
+ import openvino as ov
37
+
38
+ core = ov.Core()
39
+ model = core.read_model(path)
40
+ if fix_height: # recognizer: fixed height, dynamic batch and width
41
+ inp = model.inputs[0]
42
+ ps = inp.get_partial_shape()
43
+ if ps.rank.is_static and len(ps) == 4 and ps[2].is_dynamic:
44
+ model.reshape({inp.get_any_name(): ov.PartialShape([-1, ps[1], int(fix_height), -1])})
45
+ props = {"NUM_STREAMS": 1, "PERFORMANCE_HINT": "LATENCY", "INFERENCE_PRECISION_HINT": "f32"}
46
+ if any(op.get_type_name() == "FakeQuantize" for op in model.get_ops()) and \
47
+ platform.machine().lower() not in ("x86_64", "amd64"):
48
+ props["LP_TRANSFORMS_MODE"] = False
49
+ if threads:
50
+ props["INFERENCE_NUM_THREADS"] = int(threads)
51
+ self.req = core.compile_model(model, "CPU", props).create_infer_request()
52
+
53
+ def __call__(self, x: np.ndarray) -> np.ndarray:
54
+ self.req.infer({0: np.ascontiguousarray(x, dtype=np.float32)}, share_inputs=True)
55
+ return self.req.get_output_tensor(0).data.copy()
56
+
57
+
58
+ def load_model(path: str, backend: str = "onnxruntime", threads: Optional[int] = None, fix_height: int = 0,
59
+ arena: bool = True):
60
+ if backend == "onnxruntime":
61
+ return ORTModel(path, threads, arena=arena)
62
+ if backend == "openvino":
63
+ return OVModel(path, threads, fix_height)
64
+ raise ValueError(f"backend must be one of {BACKENDS}, not {backend!r}")
sumoocr/cli.py ADDED
@@ -0,0 +1,34 @@
1
+ """sumoocr IMAGE... [--format text|json] [--backend onnxruntime|openvino] [--threads N] [--max-side PX]"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+
8
+
9
+ def main(argv=None) -> int:
10
+ ap = argparse.ArgumentParser(prog="sumoocr", description="SumoOCR tiny: text lines of page images, on CPU.")
11
+ ap.add_argument("images", nargs="+", help="page images (PNG, JPEG, TIFF, BMP, WebP)")
12
+ ap.add_argument("--format", choices=("text", "json"), default="text",
13
+ help="text: one line per text line; json: one object per image with lines, boxes, confidences")
14
+ ap.add_argument("--backend", choices=("onnxruntime", "openvino"), default="onnxruntime")
15
+ ap.add_argument("--threads", type=int, default=None, help="CPU threads per model (default: the runtime's)")
16
+ ap.add_argument("--max-side", type=int, default=1280,
17
+ help="detector's long-side cap in px (dense small print auto-scales to 2400)")
18
+ a = ap.parse_args(argv)
19
+ from . import SumoOCR
20
+
21
+ ocr = SumoOCR(backend=a.backend, threads=a.threads, max_side=a.max_side)
22
+ for path in a.images:
23
+ lines = ocr(path)
24
+ if a.format == "json":
25
+ print(json.dumps({"image": path, "lines": [ln.to_dict() for ln in lines]}, ensure_ascii=False))
26
+ else:
27
+ if len(a.images) > 1:
28
+ print(f"==> {path} <==")
29
+ print("\n".join(ln.text for ln in lines))
30
+ return 0
31
+
32
+
33
+ if __name__ == "__main__":
34
+ sys.exit(main())
sumoocr/det.py ADDED
@@ -0,0 +1,132 @@
1
+ """Text detection: input scaling, DB post-processing, reading order, box levelling (PP-OCRv6 tiny detector)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from typing import List, Tuple
6
+
7
+ import cv2
8
+ import numpy as np
9
+
10
+ MEAN = STD = np.array([0.5, 0.5, 0.5], np.float32) # detector input: (x / 255 - 0.5) / 0.5, BGR
11
+
12
+
13
+ def det_input_size(h: int, w: int, scale: float, max_pixels: float) -> Tuple[int, int]:
14
+ """(nh, nw): multiples of 32 near (h * scale, w * scale), capped at max_pixels."""
15
+ if max_pixels and h * w * scale * scale > max_pixels:
16
+ scale = math.sqrt(max_pixels / float(h * w))
17
+ return max(32, int(round(h * scale / 32.0)) * 32), max(32, int(round(w * scale / 32.0)) * 32)
18
+
19
+
20
+ def preprocess(img: np.ndarray, nh: int, nw: int, rgb: bool = False) -> np.ndarray:
21
+ """Page (BGR, or RGB when rgb=True) -> 1 x 3 x nh x nw float32 in the detector's BGR order."""
22
+ return cv2.dnn.blobFromImage(img, scalefactor=2.0 / 255.0, size=(nw, nh), mean=(127.5, 127.5, 127.5),
23
+ swapRB=rgb, crop=False)
24
+
25
+
26
+ def _order_quad(pts: np.ndarray) -> np.ndarray:
27
+ """4 points -> top-left, top-right, bottom-right, bottom-left."""
28
+ pts = pts[np.argsort(pts[:, 0], kind="stable")]
29
+ left, right = pts[:2], pts[2:]
30
+ tl, bl = (left[0], left[1]) if left[0][1] <= left[1][1] else (left[1], left[0])
31
+ tr, br = (right[0], right[1]) if right[0][1] <= right[1][1] else (right[1], right[0])
32
+ return np.array([tl, tr, br, bl], dtype=np.float32)
33
+
34
+
35
+ def db_postprocess(prob: np.ndarray, thresh: float = 0.3, box_thresh: float = 0.5, unclip_ratio: float = 1.6,
36
+ max_candidates: int = 5000, min_size: float = 3.0) -> Tuple[List[np.ndarray], List[float]]:
37
+ """DB probability map (H x W) -> quads (map pixels) and box scores: binarize, 2 x 2 dilation, contours,
38
+ minAreaRect, mean probability inside the box, unclip. Unclipping a w x h rectangle by
39
+ d = area * ratio / perimeter is done analytically (the (w + 2d) x (h + 2d) rectangle, same centre and angle)."""
40
+ bitmap = cv2.dilate((prob > thresh).astype(np.uint8), np.ones((2, 2), np.uint8))
41
+ contours, _ = cv2.findContours(bitmap, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
42
+ H, W = prob.shape
43
+ quads: List[np.ndarray] = []
44
+ scores: List[float] = []
45
+ for cnt in contours[:max_candidates]:
46
+ (cx, cy), (rw, rh), ang = cv2.minAreaRect(cnt)
47
+ if min(rw, rh) < min_size:
48
+ continue
49
+ pts = cv2.boxPoints(((cx, cy), (rw, rh), ang))
50
+ xmin = int(np.clip(np.floor(pts[:, 0].min()), 0, W - 1))
51
+ xmax = int(np.clip(np.ceil(pts[:, 0].max()), 0, W - 1))
52
+ ymin = int(np.clip(np.floor(pts[:, 1].min()), 0, H - 1))
53
+ ymax = int(np.clip(np.ceil(pts[:, 1].max()), 0, H - 1))
54
+ mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), np.uint8)
55
+ q = pts.copy()
56
+ q[:, 0] -= xmin
57
+ q[:, 1] -= ymin
58
+ cv2.fillPoly(mask, [q.astype(np.int32)], 1)
59
+ score = cv2.mean(prob[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
60
+ if score < box_thresh:
61
+ continue
62
+ d = rw * rh * unclip_ratio / (2.0 * (rw + rh))
63
+ nw_, nh_ = rw + 2 * d, rh + 2 * d
64
+ if min(nw_, nh_) < min_size + 2:
65
+ continue
66
+ quads.append(_order_quad(cv2.boxPoints(((cx, cy), (nw_, nh_), ang))))
67
+ scores.append(float(score))
68
+ return quads, scores
69
+
70
+
71
+ def sort_reading_order(quads: List[np.ndarray], y_tol: float = 0.5) -> List[int]:
72
+ """Indices top to bottom, then left to right within a line (a box joins the current line when its centre is
73
+ within y_tol x the line's height of the line's)."""
74
+ if not quads:
75
+ return []
76
+ cy = [float(q[:, 1].mean()) for q in quads]
77
+ hh = [max(1.0, float(q[:, 1].max() - q[:, 1].min())) for q in quads]
78
+ cx = [float(q[:, 0].min()) for q in quads]
79
+ lines: List[List[int]] = []
80
+ ref = None
81
+ for i in sorted(range(len(quads)), key=lambda i: (cy[i], cx[i])):
82
+ if lines and abs(cy[i] - ref[0]) <= y_tol * ref[1]:
83
+ lines[-1].append(i)
84
+ else:
85
+ lines.append([i])
86
+ ref = (cy[i], hh[i])
87
+ return [i for ln in lines for i in sorted(ln, key=lambda j: cx[j])]
88
+
89
+
90
+ def _mod90(a: float) -> float:
91
+ return (a + 45.0) % 90.0 - 45.0
92
+
93
+
94
+ def level_quads(quads: List[np.ndarray], max_growth: float, min_deg: float = 1.0, ref_lines: int = 3,
95
+ neighbours: int = 10, square: float = 1.5) -> List[np.ndarray]:
96
+ """Returned boxes with the odd tilted ones levelled (output only: lines are read from the original boxes).
97
+ A box more than min_deg off both the page angle and the length-weighted median angle of its nearest line-like
98
+ neighbours is replaced by its bounding rectangle along that angle, when the rectangle is at most max_growth x its
99
+ area (mixed-size glyphs, e.g. a small field number before a large letter, tilt minAreaRect boxes)."""
100
+ if max_growth <= 0 or len(quads) < ref_lines:
101
+ return list(quads)
102
+ q = np.array(quads, np.float64)
103
+ e1, e2 = q[:, 1] - q[:, 0], q[:, 3] - q[:, 0]
104
+ l1, l2 = np.hypot(e1[:, 0], e1[:, 1]), np.hypot(e2[:, 0], e2[:, 1])
105
+ ang = np.array([_mod90(math.degrees(math.atan2(y, x))) for x, y in e1])
106
+ cen = q.mean(axis=1)
107
+ lines = np.flatnonzero(np.maximum(l1, l2) >= 3.0 * np.minimum(l1, l2))
108
+ if len(lines) < ref_lines:
109
+ return list(quads)
110
+ page = float(np.median(ang[lines]))
111
+ out = list(quads)
112
+ for i in np.flatnonzero([abs(_mod90(a - page)) > min_deg for a in ang]):
113
+ near = lines[np.argsort(((cen[lines] - cen[i]) ** 2).sum(axis=1))]
114
+ near = near[near != i][:neighbours]
115
+ off = np.array([_mod90(a - page) for a in ang[near]])
116
+ o = np.argsort(off)
117
+ cum = np.cumsum(np.maximum(l1, l2)[near][o])
118
+ ref = page + float(off[o][np.searchsorted(cum, cum[-1] / 2.0)])
119
+ if abs(_mod90(ang[i] - ref)) <= min_deg:
120
+ continue
121
+ t = math.radians(ref)
122
+ u, v = np.array([math.cos(t), math.sin(t)]), np.array([-math.sin(t), math.cos(t)])
123
+ s, r = q[i] @ u, q[i] @ v
124
+ if max(l1[i], l2[i]) < square * min(l1[i], l2[i]): # one glyph: no text direction, level it in place
125
+ cs, cr = cen[i] @ u, cen[i] @ v
126
+ s, r = np.array([cs - l1[i] / 2, cs + l1[i] / 2]), np.array([cr - l2[i] / 2, cr + l2[i] / 2])
127
+ elif (s.max() - s.min()) * (r.max() - r.min()) > max_growth * l1[i] * l2[i]:
128
+ continue
129
+ out[i] = _order_quad(np.array([s0 * u + r0 * v for s0, r0 in
130
+ ((s.min(), r.min()), (s.max(), r.min()), (s.max(), r.max()), (s.min(), r.max()))],
131
+ np.float32))
132
+ return out
@@ -0,0 +1,7 @@
1
+ {
2
+ "H": 40,
3
+ "time_stride": 4,
4
+ "classes": 758,
5
+ "rec_input": "BGR line crop resized to height H (aspect kept), (x / 255 - 0.5) / 0.5, N x 3 x H x W; output softmax N x W/4 x classes, class 0 = CTC blank",
6
+ "det_input": "BGR page resized to multiples of 32, (x / 255 - 0.5) / 0.5, 1 x 3 x h x w; output text probability map 1 x 1 x h x w"
7
+ }
Binary file
@@ -0,0 +1 @@
1
+ ["blank", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "@", "[", "\\", "]", "^", "_", "`", "{", "|", "}", "~", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "®", "¯", "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "Ā", "ā", "Ă", "ă", "Ą", "ą", "Ć", "ć", "Ĉ", "ĉ", "Ċ", "ċ", "Č", "č", "Ď", "ď", "Đ", "đ", "Ē", "ē", "Ĕ", "ĕ", "Ė", "ė", "Ę", "ę", "Ě", "ě", "Ĝ", "ĝ", "Ğ", "ğ", "Ġ", "ġ", "Ģ", "ģ", "Ĥ", "ĥ", "Ħ", "ħ", "Ĩ", "ĩ", "Ī", "ī", "Ĭ", "ĭ", "Į", "į", "İ", "ı", "IJ", "ij", "Ĵ", "ĵ", "Ķ", "ķ", "ĸ", "Ĺ", "ĺ", "Ļ", "ļ", "Ľ", "ľ", "Ŀ", "ŀ", "Ł", "ł", "Ń", "ń", "Ņ", "ņ", "Ň", "ň", "ʼn", "Ŋ", "ŋ", "Ō", "ō", "Ŏ", "ŏ", "Ő", "ő", "Œ", "œ", "Ŕ", "ŕ", "Ŗ", "ŗ", "Ř", "ř", "Ś", "ś", "Ŝ", "ŝ", "Ş", "ş", "Š", "š", "Ţ", "ţ", "Ť", "ť", "Ŧ", "ŧ", "Ũ", "ũ", "Ū", "ū", "Ŭ", "ŭ", "Ů", "ů", "Ű", "ű", "Ų", "ų", "Ŵ", "ŵ", "Ŷ", "ŷ", "Ÿ", "Ź", "ź", "Ż", "ż", "Ž", "ž", "ſ", "ƀ", "Ɓ", "Ƃ", "ƃ", "Ƅ", "ƅ", "Ɔ", "Ƈ", "ƈ", "Ɖ", "Ɗ", "Ƌ", "ƌ", "ƍ", "Ǝ", "Ə", "Ɛ", "Ƒ", "ƒ", "Ɠ", "Ɣ", "ƕ", "Ɩ", "Ɨ", "Ƙ", "ƙ", "ƚ", "ƛ", "Ɯ", "Ɲ", "ƞ", "Ɵ", "Ơ", "ơ", "Ƣ", "ƣ", "Ƥ", "ƥ", "Ʀ", "Ƨ", "ƨ", "Ʃ", "ƪ", "ƫ", "Ƭ", "ƭ", "Ʈ", "Ư", "ư", "Ʊ", "Ʋ", "Ƴ", "ƴ", "Ƶ", "ƶ", "Ʒ", "Ƹ", "ƹ", "ƺ", "ƻ", "Ƽ", "ƽ", "ƾ", "ƿ", "ǀ", "ǁ", "ǂ", "ǃ", "DŽ", "Dž", "dž", "LJ", "Lj", "lj", "NJ", "Nj", "nj", "Ǎ", "ǎ", "Ǐ", "ǐ", "Ǒ", "ǒ", "Ǔ", "ǔ", "Ǖ", "ǖ", "Ǘ", "ǘ", "Ǚ", "ǚ", "Ǜ", "ǜ", "ǝ", "Ǟ", "ǟ", "Ǡ", "ǡ", "Ǣ", "ǣ", "Ǥ", "ǥ", "Ǧ", "ǧ", "Ǩ", "ǩ", "Ǫ", "ǫ", "Ǭ", "ǭ", "Ǯ", "ǯ", "ǰ", "DZ", "Dz", "dz", "Ǵ", "ǵ", "Ƕ", "Ƿ", "Ǹ", "ǹ", "Ǻ", "ǻ", "Ǽ", "ǽ", "Ǿ", "ǿ", "Ȁ", "ȁ", "Ȃ", "ȃ", "Ȅ", "ȅ", "Ȇ", "ȇ", "Ȉ", "ȉ", "Ȋ", "ȋ", "Ȍ", "ȍ", "Ȏ", "ȏ", "Ȑ", "ȑ", "Ȓ", "ȓ", "Ȕ", "ȕ", "Ȗ", "ȗ", "Ș", "ș", "Ț", "ț", "Ȝ", "ȝ", "Ȟ", "ȟ", "Ƞ", "ȡ", "Ȣ", "ȣ", "Ȥ", "ȥ", "Ȧ", "ȧ", "Ȩ", "ȩ", "Ȫ", "ȫ", "Ȭ", "ȭ", "Ȯ", "ȯ", "Ȱ", "ȱ", "Ȳ", "ȳ", "ȴ", "ȵ", "ȶ", "ȷ", "ȸ", "ȹ", "Ⱥ", "Ȼ", "ȼ", "Ƚ", "Ⱦ", "ȿ", "ɀ", "Ɂ", "ɂ", "Ƀ", "Ʉ", "Ʌ", "Ɇ", "ɇ", "Ɉ", "ɉ", "Ɋ", "ɋ", "Ɍ", "ɍ", "Ɏ", "ɏ", "Ạ", "ồ", "–", "—", "―", "‖", "‘", "’", "“", "”", "†", "‡", "•", "‥", "…", "‰", "′", "″", "※", "⁎", "₠", "₡", "₢", "₣", "₤", "₥", "₦", "₧", "₨", "₩", "₪", "₫", "€", "₭", "₮", "₯", "₰", "₱", "₲", "₳", "₴", "₵", "₶", "₷", "₸", "₹", "₺", "₻", "₼", "₽", "₾", "₿", "℃", "℉", "ℎ", "ℏ", "ℑ", "℘", "ℜ", "™", "℧", "Å", "ℵ", "ℶ", "ℷ", "ℸ", "ℹ", "⅀", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ", "ⅰ", "ⅱ", "ⅲ", "ⅳ", "ⅴ", "ⅵ", "ⅶ", "ⅷ", "ⅸ", "ⅹ", "ⅺ", "ⅻ", "ⅼ", "ↀ", "ↁ", "ↂ", "←", "↑", "→", "↓", "↔", "↕", "↖", "↗", "↘", "↙", "↚", "↛", "↜", "↝", "↞", "↟", "↠", "↡", "↢", "↣", "↤", "↥", "↦", "↧", "↨", "↩", "↪", "↫", "↬", "↭", "↮", "↯", "↰", "↱", "↲", "↳", "↴", "↵", "↶", "↷", "↸", "↹", "↺", "↻", "↼", "↽", "↾", "↿", "⇀", "⇁", "⇂", "⇃", "⇄", "⇅", "⇆", "⇇", "⇈", "⇉", "⇊", "⇋", "⇌", "⇍", "⇎", "⇏", "⇐", "⇑", "⇒", "⇓", "⇔", "⇕", "⇖", "⇗", "⇘", "⇙", "⇚", "⇛", "⇜", "⇝", "⇞", "⇟", "⇠", "⇡", "⇢", "⇣", "⇤", "⇥", "⇦", "⇧", "⇨", "⇩", "⇪", "⇫", "⇬", "⇭", "⇮", "⇯", "⇰", "⇱", "⇲", "⇳", "⇴", "⇵", "⇶", "⇷", "⇸", "⇹", "⇺", "⇻", "⇼", "⇽", "⇾", "⇿", "∆", "∑", "−", "√", "∞", "≈", "≠", "≤", "≥", "☐", "☑", "☒", "□", "■", "●", "○", "◆", "◇", "✓", "✔", "✘", "„", "‚", "‹", "›", " "]
Binary file
sumoocr/ocr.py ADDED
@@ -0,0 +1,240 @@
1
+ """SumoOCR tiny: a page -> its text lines (detector + recognizer), or one line crop -> its text."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from dataclasses import asdict, dataclass
7
+ from typing import Any, List, Optional, Sequence, Tuple, Union
8
+
9
+ import cv2
10
+ import numpy as np
11
+
12
+ from .backend import load_model
13
+ from .det import db_postprocess, det_input_size, level_quads, preprocess, sort_reading_order
14
+ from .rec import CTCDecoder, crop_line, recognize
15
+
16
+ MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
17
+
18
+
19
+ @dataclass
20
+ class Line:
21
+ """One text line: its text, mean character confidence (0-1) and box (4 [x, y] points, clockwise from the
22
+ top-left, in pixels of the input image)."""
23
+ text: str
24
+ conf: float
25
+ box: List[List[float]]
26
+
27
+ def to_dict(self) -> dict:
28
+ return asdict(self)
29
+
30
+
31
+ def _rotate(img: np.ndarray, deg: int) -> np.ndarray:
32
+ """Turn the image clockwise by deg (90 / 180 / 270)."""
33
+ if deg == 90:
34
+ return cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
35
+ if deg == 180:
36
+ return cv2.rotate(img, cv2.ROTATE_180)
37
+ if deg == 270:
38
+ return cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
39
+ return img
40
+
41
+
42
+ def _rotate_pts(q: np.ndarray, deg: int, h: int, w: int) -> np.ndarray:
43
+ """Point coordinates after turning an h x w image clockwise by deg (same point order)."""
44
+ x, y = q[:, 0], q[:, 1]
45
+ if deg == 180:
46
+ return np.stack([w - x, h - y], 1).astype(np.float32)
47
+ if deg == 90:
48
+ return np.stack([h - y, x], 1).astype(np.float32)
49
+ if deg == 270:
50
+ return np.stack([y, w - x], 1).astype(np.float32)
51
+ return q
52
+
53
+
54
+ # after a turn by deg, the new tl, tr, br, bl are these points of _rotate_pts
55
+ _QUAD_ORDER = {180: [2, 3, 0, 1], 90: [3, 0, 1, 2], 270: [1, 2, 3, 0]}
56
+
57
+
58
+ def _rotate_quad(q: np.ndarray, deg: int, h: int, w: int) -> np.ndarray:
59
+ """Box coordinates after turning an h x w image clockwise by deg (re-ordered tl, tr, br, bl)."""
60
+ if deg in _QUAD_ORDER:
61
+ return _rotate_pts(q, deg, h, w)[_QUAD_ORDER[deg]]
62
+ return q
63
+
64
+
65
+ class SumoOCR:
66
+ """Page OCR with SumoOCR tiny.
67
+
68
+ ocr = SumoOCR() # ONNX Runtime on CPU; backend="openvino" needs `pip install sumoocr[openvino]`
69
+ lines = ocr("invoice.png") # a path, an H x W x 3 uint8 array (BGR, as cv2.imread) or a PIL image
70
+ text, conf = ocr.read_line(crop) # one line crop (any height)
71
+
72
+ The defaults are the settings the benchmarks were run with. max_side caps the long side of the page the detector
73
+ sees (1,280 px by default, automatically stepping up to 2,400 px on dense small print such as newspapers when
74
+ adaptive=True). text_score drops lines whose mean character confidence is below it. threads: CPU threads per model
75
+ (None = the runtime's default)."""
76
+
77
+ def __init__(self, backend: str = "onnxruntime", threads: Optional[int] = None, model_dir: str = MODEL_DIR,
78
+ det_model: Optional[str] = None, rec_model: Optional[str] = None,
79
+ max_side: int = 1280, min_side: int = 0, max_det_pixels: float = 6.0e6, det_thresh: float = 0.3,
80
+ box_thresh: float = 0.4, unclip_ratio: float = 1.6, text_score: float = 0.85, space_bias: float = 2.0,
81
+ box_level: float = 1.5, orient: bool = True, orient_conf: float = 0.92, orient_sample: int = 10,
82
+ adaptive: bool = True, adaptive_med_h: float = 13.0, adaptive_max_side: int = 2400, batch: int = 1):
83
+ if threads:
84
+ cv2.setNumThreads(int(threads))
85
+ cfg = json.load(open(os.path.join(model_dir, "config.json"), encoding="utf-8"))
86
+ self.height = int(cfg["H"])
87
+ det_path = det_model or os.path.join(model_dir, "det.onnx")
88
+ rec_path = rec_model or os.path.join(model_dir, "rec.onnx")
89
+ self.det = load_model(det_path, backend, threads, arena=True)
90
+ self.rec = load_model(rec_path, backend, threads, fix_height=self.height, arena=False)
91
+ with open(os.path.join(model_dir, "rec.classes.json"), encoding="utf-8") as fh:
92
+ self.decoder = CTCDecoder(json.load(fh), space_bias, case_conf=True, space_conf=True)
93
+ self.max_side, self.min_side, self.max_det_pixels = max_side, min_side, max_det_pixels
94
+ self.det_thresh, self.box_thresh, self.unclip_ratio = det_thresh, box_thresh, unclip_ratio
95
+ self.text_score, self.box_level, self.batch = text_score, box_level, batch
96
+ self.orient, self.orient_conf, self.orient_sample = orient, orient_conf, orient_sample
97
+ self.adaptive, self.adaptive_med_h, self.adaptive_max_side = adaptive, adaptive_med_h, adaptive_max_side
98
+ self._rgb = False
99
+
100
+ # ------------------------------------------------------------------ input
101
+ @staticmethod
102
+ def _load(image: Union[str, os.PathLike, np.ndarray, Any]) -> Tuple[np.ndarray, bool]:
103
+ """-> (H x W x 3 uint8, is_rgb)"""
104
+ if isinstance(image, (str, os.PathLike)):
105
+ img = cv2.imdecode(np.fromfile(str(image), np.uint8), cv2.IMREAD_COLOR)
106
+ if img is None:
107
+ raise ValueError(f"cannot read image {image!s}")
108
+ return img, False
109
+ if not isinstance(image, np.ndarray): # PIL image
110
+ return np.asarray(image.convert("RGB")), True
111
+ if image.ndim == 2:
112
+ return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR), False
113
+ if image.shape[2] == 4:
114
+ return cv2.cvtColor(image, cv2.COLOR_BGRA2BGR), False
115
+ return image, False
116
+
117
+ # -------------------------------------------------------------- detection
118
+ def _det_scale(self, h: int, w: int) -> float:
119
+ long_, short = max(h, w), min(h, w)
120
+ s = min(1.0, self.max_side / float(long_)) if self.max_side else 1.0
121
+ if self.min_side and short * s < self.min_side:
122
+ s = self.min_side / float(short)
123
+ if self.max_side and long_ * s > self.max_side * 1.5:
124
+ s = self.max_side * 1.5 / float(long_)
125
+ return s
126
+
127
+ def _detect_at(self, img: np.ndarray, scale: float) -> Tuple[List[np.ndarray], int, int]:
128
+ h, w = img.shape[:2]
129
+ nh, nw = det_input_size(h, w, scale, self.max_det_pixels)
130
+ prob = self.det(preprocess(img, nh, nw, self._rgb))[0, 0]
131
+ quads, _ = db_postprocess(prob, self.det_thresh, self.box_thresh, self.unclip_ratio)
132
+ out = []
133
+ sx, sy = w / float(nw), h / float(nh)
134
+ for q in quads:
135
+ q = q * np.array([sx, sy], np.float32)
136
+ q[:, 0] = np.clip(q[:, 0], 0, w - 1)
137
+ q[:, 1] = np.clip(q[:, 1], 0, h - 1)
138
+ if np.linalg.norm(q[0] - q[1]) > 3 and np.linalg.norm(q[0] - q[3]) > 3:
139
+ out.append(q)
140
+ return out, nh, nw
141
+
142
+ def _detect(self, img: np.ndarray) -> List[np.ndarray]:
143
+ h, w = img.shape[:2]
144
+ scale = self._det_scale(h, w)
145
+ out, nh, nw = self._detect_at(img, scale)
146
+ if self.adaptive and self.adaptive_med_h > 0 and len(out) >= 10 and self.max_side and \
147
+ self.adaptive_max_side > self.max_side and max(h, w) > self.max_side * 1.25:
148
+ s1 = nh / float(h)
149
+ hs = [min(float(np.linalg.norm(q[0] - q[1])), float(np.linalg.norm(q[0] - q[3]))) * s1 for q in out]
150
+ hs = [v for v in hs if v >= 3.0]
151
+ if len(hs) >= 10 and float(np.median(hs)) < self.adaptive_med_h:
152
+ s2 = min(1.0, self.adaptive_max_side / float(max(h, w)))
153
+ if s2 > scale * 1.15:
154
+ out, _, _ = self._detect_at(img, s2)
155
+ return out
156
+
157
+ # ------------------------------------------------------------ recognition
158
+ def _crops(self, img: np.ndarray, quads: Sequence[np.ndarray]) -> Tuple[List[np.ndarray], List[int]]:
159
+ crops, keep = [], []
160
+ for i, q in enumerate(quads):
161
+ cr = crop_line(img, q, self.height)
162
+ if cr is not None and cr.shape[1] >= 2:
163
+ crops.append(cr)
164
+ keep.append(i)
165
+ return crops, keep
166
+
167
+ def _read(self, crops: List[np.ndarray]) -> List[Tuple[str, float, float]]:
168
+ return recognize(self.rec, self.decoder, crops, batch=self.batch, rgb=self._rgb)
169
+
170
+ # ------------------------------------------------------------ orientation
171
+ @staticmethod
172
+ def _sideways(quads: Sequence[np.ndarray]) -> bool:
173
+ ratios = []
174
+ for q in quads:
175
+ w_q, h_q = np.linalg.norm(q[0] - q[1]), np.linalg.norm(q[0] - q[3])
176
+ if h_q > 0 and (w_q / h_q >= 1.5 or w_q / h_q <= 1 / 1.5):
177
+ ratios.append(w_q / h_q)
178
+ return len(ratios) >= 8 and sum(r < 1 for r in ratios) / len(ratios) > 0.5
179
+
180
+ def _sample(self, quads: Sequence[np.ndarray]) -> List[int]:
181
+ areas = [float(np.linalg.norm(q[0] - q[1]) * np.linalg.norm(q[0] - q[3])) for q in quads]
182
+ return sorted(range(len(quads)), key=lambda i: -areas[i])[: self.orient_sample]
183
+
184
+ def _flip_better(self, crops: List[np.ndarray]) -> bool:
185
+ """True when the crops read better turned by 180 degrees."""
186
+ if not crops:
187
+ return False
188
+ a = self._read(crops)
189
+ b = self._read([np.ascontiguousarray(c[::-1, ::-1]) for c in crops])
190
+ wins = sum(rb[1] > ra[1] + 0.05 for ra, rb in zip(a, b))
191
+ return wins > len(crops) / 2 and np.mean([r[1] for r in b]) > np.mean([r[1] for r in a]) + 0.05
192
+
193
+ # -------------------------------------------------------------------- run
194
+ def __call__(self, image: Union[str, os.PathLike, np.ndarray, Any]) -> List[Line]:
195
+ """The page's text lines in reading order."""
196
+ img, self._rgb = self._load(image)
197
+ h, w = img.shape[:2]
198
+ quads = self._detect(img)
199
+ rot = 0
200
+ if self.orient and self._sideways(quads): # text runs vertically: turn the page 90 or 270 degrees
201
+ crops, _ = self._crops(img, [quads[i] for i in self._sample(quads)])
202
+ rot = 90 if self._flip_better(crops) else 270
203
+ img = _rotate(img, rot)
204
+ h, w = img.shape[:2]
205
+ quads = self._detect(img)
206
+ crops, keep = self._crops(img, quads)
207
+ res = self._read(crops)
208
+ if self.orient and rot == 0 and res and float(np.median([r[1] for r in res])) < self.orient_conf:
209
+ idx = self._sample([quads[i] for i in keep])
210
+ if self._flip_better([crops[i] for i in idx]): # upside down
211
+ rot = 180
212
+ img = _rotate(img, 180)
213
+ quads = [_rotate_quad(q, 180, h, w) for q in quads]
214
+ crops, keep = self._crops(img, quads)
215
+ res = self._read(crops)
216
+ boxes = level_quads(quads, self.box_level) if self.box_level else quads
217
+ lines, upright = [], []
218
+ for k, i in enumerate(keep):
219
+ text, conf = res[k][0].strip(), res[k][1]
220
+ if not text or conf < self.text_score:
221
+ continue
222
+ q = boxes[i]
223
+ upright.append(q)
224
+ if rot: # boxes back in the input image's pixels
225
+ q = _rotate_quad(q, (360 - rot) % 360, h, w)
226
+ lines.append(Line(text, conf, [[float(x), float(y)] for x, y in q]))
227
+ return [lines[i] for i in sort_reading_order(upright)] # reading order on the upright page
228
+
229
+ def read_text(self, image: Union[str, os.PathLike, np.ndarray, Any]) -> str:
230
+ """The page's text, one line per detected line, in reading order."""
231
+ return "\n".join(ln.text for ln in self(image))
232
+
233
+ def read_line(self, crop: Union[str, os.PathLike, np.ndarray, Any]) -> Tuple[str, float]:
234
+ """One text-line crop (any size) -> (text, mean character confidence). No detection, no text_score filter."""
235
+ img, self._rgb = self._load(crop)
236
+ h, w = img.shape[:2]
237
+ line = cv2.resize(img, (max(1, int(round(w * self.height / float(h)))), self.height),
238
+ interpolation=cv2.INTER_AREA if h > self.height else cv2.INTER_CUBIC)
239
+ text, conf, _ = self._read([line])[0]
240
+ return text.strip(), conf
sumoocr/rec.py ADDED
@@ -0,0 +1,135 @@
1
+ """Text-line recognition: crop from the full-resolution page, resize to the recognizer height, greedy CTC decode."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from typing import List, Optional, Sequence, Tuple
6
+
7
+ import cv2
8
+ import numpy as np
9
+
10
+
11
+ def crop_line(img: np.ndarray, quad: np.ndarray, height: int) -> Optional[np.ndarray]:
12
+ """Perspective-rectify `quad` (tl, tr, br, bl in page pixels) to a `height`-px uint8 crop (same channel order as
13
+ img). Shrinking first resizes the region with INTER_AREA, then warps at the reduced scale. Tall crops
14
+ (h / w >= 1.5) are turned 90 degrees counter-clockwise."""
15
+ q = quad.astype(np.float32)
16
+ w_q = max(np.linalg.norm(q[0] - q[1]), np.linalg.norm(q[2] - q[3]))
17
+ h_q = max(np.linalg.norm(q[0] - q[3]), np.linalg.norm(q[1] - q[2]))
18
+ if w_q < 2 or h_q < 2:
19
+ return None
20
+ vertical = h_q / w_q >= 1.5
21
+ H, W = img.shape[:2]
22
+ x0 = max(0, int(math.floor(q[:, 0].min())) - 1)
23
+ y0 = max(0, int(math.floor(q[:, 1].min())) - 1)
24
+ x1 = min(W, int(math.ceil(q[:, 0].max())) + 2)
25
+ y1 = min(H, int(math.ceil(q[:, 1].max())) + 2)
26
+ if x1 - x0 < 2 or y1 - y0 < 2:
27
+ return None
28
+ region = img[y0:y1, x0:x1]
29
+ q = q - np.array([x0, y0], np.float32)
30
+ f = height / (w_q if vertical else h_q)
31
+ out_w, out_h = max(1, int(round(w_q * f))), max(1, int(round(h_q * f)))
32
+ if f < 0.75:
33
+ rw, rh = max(1, int(round(region.shape[1] * f))), max(1, int(round(region.shape[0] * f)))
34
+ region = cv2.resize(region, (rw, rh), interpolation=cv2.INTER_AREA)
35
+ q = q * np.array([rw / (x1 - x0), rh / (y1 - y0)], np.float32)
36
+ interp = cv2.INTER_LINEAR
37
+ else:
38
+ interp = cv2.INTER_CUBIC
39
+ dst = np.array([[0, 0], [out_w, 0], [out_w, out_h], [0, out_h]], np.float32)
40
+ crop = cv2.warpPerspective(region, cv2.getPerspectiveTransform(q, dst), (out_w, out_h), flags=interp,
41
+ borderMode=cv2.BORDER_REPLICATE)
42
+ if vertical:
43
+ crop = np.ascontiguousarray(np.rot90(crop))
44
+ if crop.shape[0] != height:
45
+ crop = cv2.resize(crop, (max(1, int(round(crop.shape[1] * height / crop.shape[0]))), height),
46
+ interpolation=cv2.INTER_LINEAR)
47
+ return crop
48
+
49
+
50
+ class CTCDecoder:
51
+ """Greedy CTC decoding. space_bias > 1 multiplies the space class's probability before the argmax (the
52
+ recognizer drops spaces more often than it invents them); confidences stay the unbiased probabilities.
53
+ case_conf: a letter's confidence also counts its other case (C / c, O / o, S / s look alike). space_conf: a space's
54
+ confidence also counts the blank (a biased space starts on a frame where it is at most 0.5)."""
55
+
56
+ def __init__(self, classes: Sequence[str], space_bias: float = 2.0, case_conf: bool = True,
57
+ space_conf: bool = True):
58
+ self.classes = list(classes)
59
+ self.lut = np.array(self.classes, dtype=object)
60
+ self.space_bias = float(space_bias)
61
+ self.space_idx = len(self.classes) - 1 if self.classes[-1] == " " else (
62
+ self.classes.index(" ") if " " in self.classes else -1)
63
+ pos = {ch: i for i, ch in enumerate(self.classes) if i}
64
+ self.case_pair = np.array([pos.get(ch.swapcase(), -1) if i and len(ch) == 1 and ch.swapcase() != ch else -1
65
+ for i, ch in enumerate(self.classes)], np.int64) if case_conf else None
66
+ self.space_conf = bool(space_conf) and self.space_idx > 0
67
+
68
+ def __call__(self, probs: np.ndarray, valid: Optional[Sequence[int]] = None) -> List[Tuple[str, float, float]]:
69
+ """probs: N x T x C softmax; valid[i] = time steps of sample i inside the real crop.
70
+ -> (text, mean character confidence, min character confidence) per sample."""
71
+ if self.space_bias != 1.0 and self.space_idx >= 0:
72
+ idx = probs.argmax(axis=2)
73
+ pmax = np.take_along_axis(probs, idx[:, :, None], axis=2)[:, :, 0]
74
+ sp = probs[:, :, self.space_idx]
75
+ pick_sp = (sp * self.space_bias) > pmax
76
+ idx = np.where(pick_sp, self.space_idx, idx)
77
+ pmax = np.where(pick_sp, sp, pmax)
78
+ else:
79
+ idx = probs.argmax(axis=2)
80
+ pmax = probs.max(axis=2)
81
+ if self.case_pair is not None:
82
+ pair = self.case_pair[idx]
83
+ pmax = np.minimum(1.0, pmax + np.where(
84
+ pair >= 0, np.take_along_axis(probs, np.maximum(pair, 0)[:, :, None], axis=2)[:, :, 0], 0.0))
85
+ if self.space_conf:
86
+ pmax = np.where(idx == self.space_idx, np.minimum(1.0, pmax + probs[:, :, 0]), pmax)
87
+ out = []
88
+ for i in range(probs.shape[0]):
89
+ t, p = idx[i], pmax[i]
90
+ if valid is not None:
91
+ t, p = t[: valid[i]], p[: valid[i]]
92
+ sel = np.ones(len(t), dtype=bool)
93
+ sel[1:] = t[1:] != t[:-1]
94
+ sel &= t != 0
95
+ if not sel.any():
96
+ out.append(("", 0.0, 0.0))
97
+ continue
98
+ ps = p[sel]
99
+ out.append(("".join(self.lut[t[sel]]), float(ps.mean()), float(ps.min())))
100
+ return out
101
+
102
+
103
+ def recognize(model, decoder: CTCDecoder, crops: List[np.ndarray], batch: int = 1, stride: int = 8,
104
+ rgb: bool = False) -> List[Tuple[str, float, float]]:
105
+ """Read crops (all the same height). Sorted by width and batched with mid-grey right padding to the batch's
106
+ widest crop (rounded up to `stride`); time steps in the padding are ignored. batch=1 reads every line alone (the
107
+ recognizer attends over the whole line, so padding moves its outputs a little)."""
108
+ n = len(crops)
109
+ res: List[Tuple[str, float, float]] = [("", 0.0, 0.0)] * n
110
+ if n == 0:
111
+ return res
112
+ order = sorted(range(n), key=lambda i: (crops[i].shape[1], i))
113
+ h = crops[0].shape[0]
114
+ src = (2, 1, 0) if rgb else (0, 1, 2)
115
+ for s in range(0, n, max(1, int(batch))):
116
+ ids = order[s:s + max(1, int(batch))]
117
+ wpad = int(math.ceil(max(crops[i].shape[1] for i in ids) / stride) * stride)
118
+ xb = np.zeros((len(ids), 3, h, wpad), np.float32)
119
+ valid = []
120
+ for k, i in enumerate(ids):
121
+ c = crops[i]
122
+ for ch in range(3):
123
+ xb[k, ch, :, :c.shape[1]] = c[:, :, src[ch]]
124
+ valid.append(int(math.ceil(c.shape[1] / stride)))
125
+ xb *= 2.0 / 255.0
126
+ xb -= 1.0
127
+ for k, i in enumerate(ids):
128
+ xb[k, :, :, crops[i].shape[1]:] = 0.0
129
+ probs = model(xb)
130
+ T = probs.shape[1]
131
+ scale = T / float(wpad)
132
+ valid = [min(T, int(math.ceil(v * stride * scale))) for v in valid]
133
+ for k, r in zip(ids, decoder(probs, valid)):
134
+ res[k] = r
135
+ return res
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: sumoocr
3
+ Version: 1.0.0
4
+ Summary: SumoOCR tiny: a 1M-parameter CPU OCR pipeline for business documents in Latin-script languages
5
+ Author: Docsumo
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://huggingface.co/docsumo/sumoOCR-tiny
8
+ Project-URL: Benchmark report, https://huggingface.co/docsumo/sumoOCR-tiny/blob/main/REPORT.md
9
+ Keywords: ocr,text-recognition,documents,invoices,receipts,onnx,cpu
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ License-File: NOTICE
24
+ Requires-Dist: numpy>=1.23
25
+ Requires-Dist: opencv-python-headless>=4.8
26
+ Requires-Dist: onnxruntime>=1.18
27
+ Provides-Extra: openvino
28
+ Requires-Dist: openvino>=2024.0; extra == "openvino"
29
+ Provides-Extra: pil
30
+ Requires-Dist: pillow; extra == "pil"
31
+ Provides-Extra: test
32
+ Requires-Dist: pytest; extra == "test"
33
+ Dynamic: description
34
+ Dynamic: description-content-type
35
+ Dynamic: license-file
36
+
37
+ # SumoOCR tiny
38
+
39
+ **A 1M-parameter, 1.8 MB OCR pipeline for business documents in Latin-script languages, running on one CPU core.**
40
+
41
+ ![SumoOCR tiny: accuracy against speed on CPU](https://huggingface.co/docsumo/sumoOCR-tiny/resolve/main/charts/accuracy_vs_speed.svg)
42
+
43
+ [Benchmark report](https://huggingface.co/docsumo/sumoOCR-tiny/blob/main/REPORT.md) · [SumoOCR](https://www.docsumo.com/blog/introducing-sumoocr) · [PP-OCRv6 tiny (base)](https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec) · [Citation](#citation)
44
+
45
+ ```bash
46
+ pip install sumoocr
47
+ ```
48
+
49
+ SumoOCR tiny is a text-line recognizer from Docsumo: Paddle's PP-OCRv6 tiny recognizer fine-tuned on public and business documents. Together with the PP-OCRv6 tiny text detector included in the package, it makes a complete OCR pipeline, and it is the first reader in SumoOCR, Docsumo's OCR engine.
50
+
51
+ | | SumoOCR tiny |
52
+ |---|---|
53
+ | **Size** | 1.04M parameters, 1.8 MB (0.43M detector + 0.61M recognizer) |
54
+ | **Speed** | 0.28 s a page (3.55 pages per second) on one CPU core (Mac mini M4), whole pipeline |
55
+ | **Accuracy** (word F1) | FUNSD 83.8 · SROIE 91.3 · XFUND 95.2 · OmniDocBench (English) 91.9 |
56
+ | **Languages** | English and European Latin-script languages (German, French, Spanish, Italian, Portuguese, Dutch, Polish, Czech, Hungarian, Turkish, Romanian, Nordic) |
57
+ | **Runtime** | ONNX Runtime (default) or OpenVINO, CPU only; no PyTorch or PaddlePaddle needed |
58
+ | **License** | Apache-2.0, the same as PP-OCRv6 |
59
+
60
+ Compared with the other engines tested, on the same pages and one CPU thread:
61
+
62
+ - **More accurate** than the same-size PP-OCRv6 tiny recognizer, PaddleOCR's own tiny setting, OCRia-nano-1 and Tesseract on all four benchmarks, and than Indra on SROIE, XFUND and OmniDocBench (FUNSD is a statistical tie).
63
+ - **Faster** than every engine tested: 1.65x faster than OCRia-nano-1, 1.72x than Indra 1.2.0, 3.3x than Tesseract and 8.7x than PaddleOCR's tiny setting.
64
+
65
+ Full numbers are in [Benchmarks](#benchmarks) and the [benchmark report](https://huggingface.co/docsumo/sumoOCR-tiny/blob/main/REPORT.md).
66
+
67
+ > SumoOCR tiny reads **text lines**. For whole pages it runs after a text detector (see [How it works](#how-it-works)); it does not produce layout blocks, tables or reading order.
68
+
69
+ Need checkbox and signature detection, more complex documents, or higher accuracy? Try [Docsumo](https://www.docsumo.com).
70
+
71
+ ![SumoOCR tiny: word F1 by benchmark](https://huggingface.co/docsumo/sumoOCR-tiny/resolve/main/charts/word_f1_by_benchmark.svg)
72
+
73
+ ## Quickstart
74
+
75
+ ```bash
76
+ pip install sumoocr # models included (1.8 MB); `pip install "sumoocr[openvino]"` for OpenVINO
77
+ sumoocr invoice.png # text, one line per line
78
+ sumoocr invoice.png --format json # lines with boxes and confidences
79
+ ```
80
+
81
+ ### Python
82
+
83
+ ```python
84
+ from sumoocr import SumoOCR
85
+
86
+ ocr = SumoOCR() # backend="openvino" for OpenVINO; threads=1 for one core
87
+ for line in ocr("invoice.png"): # a path, a BGR numpy array (cv2.imread) or a PIL image
88
+ print(line.text, round(line.conf, 3), line.box)
89
+
90
+ print(ocr.read_text("invoice.png")) # the page as text, in reading order
91
+ text, conf = ocr.read_line("line.png") # one text-line crop, no detection
92
+ ```
93
+
94
+ ### ONNX only
95
+
96
+ The two models are plain ONNX files in [`sumoocr/models/`](https://huggingface.co/docsumo/sumoOCR-tiny/tree/main/sumoocr/models): read a line crop without the package:
97
+
98
+ ```python
99
+ import json
100
+
101
+ import cv2
102
+ import numpy as np
103
+ import onnxruntime as ort
104
+
105
+ sess = ort.InferenceSession("sumoocr/models/rec.onnx")
106
+ chars = json.load(open("sumoocr/models/rec.classes.json")) # index 0 = CTC blank
107
+
108
+ def read_line(bgr):
109
+ h, w = bgr.shape[:2]
110
+ x = cv2.resize(bgr, (max(4, round(w * 40 / h)), 40)).astype(np.float32)
111
+ x = ((x / 255.0 - 0.5) / 0.5).transpose(2, 0, 1)[None] # 1 x 3 x 40 x W, BGR
112
+ probs = sess.run(None, {"x": x})[0][0] # W/4 x 758
113
+ ids = probs.argmax(1)
114
+ keep = (ids != 0) & np.r_[True, ids[1:] != ids[:-1]] # greedy CTC
115
+ return "".join(chars[i] for i in ids[keep])
116
+
117
+ print(read_line(cv2.imread("line.png")))
118
+ ```
119
+
120
+ ### Input
121
+
122
+ - A page image (PNG, JPEG, TIFF, BMP, WebP; any size): the detector caps its long side at 1,280 px and automatically steps up to 2,400 px on dense small print such as newspapers (`adaptive=True`).
123
+ - Printed text in Latin script; pages turned by 90°, 180° or 270° are detected and turned back.
124
+ - Or one text-line crop (`read_line`).
125
+
126
+ ### Output
127
+
128
+ | Field | What it is |
129
+ |---|---|
130
+ | `text` | the line's text |
131
+ | `conf` | mean character confidence, 0-1 (lines below 0.85 are dropped: `SumoOCR(text_score=...)`) |
132
+ | `box` | 4 [x, y] points, clockwise from the top-left, in pixels of the input image |
133
+
134
+ Lines come in reading order: top to bottom, left to right within a row.
135
+
136
+ ## How it works
137
+
138
+ | Model | File | Role | Parameters |
139
+ |---|---|---|---|
140
+ | Text detector (PP-OCRv6 tiny, INT8 QDQ) | `sumoocr/models/det.onnx` | finds the text lines on the page | 0.43M |
141
+ | **SumoOCR tiny** (INT8 QDQ) | `sumoocr/models/rec.onnx` | reads each line: 40 px high, CTC over 758 characters (`rec.classes.json`) | 0.61M |
142
+ | **Total** | | | **1.04M** |
143
+
144
+ The page is scaled for the detector, its text boxes are cut out at full resolution and read one by one; a page whose lines read badly is tried upside down, and a page whose boxes stand on end is turned.
145
+
146
+ ## Benchmarks
147
+
148
+ Word F1 (x 100) on whole pages, every engine on the same page images on CPU with one thread; bold = best in the column. Speed (pages/s) was measured on a Mac mini M4, 1 CPU core. Details, confidence intervals and the method: [benchmark report](https://huggingface.co/docsumo/sumoOCR-tiny/blob/main/REPORT.md).
149
+
150
+ | System (CPU) | FUNSD | SROIE | XFUND | OmniDocBench (EN) | Business Docs | pages/s | License |
151
+ |---|---|---|---|---|---|---|---|
152
+ | **SumoOCR tiny** | 83.8 | 91.3 | 95.2 | **91.9** | 98.9 | **3.55** | Apache-2.0 |
153
+ | SumoOCR \* | **85.6** | **94.5** | **96.0** | 90.9 | **99.0** | 0.91 | not released |
154
+ | Paddle tiny rec (our pipeline) | 79.0 | 89.3 | 94.5 | 90.4 | 97.5 | 1.31 | Apache-2.0 |
155
+ | PaddleOCR tiny ¹ | 77.0 | 86.5 | 94.5 | 91.0 | 97.1 | 0.41 | Apache-2.0 |
156
+ | OCRia-nano-1 | 80.9 | 87.0 | 92.7 | 82.2 | 98.0 | 2.15 | OCRia-nano-1 licence |
157
+ | Indra 1.2.0 | 83.4 | 89.2 | 93.6 | 90.0 | 98.2 | 2.07 | modified OpenRAIL-M |
158
+ | Tesseract 5 | 61.9 | 75.0 | 90.7 | 90.2 | 92.3 | 1.07 | Apache-2.0 |
159
+
160
+ FUNSD: 50 scanned forms. SROIE: 347 receipts. XFUND: 250 forms in German, Spanish, French, Italian and Portuguese. OmniDocBench: 755 English pages (papers, books, slides, magazines, newspapers). Business Docs: 41 public and synthetic business documents (invoices, statements, forms and US federal pages in 16 languages). "Paddle tiny rec (our pipeline)" is the PP-OCRv6 tiny recognizer SumoOCR tiny was fine-tuned from, run in the FP32 OpenVINO pipeline (see [Systems compared](https://huggingface.co/docsumo/sumoOCR-tiny/blob/main/REPORT.md#systems-compared)), not the shipped INT8 ONNX Runtime build with adaptive detection: its gap to SumoOCR tiny is the fine-tune plus those pipeline differences. The [line recognition table](#line-recognition-only) compares the two recognizers on the same crops. ¹ PaddleOCR 3.7 itself (Paddle's own package), its tiny setting: PP-OCRv6 tiny detector and recognizer. Timed natively, outside the container.
161
+
162
+ \* SumoOCR is Docsumo's full OCR engine (not released). It also supports checkboxes, signatures and more complex documents.
163
+
164
+ ### Line recognition only
165
+
166
+ The same ground-truth line crops for every recognizer (no detector): character error rate ↓, case and spaces ignored.
167
+
168
+ | Recognizer | SROIE CER ↓ | XFUND CER ↓ | FUNSD CER ↓ |
169
+ |---|---|---|---|
170
+ | SumoOCR tiny | 2.93 % | **1.77 %** | **4.26 %** |
171
+ | PP-OCRv6 tiny rec | **2.62 %** | 1.96 % | 5.38 % |
172
+ | Tesseract 5 (`--psm 7`) | 8.58 % | 9.86 % | 12.92 % |
173
+
174
+ ## Speed
175
+
176
+ **Hardware: Mac mini M4, 1 CPU core.** One process in a Docker container limited to 1 vCPU and 8 GB (`--cpus=1 --memory=8g`, Linux arm64), every engine on the same 100 pages (20 from each benchmark), taking turns page by page; whole pages, detection included.
177
+
178
+ | Configuration | mean word F1 (4 benchmarks) | pages/s | ms per page, 1 core (mean / P90) | License |
179
+ |---|---|---|---|---|
180
+ | **SumoOCR tiny** | 90.6 | 3.55 | 281 / 546 | Apache-2.0 |
181
+ | OCRia-nano-1 | 85.7 | 2.15 | 464 / 734 | OCRia-nano-1 licence |
182
+ | Indra 1.2.0 | 89.0 | 2.07 | 484 / 857 | modified OpenRAIL-M |
183
+ | Paddle tiny rec (our pipeline) | 88.3 | 1.31 | 764 / 1,456 | Apache-2.0 |
184
+ | Tesseract 5 | 79.4 | 1.07 | 931 / 2,074 | Apache-2.0 |
185
+ | SumoOCR | 91.7 | 0.91 | 1,103 / 1,976 | not released |
186
+ | PaddleOCR 3.7, tiny (PP-OCRv6 tiny det + rec) ¹ | 87.3 | 0.41 | 2,444 / 4,527 | Apache-2.0 |
187
+
188
+ ¹ PaddleOCR was not run in the 1-vCPU container: it was timed natively on the same host, one thread (`cpu_threads=1`), 100 pages (8.7x the time of SumoOCR tiny run the same way on the same pages). Paddle's CPU kernels on ARM are much slower than its x86 path.
189
+
190
+ ## Training
191
+
192
+ Fine-tuned from the PP-OCRv6 tiny recognizer (its output layer mapped to 758 Latin characters) on text-line crops (line heights 32-48 px) from business and public documents across diverse fonts and scan conditions, including:
193
+
194
+ - **Docsumo's internal benchmark documents** (their training split).
195
+ - **Public government documents**: US federal publications (IRS, Federal Register, GovInfo, Census Bureau, CFPB, GSA, Federal Reserve) and EU documents from EUR-Lex.
196
+ - **Synthetic rendered text lines**, with sentences from Tatoeba.
197
+
198
+ Only the model weights are released: no training document, crop or text is part of this repository. None of the four public benchmarks above (FUNSD, SROIE, XFUND, OmniDocBench) was used; 3 of the 41 Business Docs pages are public federal PDF pages that are also in the training set (see the [benchmark report](https://huggingface.co/docsumo/sumoOCR-tiny/blob/main/REPORT.md)).
199
+
200
+ Attribution. EUR-Lex documents: source EUR-Lex, © European Union, https://eur-lex.europa.eu. Synthetic sentences: Tatoeba (https://tatoeba.org), CC BY 2.0 FR.
201
+
202
+ ## Limitations
203
+
204
+ - **Latin script only.** The 758 characters cover English and European Latin-script languages; Cyrillic, Greek, Arabic, Hebrew, Chinese, Japanese, Korean and Indic scripts are not recognized.
205
+ - **Printed text.** Handwriting was not a training target and was not measured here.
206
+ - **Lines, not documents.** It returns text lines with boxes and confidences: no layout blocks, tables, reading order or key-value structure (the benchmarks put every engine's lines in reading order with one shared routine).
207
+ - **Receipts and low-resolution scans are its weakest pages.** SROIE 91.3 and FUNSD 83.8 word F1, 3.1 and 1.8 points behind SumoOCR. On receipt line crops the base PP-OCRv6 tiny reads slightly better (2.62 % vs 2.93 % character errors).
208
+ - **Post-training INT8 quantization.** Both ONNX models use synthetic-calibrated INT8 QDQ quantization (keeping sensitive layers in FP32) for fast CPU inference at 1.8 MB total size; word F1 is within 0.2 points of FP32 on every benchmark (0.1 on the four-benchmark mean).
209
+
210
+ ## Files
211
+
212
+ | File | What |
213
+ |---|---|
214
+ | `sumoocr/models/det.onnx` | text detector (PP-OCRv6 tiny, INT8 QDQ, opset-20 Gelu), 0.7 MB |
215
+ | `sumoocr/models/rec.onnx` | SumoOCR tiny recognizer (INT8 QDQ, opset-20 Gelu), 1.1 MB |
216
+ | `sumoocr/models/rec.classes.json` | the 758 output classes (0 = CTC blank, last = space) |
217
+ | `sumoocr/models/config.json` | input height and pre-processing of both models |
218
+ | `sumoocr/` | the Python package (`pip install sumoocr`) |
219
+ | `REPORT.md`, `charts/` | benchmark report |
220
+ | `LICENSE`, `NOTICE` | Apache-2.0; PaddleOCR attribution |
221
+
222
+ ## License
223
+
224
+ Apache-2.0, the same licence as its base model, PP-OCRv6 tiny (PaddlePaddle); see `NOTICE`. The text detector is derived from the PP-OCRv6 tiny detector (Apache-2.0). ONNX Runtime (MIT) or OpenVINO (Apache-2.0) run the models.
225
+
226
+ ## Citation
227
+
228
+ ```bibtex
229
+ @misc{sumoocrtiny2026,
230
+ title = {SumoOCR tiny: a 0.6M-parameter text-line recognizer for business documents},
231
+ author = {Docsumo},
232
+ year = {2026},
233
+ url = {https://huggingface.co/docsumo/sumoOCR-tiny}
234
+ }
235
+ ```
236
+
237
+ ---
238
+
239
+ Need checkbox and signature detection, more complex documents, or higher accuracy? Try [Docsumo](https://www.docsumo.com).
@@ -0,0 +1,17 @@
1
+ sumoocr/__init__.py,sha256=vBLEKngwnVpvUVbxKWG9wrcDKOLP0eTgXtXiy6V3fMI,303
2
+ sumoocr/backend.py,sha256=5YVZ0xMewIBc0PKIVdSGOKFHQiVjmZKKqaXrJJniw5E,2739
3
+ sumoocr/cli.py,sha256=PUf-eDuVNWTCEEq8r_Ak2f0VoHZA5sMXDOCGA0JwUok,1496
4
+ sumoocr/det.py,sha256=UZafwiYGlNJ5C40Kyrl8oKsGnZEL88Pcild-dzdV5KQ,6666
5
+ sumoocr/ocr.py,sha256=Fkz7pVJqCYVkW017KgNca1xsGGk6pBAVfxRxY4NGWKU,11962
6
+ sumoocr/rec.py,sha256=otBWOmyUAkUtFs1vAAHtrqNjpuSPUVGT02tqA5ZrvP0,6691
7
+ sumoocr/models/config.json,sha256=E71zFEVEB-cvknqdH74s6iCx0rkgh7up5kGd9reuzuw,340
8
+ sumoocr/models/det.onnx,sha256=eL7SRZUoLLiX4c1R4J-2ILhaD4p1Udgc1kDEnpM7-G4,752617
9
+ sumoocr/models/rec.classes.json,sha256=8FNcVVuhL-pGIOvK9vpE2E94cDItsoZF1Zv9UpLIrqo,4691
10
+ sumoocr/models/rec.onnx,sha256=jbNaYRP6tnZRzaTxRomcqPxKBHXZXzJLA5ZOxlGdLS0,1148133
11
+ sumoocr-1.0.0.dist-info/licenses/LICENSE,sha256=oDZKE4yAgDlHCTULbyKSgs_TnJbFGlC2Qt_mKYOgzyU,11338
12
+ sumoocr-1.0.0.dist-info/licenses/NOTICE,sha256=c6pnpv1_cTxIYPTxrIviyHU2BkuEcjBRVv3ojw7ErSA,651
13
+ sumoocr-1.0.0.dist-info/METADATA,sha256=lCTMmScpG__NNMRIiYAXFopGNrP31c0YEtSuAUCAqAE,13718
14
+ sumoocr-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ sumoocr-1.0.0.dist-info/entry_points.txt,sha256=wuHJyJSRv-OkwD9fjNoZpp0R_k391v-i-DAyhQyR3fc,45
16
+ sumoocr-1.0.0.dist-info/top_level.txt,sha256=2Y10P76nWU3DpeJFreFchVVtL5kGaQUzs_8z_AiKOxw,8
17
+ sumoocr-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sumoocr = sumoocr.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Docsumo
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,10 @@
1
+ SumoOCR tiny
2
+ Copyright 2026 Docsumo
3
+
4
+ This product includes models from PaddleOCR (https://github.com/PaddlePaddle/PaddleOCR),
5
+ Copyright PaddlePaddle Authors, licensed under the Apache License, Version 2.0:
6
+ - sumoocr/models/det.onnx: derived from the PP-OCRv6 tiny text detection model (converted to
7
+ ONNX opset 20 with fused Gelu(tanh) and post-training INT8 QDQ quantization).
8
+ - sumoocr/models/rec.onnx: SumoOCR tiny, fine-tuned by Docsumo from the PP-OCRv6 tiny text
9
+ recognition model (its output layer reduced to 758 Latin-script characters, converted to ONNX
10
+ opset 20 with fused Gelu(tanh) and post-training INT8 QDQ quantization).
@@ -0,0 +1 @@
1
+ sumoocr