glyphly 0.1.0a1__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.
glyphly/__about__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0a1"
glyphly/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """glyphly: OCR for Python with nothing to install but the package."""
2
+
3
+ from glyphly.__about__ import __version__
4
+ from glyphly.engine import Reader, read
5
+ from glyphly.models import ModelError
6
+ from glyphly.types import Line, Page, Word
7
+
8
+ __all__ = ["Line", "ModelError", "Page", "Reader", "Word", "__version__", "read"]
glyphly/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow `python -m glyphly`."""
2
+
3
+ from glyphly.cli import main
4
+
5
+ raise SystemExit(main())
glyphly/cli.py ADDED
@@ -0,0 +1,62 @@
1
+ """Command line: ``glyphly read scan.png``, ``glyphly download``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from dataclasses import asdict
10
+
11
+ from glyphly.__about__ import __version__
12
+
13
+
14
+ def _build_parser() -> argparse.ArgumentParser:
15
+ parser = argparse.ArgumentParser(prog="glyphly", description="OCR with nothing to install.")
16
+ parser.add_argument("--version", action="version", version=f"glyphly {__version__}")
17
+ sub = parser.add_subparsers(dest="command", required=True)
18
+ read = sub.add_parser("read", help="read the text in one or more images")
19
+ read.add_argument("images", nargs="+")
20
+ read.add_argument("--json", action="store_true", help="lines, words, boxes and confidences")
21
+ dl = sub.add_parser("download", help="fetch the model files now (for offline use later)")
22
+ dl.add_argument("--all", action="store_true", help="also every script model (about 70 MB)")
23
+ read.add_argument("--lang", default="auto",
24
+ help="auto (default) or language codes, e.g. ru or hi,en") # fmt: skip
25
+ return parser
26
+
27
+
28
+ def main(argv: Sequence[str] | None = None) -> int:
29
+ args = _build_parser().parse_args(argv)
30
+ for stream in (sys.stdout, sys.stderr):
31
+ reconfigure = getattr(stream, "reconfigure", None)
32
+ if reconfigure is not None:
33
+ reconfigure(encoding="utf-8")
34
+ from glyphly import models
35
+
36
+ try:
37
+ if args.command == "download":
38
+ for path in models.download_all(scripts=args.all):
39
+ print(f"ok: {path}")
40
+ return 0
41
+ from glyphly.engine import Reader
42
+
43
+ lang = args.lang if args.lang == "auto" else args.lang.split(",")
44
+ reader = Reader(lang=lang)
45
+ for name in args.images:
46
+ page = reader.read(name)
47
+ if args.json:
48
+ print(json.dumps({"image": name, **asdict(page)}, ensure_ascii=False))
49
+ else:
50
+ if len(args.images) > 1:
51
+ print(f"==> {name} <==")
52
+ print(page.text)
53
+ except models.ModelError as exc:
54
+ print(f"error: {exc}", file=sys.stderr)
55
+ return 2
56
+ except OSError as exc:
57
+ print(f"error: {exc}", file=sys.stderr)
58
+ return 1
59
+ return 0
60
+
61
+
62
+ __all__ = ["main"]
glyphly/detect.py ADDED
@@ -0,0 +1,233 @@
1
+ """Find text lines: a segmentation network marks text pixels, numpy turns them into boxes.
2
+
3
+ The network (DB, "differentiable binarisation") outputs, for every pixel, the probability
4
+ that it lies inside a text line, with lines shrunk a little so neighbours stay apart.
5
+ Post-processing (written here in numpy, no OpenCV):
6
+
7
+ 1. threshold the map and label connected regions (runs of pixels row by row, merged with
8
+ a union-find);
9
+ 2. drop regions whose mean probability is low (likely not text) or that are tiny;
10
+ 3. measure each region's direction from its pixel moments, so tilted lines (skewed
11
+ scans, phone photos) get a rotated box instead of an upright one that would also cut
12
+ through the neighbouring lines;
13
+ 4. grow each box back by the amount the network shrank it ("unclip").
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from dataclasses import dataclass, field
20
+ from typing import TYPE_CHECKING
21
+
22
+ import numpy as np
23
+
24
+ if TYPE_CHECKING:
25
+ import onnxruntime as ort
26
+
27
+ # ImageNet statistics, applied to BGR input as in the detector's training.
28
+ _MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
29
+ _STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
30
+
31
+ THRESH = 0.3 # pixel probability above which a pixel is "text"
32
+ BOX_THRESH = 0.5 # minimum mean probability of a region to keep it
33
+ UNCLIP_RATIO = 1.6 # how far boxes are grown back (DB's shrink ratio, inverted)
34
+ MIN_SIDE = 3 # regions thinner than this (in map pixels) are noise
35
+ MAX_SIDE = 2048 # longest side fed to the network (larger pages are scaled down)
36
+ STRAIGHT = math.radians(0.5) # below this tilt a line is cut out upright (no resampling)
37
+ ELONGATED = 2.0 # long axis at least this many times the short one to trust a direction
38
+
39
+
40
+ @dataclass
41
+ class Region:
42
+ """A connected text region, accumulated run by run."""
43
+
44
+ x0: int
45
+ y0: int
46
+ x1: int # inclusive
47
+ y1: int # inclusive
48
+ pixels: int = 0
49
+ prob_sum: float = 0.0
50
+ ends: list[tuple[int, int, int]] = field(default_factory=list) # (y, start, end)
51
+ # pixel moments for the direction: sums of x, y, x^2, y^2, xy
52
+ sx: float = 0.0
53
+ sy: float = 0.0
54
+ sxx: float = 0.0
55
+ syy: float = 0.0
56
+ sxy: float = 0.0
57
+
58
+ @property
59
+ def score(self) -> float:
60
+ return self.prob_sum / self.pixels if self.pixels else 0.0
61
+
62
+ def add(self, y: int, start: int, end: int, prob: float) -> None:
63
+ n = end - start + 1
64
+ self.x0, self.x1 = min(self.x0, start), max(self.x1, end)
65
+ self.y0, self.y1 = min(self.y0, y), max(self.y1, y)
66
+ self.pixels += n
67
+ self.prob_sum += prob
68
+ self.ends.append((y, start, end))
69
+ sum_x = n * (start + end) / 2
70
+ # sum of x^2 over start..end
71
+ sum_xx = (end * (end + 1) * (2 * end + 1) - (start - 1) * start * (2 * start - 1)) / 6
72
+ self.sx += sum_x
73
+ self.sy += n * y
74
+ self.sxx += sum_xx
75
+ self.syy += n * y * y
76
+ self.sxy += y * sum_x
77
+
78
+ def angle(self) -> float:
79
+ """Direction of the region's long axis, in radians (0 = horizontal).
80
+
81
+ 0 when the region has no clear long axis (a single character, a dot): its
82
+ direction would be noise.
83
+ """
84
+ n = self.pixels
85
+ mx, my = self.sx / n, self.sy / n
86
+ cxx = self.sxx / n - mx * mx
87
+ cyy = self.syy / n - my * my
88
+ cxy = self.sxy / n - mx * my
89
+ half_diff = math.hypot((cxx - cyy) / 2, cxy)
90
+ long_var, short_var = (cxx + cyy) / 2 + half_diff, (cxx + cyy) / 2 - half_diff
91
+ if long_var < ELONGATED**2 * max(short_var, 1e-9):
92
+ return 0.0
93
+ return 0.5 * math.atan2(2 * cxy, cxx - cyy)
94
+
95
+
96
+ @dataclass
97
+ class TextBox:
98
+ """A (possibly rotated) text-line rectangle in image pixels."""
99
+
100
+ cx: float
101
+ cy: float
102
+ length: float # along the line
103
+ thickness: float # across the line
104
+ angle: float # radians, 0 = horizontal
105
+
106
+ def corners(self) -> list[tuple[float, float]]:
107
+ c, s = math.cos(self.angle), math.sin(self.angle)
108
+ hl, ht = self.length / 2, self.thickness / 2
109
+ return [
110
+ (self.cx + u * c - v * s, self.cy + u * s + v * c)
111
+ for u, v in ((-hl, -ht), (hl, -ht), (hl, ht), (-hl, ht))
112
+ ]
113
+
114
+ @property
115
+ def bounds(self) -> tuple[float, float, float, float]:
116
+ pts = self.corners()
117
+ xs, ys = [p[0] for p in pts], [p[1] for p in pts]
118
+ return min(xs), min(ys), max(xs), max(ys)
119
+
120
+ def point(self, u: float) -> tuple[float, float]:
121
+ """Image position of the point ``u`` pixels from the line's start, on its axis."""
122
+ c, s = math.cos(self.angle), math.sin(self.angle)
123
+ d = u - self.length / 2
124
+ return self.cx + d * c, self.cy + d * s
125
+
126
+
127
+ def _row_runs(row: np.ndarray) -> list[tuple[int, int]]:
128
+ """(start, end inclusive) of each run of True values in a 1-D boolean array."""
129
+ padded = np.concatenate(([False], row, [False]))
130
+ edges = np.flatnonzero(padded[1:] != padded[:-1])
131
+ return list(zip(edges[0::2].tolist(), (edges[1::2] - 1).tolist(), strict=True))
132
+
133
+
134
+ def regions(mask: np.ndarray, prob: np.ndarray) -> list[Region]:
135
+ """Connected regions (8-connectivity) of ``mask``."""
136
+ parent: list[int] = []
137
+
138
+ def find(i: int) -> int:
139
+ while parent[i] != i:
140
+ parent[i] = parent[parent[i]]
141
+ i = parent[i]
142
+ return i
143
+
144
+ runs: list[tuple[int, int, int]] = [] # (y, start, end)
145
+ prev: list[int] = [] # run ids on the previous row
146
+ for y in range(mask.shape[0]):
147
+ current: list[int] = []
148
+ j = 0
149
+ for start, end in _row_runs(mask[y]):
150
+ rid = len(runs)
151
+ runs.append((y, start, end))
152
+ parent.append(rid)
153
+ # previous-row runs that touch this one (diagonals included)
154
+ while j < len(prev) and runs[prev[j]][2] < start - 1:
155
+ j += 1
156
+ k = j
157
+ while k < len(prev) and runs[prev[k]][1] <= end + 1:
158
+ a, b = find(rid), find(prev[k])
159
+ if a != b:
160
+ parent[max(a, b)] = min(a, b)
161
+ k += 1
162
+ current.append(rid)
163
+ prev = current
164
+
165
+ out: dict[int, Region] = {}
166
+ for rid, (y, start, end) in enumerate(runs):
167
+ root = find(rid)
168
+ r = out.get(root)
169
+ if r is None:
170
+ r = out[root] = Region(start, y, end, y)
171
+ r.add(y, start, end, float(prob[y, start : end + 1].sum()))
172
+ return list(out.values())
173
+
174
+
175
+ def unclip(x0: float, y0: float, x1: float, y1: float, ratio: float = UNCLIP_RATIO) -> tuple:
176
+ """Grow a box by DB's offset: area * ratio / perimeter on every side."""
177
+ w, h = x1 - x0, y1 - y0
178
+ d = w * h * ratio / (2 * (w + h)) if w + h > 0 else 0.0
179
+ return x0 - d, y0 - d, x1 + d, y1 + d
180
+
181
+
182
+ def text_box(r: Region, sx: float, sy: float) -> TextBox:
183
+ """The region's rectangle along its own direction, grown back, in image pixels."""
184
+ a = r.angle()
185
+ if abs(a) < STRAIGHT:
186
+ a = 0.0
187
+ c, s = math.cos(a), math.sin(a)
188
+ # extent along (u) and across (v) the direction, from the run end points (map pixels,
189
+ # pixel centres +- 0.5)
190
+ us, vs = [], []
191
+ for y, start, end in r.ends:
192
+ for x in (start - 0.5, end + 0.5):
193
+ for yy in (y - 0.5, y + 0.5):
194
+ us.append(x * c + yy * s)
195
+ vs.append(-x * s + yy * c)
196
+ u0, u1, v0, v1 = min(us), max(us), min(vs), max(vs)
197
+ u0, v0, u1, v1 = unclip(u0, v0, u1, v1)
198
+ cu, cv = (u0 + u1) / 2, (v0 + v1) / 2
199
+ cx, cy = cu * c - cv * s, cu * s + cv * c
200
+ # map -> image pixels (the two axes may be scaled slightly differently)
201
+ length = math.hypot((u1 - u0) * c * sx, (u1 - u0) * s * sy)
202
+ thickness = math.hypot((v1 - v0) * s * sx, (v1 - v0) * c * sy)
203
+ angle = math.atan2(s * sy, c * sx)
204
+ return TextBox(cx * sx, cy * sy, length, thickness, angle)
205
+
206
+
207
+ def _input(rgb: np.ndarray, max_side: int) -> tuple[np.ndarray, float, float]:
208
+ from PIL import Image
209
+
210
+ h, w = rgb.shape[:2]
211
+ scale = min(1.0, max_side / max(h, w))
212
+ nh = max(32, round(h * scale / 32) * 32)
213
+ nw = max(32, round(w * scale / 32) * 32)
214
+ img = rgb if (nh, nw) == (h, w) else np.asarray(Image.fromarray(rgb).resize((nw, nh)))
215
+ x = (img[:, :, ::-1].astype(np.float32) / 255.0 - _MEAN) / _STD # RGB -> BGR
216
+ return x.transpose(2, 0, 1)[None], w / nw, h / nh
217
+
218
+
219
+ def detect(
220
+ session: ort.InferenceSession, rgb: np.ndarray, *, max_side: int = MAX_SIDE
221
+ ) -> list[TextBox]:
222
+ """Text-line boxes in pixels of ``rgb`` (H x W x 3 uint8)."""
223
+ x, sx, sy = _input(rgb, max_side)
224
+ prob = np.asarray(session.run(None, {session.get_inputs()[0].name: x})[0])[0, 0]
225
+ boxes = []
226
+ for r in regions(prob > THRESH, prob):
227
+ if min(r.x1 - r.x0, r.y1 - r.y0) + 1 < MIN_SIDE or r.score < BOX_THRESH:
228
+ continue
229
+ boxes.append(text_box(r, sx, sy))
230
+ return boxes
231
+
232
+
233
+ __all__ = ["Region", "TextBox", "detect", "regions", "text_box", "unclip"]