python-doctr 1.0.1__py3-none-any.whl → 1.2.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.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +669 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +14 -3
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +121 -37
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +9 -7
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +129 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +5 -4
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +10 -8
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +104 -21
- doctr/datasets/vocabs.py +320 -148
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +3 -0
- doctr/io/elements.py +381 -271
- doctr/io/exporters.py +1915 -0
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -7
- doctr/io/image/pytorch.py +13 -5
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +3 -0
- doctr/models/_utils.py +206 -13
- doctr/models/builder.py +590 -137
- doctr/models/classification/__init__.py +3 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +34 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +14 -2
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +32 -18
- doctr/models/detection/differentiable_binarization/base.py +23 -9
- doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
- doctr/models/detection/fast/base.py +22 -6
- doctr/models/detection/fast/pytorch.py +24 -11
- doctr/models/detection/linknet/base.py +22 -6
- doctr/models/detection/linknet/pytorch.py +10 -3
- doctr/models/detection/predictor/pytorch.py +43 -2
- doctr/models/detection/zoo.py +6 -2
- doctr/models/factory/hub.py +59 -41
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +23 -1
- doctr/models/kie_predictor/pytorch.py +87 -15
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +895 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +114 -0
- doctr/models/layout/zoo.py +94 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +415 -17
- doctr/models/predictor/pytorch.py +109 -12
- doctr/models/preprocessor/pytorch.py +82 -25
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +1127 -0
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +40 -16
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +84 -22
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +126 -25
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +68 -12
- doctr/models/recognition/sar/pytorch.py +21 -7
- doctr/models/recognition/utils.py +80 -50
- doctr/models/recognition/viptr/pytorch.py +38 -14
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +11 -7
- doctr/models/recognition/zoo.py +36 -9
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +231 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +675 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
- doctr/models/table_structure/zoo.py +87 -0
- doctr/models/utils/pytorch.py +381 -25
- doctr/models/zoo.py +141 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +261 -82
- doctr/transforms/modules/pytorch.py +396 -76
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +24 -11
- doctr/utils/fonts.py +64 -17
- doctr/utils/geometry.py +167 -28
- doctr/utils/metrics.py +481 -19
- doctr/utils/multithreading.py +127 -4
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +73 -10
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
- python_doctr-1.2.0.dist-info/RECORD +191 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/utils/reconstitution.py
CHANGED
|
@@ -3,206 +3,770 @@
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
import logging
|
|
6
|
-
|
|
6
|
+
import math
|
|
7
|
+
from functools import lru_cache
|
|
8
|
+
from typing import Any, NamedTuple
|
|
7
9
|
|
|
8
10
|
import numpy as np
|
|
9
11
|
from anyascii import anyascii
|
|
10
|
-
from PIL import Image, ImageDraw
|
|
12
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
11
13
|
|
|
12
14
|
from .fonts import get_font
|
|
13
15
|
|
|
14
16
|
__all__ = ["synthesize_page", "synthesize_kie_page"]
|
|
15
17
|
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
16
19
|
|
|
17
|
-
# Global variable to avoid multiple warnings
|
|
18
|
-
ROTATION_WARNING = False
|
|
19
20
|
|
|
21
|
+
class _Word(NamedTuple):
|
|
22
|
+
"""A word to render, with its text, position, size and rotation."""
|
|
20
23
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
value: str
|
|
25
|
+
x: int
|
|
26
|
+
y: int
|
|
27
|
+
width: int
|
|
28
|
+
height: int
|
|
29
|
+
angle: float # degrees, counter-clockwise
|
|
26
30
|
|
|
27
31
|
|
|
28
|
-
|
|
32
|
+
@lru_cache(maxsize=256)
|
|
33
|
+
def _cached_font(font_family: str | None, font_size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
|
|
34
|
+
"""Memoized font loader: avoids re-reading the font file for every word."""
|
|
35
|
+
try:
|
|
36
|
+
return get_font(font_family, max(font_size, 1))
|
|
37
|
+
except Exception: # pragma: no cover
|
|
38
|
+
logger.warning(f"Could not load font '{font_family}', falling back to the default font")
|
|
39
|
+
return get_font(None, max(font_size, 1))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@lru_cache(maxsize=1)
|
|
43
|
+
def _warn_rotation_once() -> None: # pragma: no cover
|
|
44
|
+
# lru_cache is thread-safe "warn once" semantics without a mutable global
|
|
45
|
+
logger.warning("Polygons with larger rotations may lead to slightly inaccurate rendering")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _points(geometry: Any) -> list[tuple[float, float]] | None:
|
|
49
|
+
"""Validate a geometry and return its points, or None if it is unusable."""
|
|
50
|
+
try:
|
|
51
|
+
points = [(float(x), float(y)) for x, y in geometry]
|
|
52
|
+
except (TypeError, ValueError):
|
|
53
|
+
return None
|
|
54
|
+
if len(points) not in (2, 4) or not all(math.isfinite(v) for point in points for v in point):
|
|
55
|
+
return None
|
|
56
|
+
return points
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _polygon_angle(polygon: list[tuple[float, float]], w: int, h: int) -> float:
|
|
60
|
+
"""Estimate the rotation angle (degrees, counter-clockwise) from the top edge of a 4-point polygon."""
|
|
61
|
+
(x0, y0), (x1, y1) = polygon[0], polygon[1]
|
|
62
|
+
return -math.degrees(math.atan2((y1 - y0) * h, (x1 - x0) * w))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _text_width(font: ImageFont.FreeTypeFont | ImageFont.ImageFont, text: str, stroke: int = 0) -> int:
|
|
66
|
+
"""Width from the drawing origin to the right edge of the ink, so the left bearing counts."""
|
|
67
|
+
bbox = font.getbbox(text)
|
|
68
|
+
return max(math.ceil(bbox[2]) + 2 * stroke, 1)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _text_height(font: ImageFont.FreeTypeFont | ImageFont.ImageFont, text: str) -> int:
|
|
72
|
+
"""Height from the top of the ink to the bottom, so the ascender counts."""
|
|
73
|
+
bbox = font.getbbox(text)
|
|
74
|
+
return max(int(bbox[3]) - int(bbox[1]), 1)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _text_vspan(font: ImageFont.FreeTypeFont | ImageFont.ImageFont, text: str) -> int:
|
|
78
|
+
"""Ascender-to-descender span: the vertical extent the "lm" anchor is centered on."""
|
|
79
|
+
try:
|
|
80
|
+
ascent, descent = font.getmetrics() # type: ignore[union-attr]
|
|
81
|
+
return max(ascent + descent, 1)
|
|
82
|
+
except AttributeError: # pragma: no cover - bitmap fonts expose no metrics
|
|
83
|
+
return _text_height(font, text)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _fit_font_size(
|
|
87
|
+
text: str,
|
|
88
|
+
box_w: int,
|
|
89
|
+
box_h: int,
|
|
90
|
+
font_family: str | None,
|
|
91
|
+
min_font_size: int,
|
|
92
|
+
max_font_size: int,
|
|
93
|
+
) -> int:
|
|
94
|
+
"""Directly estimate the largest font size fitting the box (text width scales ~linearly with size)."""
|
|
95
|
+
font_size = max(min(box_h, max_font_size), min_font_size)
|
|
96
|
+
try:
|
|
97
|
+
font = _cached_font(font_family, font_size)
|
|
98
|
+
# A font size is an em size while the box bounds the ink, so scale on the measured ink:
|
|
99
|
+
# without this the text is rendered noticeably smaller than the box it was detected in.
|
|
100
|
+
scale = min(box_w / _text_width(font, text), box_h / _text_height(font, text))
|
|
101
|
+
font_size = max(min(int(font_size * scale), max_font_size), min_font_size)
|
|
102
|
+
except ValueError: # pragma: no cover
|
|
103
|
+
font_size = min_font_size
|
|
104
|
+
return font_size
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _fit_line_font_size(
|
|
108
|
+
words: list[_Word],
|
|
109
|
+
font_family: str | None,
|
|
110
|
+
min_font_size: int,
|
|
111
|
+
max_font_size: int,
|
|
112
|
+
) -> int:
|
|
113
|
+
"""Find one font size for a whole line, driven by the median word box."""
|
|
114
|
+
font_size = max(min(int(np.median([word.height for word in words])), max_font_size), min_font_size)
|
|
115
|
+
try:
|
|
116
|
+
font = _cached_font(font_family, font_size)
|
|
117
|
+
scale = min(
|
|
118
|
+
float(np.median([word.height / _text_height(font, word.value) for word in words])),
|
|
119
|
+
float(np.median([word.width / _text_width(font, word.value) for word in words])),
|
|
120
|
+
)
|
|
121
|
+
font_size = max(min(int(font_size * scale), max_font_size), min_font_size)
|
|
122
|
+
except ValueError: # pragma: no cover
|
|
123
|
+
font_size = min_font_size
|
|
124
|
+
return font_size
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _harmonize(sizes: list[int], tolerance: float = 0.2, passes: int = 4) -> list[int]:
|
|
128
|
+
"""Snap font sizes that are close to each other onto one common size.
|
|
129
|
+
|
|
130
|
+
Boxes for one and the same typeface come out a pixel or two apart from line to line, and
|
|
131
|
+
rendering every line at its own size is what makes a synthesized page look ragged. Sizes
|
|
132
|
+
within `tolerance` of each other collapse onto their median, while genuinely different sizes
|
|
133
|
+
- a headline, a caption, small print - stay apart.
|
|
134
|
+
"""
|
|
135
|
+
values = np.array(sizes, dtype=float)
|
|
136
|
+
for _ in range(passes):
|
|
137
|
+
snapped = np.array([float(np.median(values[np.abs(values - size) <= tolerance * size])) for size in values])
|
|
138
|
+
if np.array_equal(snapped, values):
|
|
139
|
+
break
|
|
140
|
+
values = snapped
|
|
141
|
+
return [int(round(float(value))) for value in values]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _stroke(font_size: int, bold: bool) -> int:
|
|
145
|
+
"""Outline width that sets a face in bold, kept in one place so every entry gets one weight."""
|
|
146
|
+
return max(round(font_size / 32), 1) if bold else 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _draw_word(
|
|
150
|
+
d: ImageDraw.ImageDraw,
|
|
151
|
+
xy: tuple[int, int],
|
|
152
|
+
text: str,
|
|
153
|
+
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
|
|
154
|
+
fill: tuple[int, int, int],
|
|
155
|
+
anchor: str = "lm",
|
|
156
|
+
stroke: int = 0,
|
|
157
|
+
) -> None:
|
|
158
|
+
"""Draw a word, falling back to ASCII if the font cannot render it.
|
|
159
|
+
|
|
160
|
+
`stroke` outlines the glyphs in their own colour, which is how a heading is set in bold without
|
|
161
|
+
a second font file
|
|
162
|
+
"""
|
|
163
|
+
try:
|
|
164
|
+
try:
|
|
165
|
+
d.text(xy, text, font=font, fill=fill, anchor=anchor, stroke_width=stroke, stroke_fill=fill)
|
|
166
|
+
except UnicodeEncodeError:
|
|
167
|
+
d.text(xy, anyascii(text), font=font, fill=fill, anchor=anchor, stroke_width=stroke, stroke_fill=fill)
|
|
168
|
+
except Exception: # pragma: no cover
|
|
169
|
+
try:
|
|
170
|
+
# Anchors are rejected by bitmap fonts, which would otherwise leave the page blank
|
|
171
|
+
d.text(xy, anyascii(text), font=font, fill=fill)
|
|
172
|
+
except Exception:
|
|
173
|
+
logger.warning(f"Could not render word: {text}")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _paste_word(
|
|
177
|
+
response: Image.Image,
|
|
178
|
+
text: str,
|
|
179
|
+
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
|
|
180
|
+
position: tuple[int, int],
|
|
181
|
+
fill: tuple[int, int, int],
|
|
182
|
+
angle: float = 0.0,
|
|
183
|
+
squeeze: float = 1.0,
|
|
184
|
+
stroke: int = 0,
|
|
185
|
+
) -> None:
|
|
186
|
+
"""Render a word on a transparent patch, condense and rotate it, then paste it."""
|
|
187
|
+
pad = 2 + stroke
|
|
188
|
+
patch = Image.new(
|
|
189
|
+
"RGBA",
|
|
190
|
+
(_text_width(font, text, stroke) + 2 * pad, _text_vspan(font, text) + 2 * pad + 2 * stroke),
|
|
191
|
+
(0, 0, 0, 0),
|
|
192
|
+
)
|
|
193
|
+
_draw_word(ImageDraw.Draw(patch), (pad, pad + stroke), text, font, fill, anchor="la", stroke=stroke)
|
|
194
|
+
if squeeze < 1.0:
|
|
195
|
+
patch = patch.resize((max(round(patch.width * squeeze), 1), patch.height), Image.Resampling.BICUBIC)
|
|
196
|
+
pad = round(pad * squeeze)
|
|
197
|
+
|
|
198
|
+
anchor_x, anchor_y = float(pad), patch.height / 2
|
|
199
|
+
if abs(angle) > 3:
|
|
200
|
+
# rotate() turns the patch about its centre and expands the canvas, so follow the anchor
|
|
201
|
+
theta = math.radians(angle)
|
|
202
|
+
dx, dy = anchor_x - patch.width / 2, anchor_y - patch.height / 2
|
|
203
|
+
patch = patch.rotate(angle, expand=True, resample=Image.Resampling.BICUBIC)
|
|
204
|
+
anchor_x = patch.width / 2 + dx * math.cos(theta) + dy * math.sin(theta)
|
|
205
|
+
anchor_y = patch.height / 2 - dx * math.sin(theta) + dy * math.cos(theta)
|
|
206
|
+
response.paste(patch, (round(position[0] - anchor_x), round(position[1] - anchor_y)), patch)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _tilt(words: list[_Word], sample: int = 64) -> float | None:
|
|
210
|
+
"""Direction of a line in degrees, read from where its words sit, or None if they disagree."""
|
|
211
|
+
if len(words) < 4:
|
|
212
|
+
return None
|
|
213
|
+
if len(words) > sample:
|
|
214
|
+
step = len(words) / sample
|
|
215
|
+
words = [words[int(index * step)] for index in range(sample)]
|
|
216
|
+
xs = np.array([word.x for word in words], dtype=float)
|
|
217
|
+
ys = np.array([word.y for word in words], dtype=float)
|
|
218
|
+
height = float(np.median([word.height for word in words]))
|
|
219
|
+
dx, dy = xs[:, None] - xs[None, :], ys[:, None] - ys[None, :]
|
|
220
|
+
spread = np.abs(dx) > height # pairs too close together only measure box noise
|
|
221
|
+
if not spread.any():
|
|
222
|
+
return None
|
|
223
|
+
slopes = dy[spread] / dx[spread]
|
|
224
|
+
slope = float(np.median(slopes))
|
|
225
|
+
if float(np.median(np.abs(slopes - slope))) > max(0.5 * abs(slope), 0.02):
|
|
226
|
+
return None
|
|
227
|
+
return -math.degrees(math.atan(slope))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _unrotate_box(word: _Word, angle: float) -> _Word:
|
|
231
|
+
"""Recover the text extent and leading-edge anchor of a word from its axis-aligned box."""
|
|
232
|
+
s, c = abs(math.sin(math.radians(angle))), abs(math.cos(math.radians(angle)))
|
|
233
|
+
det = c * c - s * s
|
|
234
|
+
if det < 0.2: # past ~39 degrees the inversion stops being trustworthy
|
|
235
|
+
return word
|
|
236
|
+
width = (word.width * c - word.height * s) / det
|
|
237
|
+
height = (word.height * c - word.width * s) / det
|
|
238
|
+
if width < 1 or height < 1:
|
|
239
|
+
return word
|
|
240
|
+
# The anchor moves from the middle of the box edge to the middle of the leading edge of the text
|
|
241
|
+
x = word.x + height * s / 2
|
|
242
|
+
y = word.y - word.height / 2 + height * c / 2 if angle < 0 else word.y + word.height / 2 - height * c / 2
|
|
243
|
+
return word._replace(x=round(x), y=round(y), width=round(width), height=round(height), angle=angle)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _space_width(font: ImageFont.FreeTypeFont | ImageFont.ImageFont) -> float:
|
|
247
|
+
"""Half of the font's own space advance: the least gap that still reads as a word break."""
|
|
248
|
+
try:
|
|
249
|
+
return max(float(font.getlength(" ")) / 2, 1.0)
|
|
250
|
+
except Exception: # pragma: no cover - a bitmap font may not measure a space
|
|
251
|
+
return max(_text_width(font, "n") / 2, 1.0)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _entry_words(entry: dict[str, Any], w: int, h: int) -> list[_Word]:
|
|
255
|
+
"""Collect the renderable words of a line entry, in pixel coordinates."""
|
|
256
|
+
words = []
|
|
257
|
+
for word in entry.get("words") or []:
|
|
258
|
+
if not isinstance(word, dict):
|
|
259
|
+
continue
|
|
260
|
+
geom = _points(word.get("geometry"))
|
|
261
|
+
if geom is None or not str(word.get("value", "")).strip():
|
|
262
|
+
continue
|
|
263
|
+
value = str(word["value"])
|
|
264
|
+
if len(geom) == 2:
|
|
265
|
+
(gx0, gy0), (gx1, gy1) = geom
|
|
266
|
+
x0, y0 = int(round(w * gx0)), int(round(h * gy0))
|
|
267
|
+
x1, y1 = int(round(w * gx1)), int(round(h * gy1))
|
|
268
|
+
words.append(_Word(value, min(x0, x1), (y0 + y1) // 2, max(abs(x1 - x0), 1), max(abs(y1 - y0), 1), 0.0))
|
|
269
|
+
else:
|
|
270
|
+
# True text-direction extent: length of the top edge / left edge in pixels
|
|
271
|
+
width = math.hypot((geom[1][0] - geom[0][0]) * w, (geom[1][1] - geom[0][1]) * h)
|
|
272
|
+
height = math.hypot((geom[2][0] - geom[1][0]) * w, (geom[2][1] - geom[1][1]) * h)
|
|
273
|
+
words.append(
|
|
274
|
+
_Word(
|
|
275
|
+
value,
|
|
276
|
+
int(round(w * (geom[0][0] + geom[3][0]) / 2)),
|
|
277
|
+
int(round(h * (geom[0][1] + geom[3][1]) / 2)),
|
|
278
|
+
max(int(round(width)), 1),
|
|
279
|
+
max(int(round(height)), 1),
|
|
280
|
+
_polygon_angle(geom, w, h),
|
|
281
|
+
)
|
|
282
|
+
)
|
|
283
|
+
# An upright box carries no angle of its own, so a tilted line has to be recognised from where
|
|
284
|
+
# its words sit before anything can be sized off boxes that the tilt has inflated
|
|
285
|
+
tilt = _tilt(words) if words and not any(word.angle for word in words) else None
|
|
286
|
+
return [_unrotate_box(word, tilt) for word in words] if tilt and abs(tilt) >= 3 else words
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _line_axis(words: list[_Word]) -> tuple[float, float, float, float, float]:
|
|
290
|
+
"""The baseline of a line: its origin, its unit direction and its angle."""
|
|
291
|
+
# Where the words sit pins the direction down far more tightly than their own corners do,
|
|
292
|
+
# so the box angles are only a fallback for lines too short to read a trend from
|
|
293
|
+
angle = _tilt(words)
|
|
294
|
+
if angle is None:
|
|
295
|
+
angle = _median_angle(words)
|
|
296
|
+
theta = math.radians(angle)
|
|
297
|
+
ux, uy = math.cos(theta), -math.sin(theta)
|
|
298
|
+
x0, y0 = words[0].x, words[0].y
|
|
299
|
+
across = float(np.median([(word.x - x0) * -uy + (word.y - y0) * ux for word in words]))
|
|
300
|
+
return x0 + across * -uy, y0 + across * ux, ux, uy, angle
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _place_words(offsets: list[float], widths: list[float], space: float, budget: float) -> tuple[list[float], float]:
|
|
304
|
+
"""Keep every word where it was detected, unless that would run it into its neighbour.
|
|
305
|
+
|
|
306
|
+
A word only moves when the word before it needs the room, and if the line then overruns the
|
|
307
|
+
space it was detected in, the whole line is condensed by a single factor - so words never
|
|
308
|
+
overlap, and the ones that had to give way still share the size of the rest of the page.
|
|
309
|
+
"""
|
|
310
|
+
|
|
311
|
+
def run(squeeze: float) -> list[float]:
|
|
312
|
+
cursor, placed = -math.inf, []
|
|
313
|
+
for offset, width in zip(offsets, widths):
|
|
314
|
+
start = max(offset, cursor)
|
|
315
|
+
placed.append(start)
|
|
316
|
+
cursor = start + squeeze * (width + space)
|
|
317
|
+
return placed
|
|
318
|
+
|
|
319
|
+
placed, squeeze = run(1.0), 1.0
|
|
320
|
+
for _ in range(3): # pushes shrink as the line condenses, so a few passes converge
|
|
321
|
+
end = placed[-1] + squeeze * widths[-1]
|
|
322
|
+
if end <= budget or budget <= 0:
|
|
323
|
+
break
|
|
324
|
+
squeeze = max(squeeze * budget / end, 0.5)
|
|
325
|
+
placed = run(squeeze)
|
|
326
|
+
return placed, squeeze
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _median_angle(words: list[_Word]) -> float:
|
|
330
|
+
"""Median of the word angles, folded so they all lie within a quarter turn of zero."""
|
|
331
|
+
return float(np.median([(word.angle + 90) % 180 - 90 for word in words]))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _split_rows(words: list[_Word]) -> list[list[_Word]]:
|
|
335
|
+
"""Split a group of words into the separate baselines they actually sit on."""
|
|
336
|
+
if len(words) < 2:
|
|
337
|
+
return [words]
|
|
338
|
+
theta = math.radians(_median_angle(words))
|
|
339
|
+
vx, vy = math.sin(theta), math.cos(theta) # across the text direction
|
|
340
|
+
tolerance = 0.8 * float(np.median([word.height for word in words]))
|
|
341
|
+
ordered = sorted(words, key=lambda word: word.x * vx + word.y * vy)
|
|
342
|
+
rows, current = [], [ordered[0]]
|
|
343
|
+
for previous, word in zip(ordered, ordered[1:]):
|
|
344
|
+
if (word.x - previous.x) * vx + (word.y - previous.y) * vy > tolerance:
|
|
345
|
+
rows.append(current)
|
|
346
|
+
current = []
|
|
347
|
+
current.append(word)
|
|
348
|
+
rows.append(current)
|
|
349
|
+
return rows
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _place_word(
|
|
353
|
+
response: Image.Image,
|
|
354
|
+
d: ImageDraw.ImageDraw,
|
|
355
|
+
text: str,
|
|
356
|
+
font: ImageFont.FreeTypeFont | ImageFont.ImageFont,
|
|
357
|
+
position: tuple[int, int],
|
|
358
|
+
fill: tuple[int, int, int],
|
|
359
|
+
angle: float = 0.0,
|
|
360
|
+
squeeze: float = 1.0,
|
|
361
|
+
stroke: int = 0,
|
|
362
|
+
) -> None:
|
|
363
|
+
"""Put one word on the page: straight onto it when it can be, on a patch when it cannot."""
|
|
364
|
+
if abs(angle) > 3 or squeeze < 1.0:
|
|
365
|
+
_paste_word(response, text, font, position, fill, angle, squeeze, stroke)
|
|
366
|
+
else:
|
|
367
|
+
# "lm" anchor: vertically centered on the baseline, no ascender-offset drift
|
|
368
|
+
_draw_word(d, position, text, font, fill, anchor="lm", stroke=stroke)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _synthesize_line(
|
|
372
|
+
response: Image.Image,
|
|
373
|
+
words: list[_Word],
|
|
374
|
+
font_size: int,
|
|
375
|
+
font_family: str | None,
|
|
376
|
+
min_font_size: int,
|
|
377
|
+
text_color: tuple[int, int, int],
|
|
378
|
+
bold: bool = False,
|
|
379
|
+
) -> None:
|
|
380
|
+
"""Draw a line, as one row per baseline its words turn out to share."""
|
|
381
|
+
for row in _split_rows(words):
|
|
382
|
+
_synthesize_row(response, row, font_size, font_family, min_font_size, text_color, bold)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _synthesize_row(
|
|
386
|
+
response: Image.Image,
|
|
387
|
+
words: list[_Word],
|
|
388
|
+
font_size: int,
|
|
389
|
+
font_family: str | None,
|
|
390
|
+
min_font_size: int,
|
|
391
|
+
text_color: tuple[int, int, int],
|
|
392
|
+
bold: bool = False,
|
|
393
|
+
) -> None:
|
|
394
|
+
"""Draw the words of one row at one font size, spaced so that none can overlap the next."""
|
|
395
|
+
ox, oy, ux, uy, angle = _line_axis(words)
|
|
396
|
+
along = sorted(((word.x - ox) * ux + (word.y - oy) * uy, word) for word in words)
|
|
397
|
+
offsets = [offset for offset, _ in along]
|
|
398
|
+
words = [word for _, word in along]
|
|
399
|
+
budget = max(offset + word.width for offset, word in along)
|
|
400
|
+
|
|
401
|
+
for _ in range(2):
|
|
402
|
+
font = _cached_font(font_family, font_size)
|
|
403
|
+
# A bold face is set by outlining the glyphs, which widens them: the layout has to allow
|
|
404
|
+
# for that or the extra weight would spill over the following word
|
|
405
|
+
stroke = _stroke(font_size, bold)
|
|
406
|
+
squeezes = [max(min(1.0, word.width / _text_width(font, word.value, stroke)), 0.5) for word in words]
|
|
407
|
+
widths = [squeeze * _text_width(font, word.value, stroke) for squeeze, word in zip(squeezes, words)]
|
|
408
|
+
# The boxes cannot supply the spacing (a detector dilates them), so the layout keeps at
|
|
409
|
+
# least a readable gap of its own between one word and the next
|
|
410
|
+
placed, line_squeeze = _place_words(offsets, widths, _space_width(font), budget)
|
|
411
|
+
# A line that would have to be condensed to less than half is not crowded but mis-sized:
|
|
412
|
+
# a smaller face keeps it readable instead of squashing the glyphs to nothing.
|
|
413
|
+
if line_squeeze > 0.5 or font_size <= min_font_size:
|
|
414
|
+
break
|
|
415
|
+
font_size = max(int(font_size * 2 * line_squeeze), min_font_size)
|
|
416
|
+
|
|
417
|
+
d = ImageDraw.Draw(response)
|
|
418
|
+
for word, offset, squeeze in zip(words, placed, squeezes):
|
|
419
|
+
x, y = round(ox + offset * ux), round(oy + offset * uy)
|
|
420
|
+
_place_word(response, d, word.value, font, (x, y), text_color, angle, squeeze * line_squeeze, stroke)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _synthesize_value(
|
|
29
424
|
response: Image.Image,
|
|
30
425
|
entry: dict[str, Any],
|
|
426
|
+
polygon: list[tuple[float, float]],
|
|
427
|
+
angle: float,
|
|
31
428
|
w: int,
|
|
32
429
|
h: int,
|
|
33
|
-
|
|
430
|
+
font_size: int,
|
|
431
|
+
font_family: str | None,
|
|
432
|
+
text_color: tuple[int, int, int],
|
|
433
|
+
bold: bool = False,
|
|
434
|
+
) -> None:
|
|
435
|
+
"""Draw a single value (a word entry, or a KIE prediction) inside its own box."""
|
|
436
|
+
text = str(entry["value"])
|
|
437
|
+
# Measure along the text direction, not on the axis-aligned bounding box
|
|
438
|
+
box_w = max(int(round(math.hypot((polygon[1][0] - polygon[0][0]) * w, (polygon[1][1] - polygon[0][1]) * h))), 1)
|
|
439
|
+
font = _cached_font(font_family, font_size)
|
|
440
|
+
# Anchor on the middle of the leading edge, like the "lm" anchor of flat text
|
|
441
|
+
x = int(round(w * (polygon[0][0] + polygon[3][0]) / 2))
|
|
442
|
+
y = int(round(h * (polygon[0][1] + polygon[3][1]) / 2))
|
|
443
|
+
stroke = _stroke(font_size, bold)
|
|
444
|
+
# stay inside the box, do not run into the next field
|
|
445
|
+
squeeze = min(1.0, box_w / _text_width(font, text, stroke))
|
|
446
|
+
_place_word(response, ImageDraw.Draw(response), text, font, (x, y), text_color, angle, squeeze, stroke)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _draw_confidence(
|
|
450
|
+
response: Image.Image,
|
|
451
|
+
entry: dict[str, Any],
|
|
452
|
+
box: tuple[int, int, int, int],
|
|
453
|
+
font_family: str | None,
|
|
454
|
+
) -> None:
|
|
455
|
+
"""Outline the entry and label it with its confidence. Blue: p=1, red: p=0."""
|
|
456
|
+
xmin, ymin, xmax, ymax = box
|
|
457
|
+
box_width, box_height = max(xmax - xmin, 1), max(ymax - ymin, 1)
|
|
458
|
+
confidences = [
|
|
459
|
+
float(word["confidence"])
|
|
460
|
+
for word in entry.get("words") or []
|
|
461
|
+
if isinstance(word, dict)
|
|
462
|
+
and isinstance(word.get("confidence"), int | float)
|
|
463
|
+
and math.isfinite(float(word["confidence"]))
|
|
464
|
+
]
|
|
465
|
+
confidence = entry.get("confidence")
|
|
466
|
+
if not (isinstance(confidence, int | float) and math.isfinite(float(confidence))):
|
|
467
|
+
confidence = float(np.mean(confidences)) if confidences else 1.0
|
|
468
|
+
confidence = min(max(float(confidence), 0.0), 1.0)
|
|
469
|
+
p = int(255 * confidence)
|
|
470
|
+
color = (255 - p, 0, p)
|
|
471
|
+
|
|
472
|
+
d = ImageDraw.Draw(response)
|
|
473
|
+
d.rectangle([(xmin, ymin), (xmax, ymax)], outline=color, width=2)
|
|
474
|
+
# Scale the confidence label with the box instead of a hardcoded size
|
|
475
|
+
prob_font = _cached_font(font_family, max(min(box_height // 2, 20), 10))
|
|
476
|
+
prob_text = f"{confidence:.2f}"
|
|
477
|
+
prob_width, prob_height = _text_width(prob_font, prob_text), _text_height(prob_font, prob_text)
|
|
478
|
+
prob_x = xmin + (box_width - prob_width) // 2
|
|
479
|
+
# The label goes above the box it belongs to, and inside it when the box is against the top of
|
|
480
|
+
# the page: clamping to the page edge instead would draw the label over its own outline.
|
|
481
|
+
prob_y = ymin - prob_height - 2 if ymin - prob_height - 2 >= 0 else ymin + 3
|
|
482
|
+
_draw_word(d, (int(prob_x), int(prob_y)), prob_text, prob_font, color, anchor="lt")
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _region_kind(kind: str) -> str:
|
|
486
|
+
"""Normalize a layout class name so 'Section-header', 'section header' and 'SECTION_HEADER' match."""
|
|
487
|
+
return "".join(character for character in kind.lower() if character.isalnum())
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _region_type(regions: list[tuple[tuple[int, int, int, int], str]], point: tuple[int, int]) -> str:
|
|
491
|
+
"""Type of the smallest layout region holding a point, or "" if it falls outside them all."""
|
|
492
|
+
holding = [(box, kind) for box, kind in regions if box[0] <= point[0] <= box[2] and box[1] <= point[1] <= box[3]]
|
|
493
|
+
if not holding:
|
|
494
|
+
return ""
|
|
495
|
+
box, kind = min(holding, key=lambda item: (item[0][2] - item[0][0]) * (item[0][3] - item[0][1]))
|
|
496
|
+
return kind
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _draw_region(
|
|
500
|
+
response: Image.Image,
|
|
501
|
+
box: tuple[int, int, int, int],
|
|
502
|
+
color: tuple[int, int, int],
|
|
503
|
+
label: str = "",
|
|
34
504
|
font_family: str | None = None,
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
505
|
+
) -> None:
|
|
506
|
+
"""Outline a region of the page and, if it is roomy enough, name it."""
|
|
507
|
+
xmin, ymin, xmax, ymax = box
|
|
508
|
+
d = ImageDraw.Draw(response)
|
|
509
|
+
d.rectangle([(xmin, ymin), (xmax, ymax)], outline=color, width=2)
|
|
510
|
+
if label:
|
|
511
|
+
size = _fit_font_size(label, max(xmax - xmin, 1), max((ymax - ymin) // 4, 1), font_family, 8, 20)
|
|
512
|
+
font = _cached_font(font_family, size)
|
|
513
|
+
_draw_word(d, ((xmin + xmax) // 2, (ymin + ymax) // 2), label, font, color, anchor="mm")
|
|
44
514
|
|
|
45
|
-
|
|
515
|
+
|
|
516
|
+
def _entry_geometry(
|
|
517
|
+
entry: dict[str, Any], w: int, h: int
|
|
518
|
+
) -> tuple[list[tuple[float, float]], float, tuple[int, int, int, int]] | None:
|
|
519
|
+
"""Normalize an entry geometry to a 4-point polygon, its angle and its pixel bounding box."""
|
|
520
|
+
geometry = _points(entry.get("geometry"))
|
|
521
|
+
if geometry is None:
|
|
522
|
+
return None
|
|
523
|
+
if len(geometry) == 2:
|
|
524
|
+
(xmin_r, ymin_r), (xmax_r, ymax_r) = geometry
|
|
525
|
+
polygon = [(xmin_r, ymin_r), (xmax_r, ymin_r), (xmax_r, ymax_r), (xmin_r, ymax_r)]
|
|
526
|
+
angle = 0.0
|
|
527
|
+
else:
|
|
528
|
+
polygon, angle = geometry, _polygon_angle(geometry, w, h)
|
|
529
|
+
_warn_rotation_once() # pragma: no cover
|
|
46
530
|
x_coords, y_coords = zip(*polygon)
|
|
47
|
-
|
|
531
|
+
box = (
|
|
48
532
|
int(round(w * min(x_coords))),
|
|
49
533
|
int(round(h * min(y_coords))),
|
|
50
534
|
int(round(w * max(x_coords))),
|
|
51
535
|
int(round(h * max(y_coords))),
|
|
52
536
|
)
|
|
53
|
-
|
|
54
|
-
word_height = ymax - ymin
|
|
537
|
+
return polygon, angle, box
|
|
55
538
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
# Draw the word text
|
|
79
|
-
d = ImageDraw.Draw(response)
|
|
539
|
+
|
|
540
|
+
def _entry_font_size(
|
|
541
|
+
entry: dict[str, Any],
|
|
542
|
+
words: list[_Word],
|
|
543
|
+
polygon: list[tuple[float, float]],
|
|
544
|
+
w: int,
|
|
545
|
+
h: int,
|
|
546
|
+
font_family: str | None,
|
|
547
|
+
min_font_size: int,
|
|
548
|
+
max_font_size: int,
|
|
549
|
+
) -> int:
|
|
550
|
+
"""The size this entry would like, before it is harmonized with the rest of the page."""
|
|
551
|
+
if words:
|
|
552
|
+
return _fit_line_font_size(words, font_family, min_font_size, max_font_size)
|
|
553
|
+
box_w = max(int(round(math.hypot((polygon[1][0] - polygon[0][0]) * w, (polygon[1][1] - polygon[0][1]) * h))), 1)
|
|
554
|
+
box_h = max(int(round(math.hypot((polygon[2][0] - polygon[1][0]) * w, (polygon[2][1] - polygon[1][1]) * h))), 1)
|
|
555
|
+
return _fit_font_size(str(entry["value"]), box_w, box_h, font_family, min_font_size, max_font_size)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _page_size(page: dict[str, Any]) -> tuple[int, int]:
|
|
559
|
+
"""Validate the page dimensions before allocating the canvas."""
|
|
80
560
|
try:
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
561
|
+
h, w = (int(round(float(value))) for value in page["dimensions"])
|
|
562
|
+
except Exception as exc:
|
|
563
|
+
raise ValueError(f"invalid page 'dimensions': {page.get('dimensions')!r}") from exc
|
|
564
|
+
if h <= 0 or w <= 0:
|
|
565
|
+
raise ValueError(f"page dimensions must be positive, got {(h, w)}")
|
|
566
|
+
if Image.MAX_IMAGE_PIXELS is not None and h * w > Image.MAX_IMAGE_PIXELS:
|
|
567
|
+
raise ValueError(f"page dimensions {(h, w)} exceed Pillow's MAX_IMAGE_PIXELS safety limit")
|
|
568
|
+
return h, w
|
|
88
569
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
570
|
+
|
|
571
|
+
def _render(
|
|
572
|
+
page: dict[str, Any],
|
|
573
|
+
entries: list[dict[str, Any]],
|
|
574
|
+
draw_proba: bool,
|
|
575
|
+
font_family: str | None,
|
|
576
|
+
min_font_size: int,
|
|
577
|
+
max_font_size: int,
|
|
578
|
+
background_color: tuple[int, int, int],
|
|
579
|
+
text_color: tuple[int, int, int],
|
|
580
|
+
draw_placeholders: bool,
|
|
581
|
+
) -> np.ndarray:
|
|
582
|
+
"""Render entries onto a blank page at one harmonized set of font sizes."""
|
|
583
|
+
if min_font_size < 1 or max_font_size < min_font_size:
|
|
584
|
+
raise ValueError(
|
|
585
|
+
f"font sizes must satisfy 1 <= min_font_size <= max_font_size, got {(min_font_size, max_font_size)}"
|
|
94
586
|
)
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
587
|
+
h, w = _page_size(page)
|
|
588
|
+
response = Image.new("RGB", (w, h), color=background_color)
|
|
589
|
+
|
|
590
|
+
prepared = []
|
|
591
|
+
for entry in entries:
|
|
592
|
+
geometry = _entry_geometry(entry, w, h)
|
|
593
|
+
if geometry is None:
|
|
594
|
+
continue
|
|
595
|
+
polygon, angle, box = geometry
|
|
596
|
+
words = _entry_words(entry, w, h)
|
|
597
|
+
if not words and not str(entry.get("value", "")).strip():
|
|
598
|
+
if draw_proba:
|
|
599
|
+
_draw_confidence(response, entry, box, font_family)
|
|
600
|
+
continue
|
|
601
|
+
try:
|
|
602
|
+
size = _entry_font_size(entry, words, polygon, w, h, font_family, min_font_size, max_font_size)
|
|
603
|
+
except Exception as exc:
|
|
604
|
+
logger.warning(f"Could not size entry: {exc}")
|
|
605
|
+
continue
|
|
606
|
+
prepared.append((entry, polygon, angle, box, words, size))
|
|
98
607
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
608
|
+
# The grid of a table, and the outline of a region holding no text of its own - a picture, a
|
|
609
|
+
# formula, a region the predictor was told to ignore - are both stand-ins for structure the page
|
|
610
|
+
# carries but its text does not. Neither is content, so both are drawn only when the caller asks
|
|
611
|
+
# for placeholders, and then in a tone leaning towards the page itself so they stay quiet under
|
|
612
|
+
# the text that is laid over them.
|
|
613
|
+
faint: tuple[int, int, int] = tuple((2 * back + fore) // 3 for back, fore in zip(background_color, text_color)) # type: ignore[assignment]
|
|
614
|
+
filled: list[tuple[int, int]] = []
|
|
615
|
+
if draw_placeholders:
|
|
616
|
+
for _, _, _, box, entry_words, _ in prepared:
|
|
617
|
+
filled.extend(
|
|
618
|
+
[(word.x, word.y) for word in entry_words] or [((box[0] + box[2]) // 2, (box[1] + box[3]) // 2)]
|
|
619
|
+
)
|
|
620
|
+
for table in page.get("tables") or []:
|
|
621
|
+
if not isinstance(table, dict):
|
|
622
|
+
continue
|
|
623
|
+
for region in [table, *(table.get("cells") or [])]:
|
|
624
|
+
geometry = _entry_geometry(region, w, h) if isinstance(region, dict) else None
|
|
625
|
+
if geometry is not None:
|
|
626
|
+
_draw_region(response, geometry[2], faint)
|
|
627
|
+
regions = []
|
|
628
|
+
for region in page.get("layout") or []:
|
|
629
|
+
geometry = _entry_geometry(region, w, h) if isinstance(region, dict) else None
|
|
630
|
+
if geometry is None:
|
|
631
|
+
continue
|
|
632
|
+
regions.append((geometry[2], str(region.get("type", "")).strip()))
|
|
633
|
+
xmin, ymin, xmax, ymax = geometry[2]
|
|
634
|
+
if draw_placeholders and not any(xmin <= x <= xmax and ymin <= y <= ymax for x, y in filled):
|
|
635
|
+
_draw_region(response, geometry[2], faint, str(region.get("type", "")).strip(), font_family)
|
|
102
636
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
637
|
+
sizes = [size for *_, size in prepared]
|
|
638
|
+
# A page that is nothing but a table - a cropped invoice, a receipt - has no body text to borrow a size from,
|
|
639
|
+
# so half the height of the row stands in for the padding a cell carries.
|
|
640
|
+
body = [size for (entry, *_), size in zip(prepared, sizes) if "row_start" not in entry]
|
|
641
|
+
page_size = int(np.median(body)) if body else 0
|
|
642
|
+
for index, ((entry, _, _, box, _, _), size) in enumerate(zip(prepared, sizes)):
|
|
643
|
+
if "row_start" not in entry:
|
|
644
|
+
continue
|
|
645
|
+
# A page that is nothing but a table - a cropped invoice, a receipt - has no body text to
|
|
646
|
+
# borrow a size from, so half the height of the row stands in for the padding a cell carries
|
|
647
|
+
cap = page_size or max((box[3] - box[1]) // 2, 1)
|
|
648
|
+
sizes[index] = max(min(size, cap), min_font_size)
|
|
649
|
+
# Harmonizing inside a region rather than across the whole page is what keeps a section header its own size
|
|
650
|
+
grouped: dict[str, list[int]] = {}
|
|
651
|
+
for index, (_, _, _, box, _, _) in enumerate(prepared):
|
|
652
|
+
centre = ((box[0] + box[2]) // 2, (box[1] + box[3]) // 2)
|
|
653
|
+
grouped.setdefault(_region_type(regions, centre), []).append(index)
|
|
654
|
+
for indices in grouped.values():
|
|
655
|
+
for index, size in zip(indices, _harmonize([sizes[index] for index in indices])):
|
|
656
|
+
sizes[index] = size
|
|
107
657
|
|
|
108
|
-
|
|
658
|
+
for (entry, polygon, angle, box, words, _), size in zip(prepared, sizes):
|
|
659
|
+
centre = ((box[0] + box[2]) // 2, (box[1] + box[3]) // 2)
|
|
660
|
+
kind = _region_kind(_region_type(regions, centre))
|
|
661
|
+
bold = kind in ("title", "sectionheader")
|
|
662
|
+
try:
|
|
663
|
+
if words:
|
|
664
|
+
_synthesize_line(response, words, size, font_family, min_font_size, text_color, bold)
|
|
665
|
+
else:
|
|
666
|
+
_synthesize_value(response, entry, polygon, angle, w, h, size, font_family, text_color, bold)
|
|
667
|
+
except Exception as exc:
|
|
668
|
+
logger.warning(f"Could not render entry: {exc}")
|
|
669
|
+
if draw_proba:
|
|
670
|
+
_draw_confidence(response, entry, box, font_family)
|
|
109
671
|
|
|
110
|
-
return response
|
|
672
|
+
return np.array(response, dtype=np.uint8)
|
|
111
673
|
|
|
112
674
|
|
|
113
675
|
def synthesize_page(
|
|
114
676
|
page: dict[str, Any],
|
|
115
677
|
draw_proba: bool = False,
|
|
116
678
|
font_family: str | None = None,
|
|
117
|
-
smoothing_factor: float = 0.95,
|
|
118
679
|
min_font_size: int = 8,
|
|
119
680
|
max_font_size: int = 50,
|
|
681
|
+
background_color: tuple[int, int, int] = (255, 255, 255),
|
|
682
|
+
text_color: tuple[int, int, int] = (0, 0, 0),
|
|
683
|
+
draw_placeholders: bool = False,
|
|
120
684
|
) -> np.ndarray:
|
|
121
|
-
"""Draw
|
|
685
|
+
"""Draw the content of the element page (OCR response) on a blank page.
|
|
122
686
|
|
|
123
687
|
Args:
|
|
124
688
|
page: exported Page object to represent
|
|
125
689
|
draw_proba: if True, draw words in colors to represent confidence. Blue: p=1, red: p=0
|
|
126
690
|
font_family: family of the font
|
|
127
|
-
smoothing_factor: factor to smooth the font size
|
|
128
691
|
min_font_size: minimum font size
|
|
129
692
|
max_font_size: maximum font size
|
|
693
|
+
background_color: RGB color of the page background
|
|
694
|
+
text_color: RGB color of the rendered text
|
|
695
|
+
draw_placeholders: if True, draw the grid of the recognized tables and outline the layout
|
|
696
|
+
regions holding no text of their own
|
|
130
697
|
|
|
131
698
|
Returns:
|
|
132
699
|
the synthesized page
|
|
133
700
|
"""
|
|
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
|
-
entry=word,
|
|
162
|
-
w=w,
|
|
163
|
-
h=h,
|
|
164
|
-
draw_proba=draw_proba,
|
|
165
|
-
font_family=font_family,
|
|
166
|
-
smoothing_factor=smoothing_factor,
|
|
167
|
-
min_font_size=min_font_size,
|
|
168
|
-
max_font_size=max_font_size,
|
|
169
|
-
)
|
|
170
|
-
|
|
171
|
-
return np.array(response, dtype=np.uint8)
|
|
701
|
+
entries = [
|
|
702
|
+
line
|
|
703
|
+
for block in page.get("blocks") or []
|
|
704
|
+
if isinstance(block, dict)
|
|
705
|
+
for line in block.get("lines") or []
|
|
706
|
+
if isinstance(line, dict)
|
|
707
|
+
]
|
|
708
|
+
# Words falling in a table are regrouped into its cells and removed from the blocks, so the
|
|
709
|
+
# cells are the only place that text still exists
|
|
710
|
+
entries += [
|
|
711
|
+
cell
|
|
712
|
+
for table in page.get("tables") or []
|
|
713
|
+
if isinstance(table, dict)
|
|
714
|
+
for cell in table.get("cells") or []
|
|
715
|
+
if isinstance(cell, dict)
|
|
716
|
+
]
|
|
717
|
+
return _render(
|
|
718
|
+
page,
|
|
719
|
+
entries,
|
|
720
|
+
draw_proba,
|
|
721
|
+
font_family,
|
|
722
|
+
min_font_size,
|
|
723
|
+
max_font_size,
|
|
724
|
+
background_color,
|
|
725
|
+
text_color,
|
|
726
|
+
draw_placeholders,
|
|
727
|
+
)
|
|
172
728
|
|
|
173
729
|
|
|
174
730
|
def synthesize_kie_page(
|
|
175
731
|
page: dict[str, Any],
|
|
176
732
|
draw_proba: bool = False,
|
|
177
733
|
font_family: str | None = None,
|
|
734
|
+
min_font_size: int = 8,
|
|
735
|
+
max_font_size: int = 50,
|
|
736
|
+
background_color: tuple[int, int, int] = (255, 255, 255),
|
|
737
|
+
text_color: tuple[int, int, int] = (0, 0, 0),
|
|
738
|
+
draw_placeholders: bool = False,
|
|
178
739
|
) -> np.ndarray:
|
|
179
|
-
"""Draw
|
|
740
|
+
"""Draw the content of the element page (KIE OCR response) on a blank page.
|
|
180
741
|
|
|
181
742
|
Args:
|
|
182
743
|
page: exported Page object to represent
|
|
183
744
|
draw_proba: if True, draw words in colors to represent confidence. Blue: p=1, red: p=0
|
|
184
745
|
font_family: family of the font
|
|
185
|
-
smoothing_factor: factor to smooth the font size
|
|
186
746
|
min_font_size: minimum font size
|
|
187
747
|
max_font_size: maximum font size
|
|
748
|
+
background_color: RGB color of the page background
|
|
749
|
+
text_color: RGB color of the rendered text
|
|
750
|
+
draw_placeholders: if True, draw the grid of the recognized tables and outline the layout
|
|
751
|
+
regions holding no text of their own
|
|
188
752
|
|
|
189
753
|
Returns:
|
|
190
754
|
the synthesized page
|
|
191
755
|
"""
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
756
|
+
predictions = [
|
|
757
|
+
prediction
|
|
758
|
+
for predictions in (page.get("predictions") or {}).values()
|
|
759
|
+
for prediction in predictions or []
|
|
760
|
+
if isinstance(prediction, dict)
|
|
761
|
+
]
|
|
762
|
+
return _render(
|
|
763
|
+
page,
|
|
764
|
+
predictions,
|
|
765
|
+
draw_proba,
|
|
766
|
+
font_family,
|
|
767
|
+
min_font_size,
|
|
768
|
+
max_font_size,
|
|
769
|
+
background_color,
|
|
770
|
+
text_color,
|
|
771
|
+
draw_placeholders,
|
|
772
|
+
)
|