python-doctr 1.1.0__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/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- 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 +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/utils/fonts.py
CHANGED
|
@@ -9,7 +9,7 @@ from functools import lru_cache
|
|
|
9
9
|
|
|
10
10
|
from PIL import ImageFont
|
|
11
11
|
|
|
12
|
-
__all__ = ["get_font"]
|
|
12
|
+
__all__ = ["get_font", "get_font_candidates"]
|
|
13
13
|
|
|
14
14
|
logger = logging.getLogger(__name__)
|
|
15
15
|
|
|
@@ -34,17 +34,25 @@ _FONT_CANDIDATES: dict[str, tuple[str, ...]] = {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
|
|
37
|
+
def _is_available(font_family: str) -> bool:
|
|
38
|
+
try:
|
|
39
|
+
_ = ImageFont.truetype(font_family, 10)
|
|
40
|
+
except OSError:
|
|
41
|
+
return False
|
|
42
|
+
return True
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_font_candidates() -> tuple[str, ...]:
|
|
46
|
+
"""List the recommended fonts which are installed on this system."""
|
|
47
|
+
candidates = _FONT_CANDIDATES.get(platform.system(), _FONT_CANDIDATES["Linux"])
|
|
48
|
+
return tuple(family for family in candidates if _is_available(family))
|
|
49
|
+
|
|
50
|
+
|
|
37
51
|
@lru_cache(maxsize=1)
|
|
38
52
|
def _resolve_default_font_family() -> str | None:
|
|
39
53
|
"""Find the first available candidate font for this platform."""
|
|
40
|
-
candidates =
|
|
41
|
-
|
|
42
|
-
try:
|
|
43
|
-
ImageFont.truetype(family, 10)
|
|
44
|
-
return family
|
|
45
|
-
except OSError:
|
|
46
|
-
continue
|
|
47
|
-
return None
|
|
54
|
+
candidates = get_font_candidates()
|
|
55
|
+
return candidates[0] if candidates else None
|
|
48
56
|
|
|
49
57
|
|
|
50
58
|
def get_font(font_family: str | None = None, font_size: int = 13) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
|
doctr/utils/geometry.py
CHANGED
|
@@ -37,9 +37,9 @@ def bbox_to_polygon(bbox: BoundingBox) -> Polygon4P:
|
|
|
37
37
|
bbox: a bounding box
|
|
38
38
|
|
|
39
39
|
Returns:
|
|
40
|
-
a polygon
|
|
40
|
+
a polygon with the top left, top right, bottom right and bottom left corners
|
|
41
41
|
"""
|
|
42
|
-
return bbox[0], (bbox[1][0], bbox[0][1]), (bbox[0][0], bbox[1][1])
|
|
42
|
+
return bbox[0], (bbox[1][0], bbox[0][1]), bbox[1], (bbox[0][0], bbox[1][1])
|
|
43
43
|
|
|
44
44
|
|
|
45
45
|
def polygon_to_bbox(polygon: Polygon4P) -> BoundingBox:
|
|
@@ -121,6 +121,8 @@ def detach_scores(boxes: list[np.ndarray]) -> tuple[list[np.ndarray], list[np.nd
|
|
|
121
121
|
return boxes[:, :-1], boxes[:, -1]
|
|
122
122
|
return boxes[:, :-1], boxes[:, -1, -1]
|
|
123
123
|
|
|
124
|
+
if len(boxes) == 0:
|
|
125
|
+
return [], []
|
|
124
126
|
loc_preds, obj_scores = zip(*(_detach(box) for box in boxes))
|
|
125
127
|
return list(loc_preds), list(obj_scores)
|
|
126
128
|
|
|
@@ -179,8 +181,10 @@ def rotate_abs_points(points: np.ndarray, angle: float = 0.0) -> np.ndarray:
|
|
|
179
181
|
Rotated points
|
|
180
182
|
"""
|
|
181
183
|
angle_rad = angle * np.pi / 180.0 # compute radian angle for np functions
|
|
184
|
+
# Integer points need a float matrix, otherwise its cosine and sine are truncated to 0 or 1
|
|
182
185
|
rotation_mat = np.array(
|
|
183
|
-
[[np.cos(angle_rad), -np.sin(angle_rad)], [np.sin(angle_rad), np.cos(angle_rad)]],
|
|
186
|
+
[[np.cos(angle_rad), -np.sin(angle_rad)], [np.sin(angle_rad), np.cos(angle_rad)]],
|
|
187
|
+
dtype=np.result_type(points.dtype, np.float32),
|
|
184
188
|
)
|
|
185
189
|
return np.matmul(points, rotation_mat.T)
|
|
186
190
|
|
|
@@ -266,7 +270,8 @@ def remap_boxes(loc_preds: np.ndarray, orig_shape: tuple[int, int], dest_shape:
|
|
|
266
270
|
raise ValueError(f"Image_shape length should be 2, was found at: {len(orig_shape)}")
|
|
267
271
|
orig_height, orig_width = orig_shape
|
|
268
272
|
dest_height, dest_width = dest_shape
|
|
269
|
-
|
|
273
|
+
# The remapped coordinates are fractional, so integer boxes (e.g. a whole page) are remapped in floating point
|
|
274
|
+
mboxes = loc_preds.astype(np.result_type(loc_preds.dtype, np.float32))
|
|
270
275
|
mboxes[:, :, 0] = ((loc_preds[:, :, 0] * orig_width) + (dest_width - orig_width) / 2) / dest_width
|
|
271
276
|
mboxes[:, :, 1] = ((loc_preds[:, :, 1] * orig_height) + (dest_height - orig_height) / 2) / dest_height
|
|
272
277
|
|
|
@@ -295,8 +300,8 @@ def rotate_boxes(
|
|
|
295
300
|
Returns:
|
|
296
301
|
A batch of rotated boxes (N, 4, 2): or a batch of straight bounding boxes
|
|
297
302
|
"""
|
|
298
|
-
# Change format of the boxes to rotated boxes
|
|
299
|
-
_boxes = loc_preds.
|
|
303
|
+
# Change format of the boxes to rotated boxes (in floating point, so that integer boxes can be rotated)
|
|
304
|
+
_boxes = loc_preds.astype(np.result_type(loc_preds.dtype, np.float32))
|
|
300
305
|
if _boxes.ndim == 2:
|
|
301
306
|
_boxes = np.stack(
|
|
302
307
|
[
|
|
@@ -330,6 +335,11 @@ def rotate_boxes(
|
|
|
330
335
|
return rotated_boxes
|
|
331
336
|
|
|
332
337
|
|
|
338
|
+
def _pad_width(image: np.ndarray, h_pad: int, w_pad: int) -> tuple[tuple[int, int], ...]:
|
|
339
|
+
"""Pad widths centering an image of shape (H, W) or (H, W, C) in a canvas larger by h_pad x w_pad"""
|
|
340
|
+
return ((h_pad // 2, h_pad - h_pad // 2), (w_pad // 2, w_pad - w_pad // 2)) + ((0, 0),) * (image.ndim - 2)
|
|
341
|
+
|
|
342
|
+
|
|
333
343
|
def rotate_image(
|
|
334
344
|
image: np.ndarray,
|
|
335
345
|
angle: float,
|
|
@@ -339,7 +349,7 @@ def rotate_image(
|
|
|
339
349
|
"""Rotate an image counterclockwise by an given angle.
|
|
340
350
|
|
|
341
351
|
Args:
|
|
342
|
-
image:
|
|
352
|
+
image: array of shape (H, W) or (H, W, C)
|
|
343
353
|
angle: rotation angle in degrees, between -90 and +90
|
|
344
354
|
expand: whether the image should be padded before the rotation
|
|
345
355
|
preserve_origin_shape: if expand is set to True, resizes the final output to the original image size
|
|
@@ -355,7 +365,7 @@ def rotate_image(
|
|
|
355
365
|
int(max(0, ceil(exp_shape[0] - image.shape[0]))),
|
|
356
366
|
int(max(0, ceil(exp_shape[1] - image.shape[1]))),
|
|
357
367
|
)
|
|
358
|
-
exp_img = np.pad(image, (
|
|
368
|
+
exp_img = np.pad(image, _pad_width(image, h_pad, w_pad))
|
|
359
369
|
else:
|
|
360
370
|
exp_img = image
|
|
361
371
|
|
|
@@ -371,10 +381,13 @@ def rotate_image(
|
|
|
371
381
|
# Pad height
|
|
372
382
|
else:
|
|
373
383
|
h_pad, w_pad = int(rot_img.shape[1] * image.shape[0] / image.shape[1] - rot_img.shape[0]), 0
|
|
374
|
-
rot_img = np.pad(rot_img, (
|
|
384
|
+
rot_img = np.pad(rot_img, _pad_width(rot_img, h_pad, w_pad))
|
|
375
385
|
if preserve_origin_shape:
|
|
376
386
|
# rescale
|
|
377
|
-
rot_img = cv2.resize(rot_img, image.shape[
|
|
387
|
+
rot_img = cv2.resize(rot_img, image.shape[1::-1], interpolation=cv2.INTER_LINEAR)
|
|
388
|
+
|
|
389
|
+
if rot_img.ndim < image.ndim: # cv2 drops a singleton channel axis
|
|
390
|
+
rot_img = rot_img[..., None]
|
|
378
391
|
|
|
379
392
|
return rot_img
|
|
380
393
|
|
|
@@ -407,7 +420,7 @@ def straighten_page(
|
|
|
407
420
|
and the inverse affine matrix that maps straightened-page coordinates back to the original page.
|
|
408
421
|
|
|
409
422
|
Args:
|
|
410
|
-
page: the original page image (H, W, C)
|
|
423
|
+
page: the original page image (H, W) or (H, W, C)
|
|
411
424
|
angle: rotation angle in degrees (between -90 and +90)
|
|
412
425
|
|
|
413
426
|
Returns:
|
|
@@ -425,21 +438,25 @@ def straighten_page(
|
|
|
425
438
|
pt, pb = h_pad // 2, h_pad - h_pad // 2
|
|
426
439
|
pl, pr = w_pad // 2, w_pad - w_pad // 2
|
|
427
440
|
|
|
428
|
-
|
|
441
|
+
# A grayscale page (H, W) has no channel axis to leave unpadded
|
|
442
|
+
channels = ((0, 0),) * (page.ndim - 2)
|
|
443
|
+
exp_img = np.pad(page, ((pt, pb), (pl, pr), *channels))
|
|
429
444
|
ph_pad, pw_pad = exp_img.shape[:2]
|
|
430
445
|
|
|
431
446
|
# Rotate around the padded image center
|
|
432
447
|
rot_mat = cv2.getRotationMatrix2D((pw_pad / 2, ph_pad / 2), angle, 1.0)
|
|
433
448
|
rotated = cv2.warpAffine(exp_img, rot_mat, (pw_pad, ph_pad))
|
|
449
|
+
if rotated.ndim < exp_img.ndim: # cv2 drops a singleton channel axis
|
|
450
|
+
rotated = rotated[..., None]
|
|
434
451
|
|
|
435
452
|
# Aspect-ratio padding (applied only on right/bottom so analytic crop stays simple)
|
|
436
453
|
if h_pad > 0 or w_pad > 0:
|
|
437
454
|
if (rotated.shape[0] / rotated.shape[1]) > (h / w):
|
|
438
455
|
w_pad2 = int(rotated.shape[0] * w / h - rotated.shape[1])
|
|
439
|
-
rotated = np.pad(rotated, ((0, 0), (0, w_pad2),
|
|
456
|
+
rotated = np.pad(rotated, ((0, 0), (0, w_pad2), *channels))
|
|
440
457
|
else:
|
|
441
458
|
h_pad2 = int(rotated.shape[1] * h / w - rotated.shape[0])
|
|
442
|
-
rotated = np.pad(rotated, ((0, h_pad2), (0, 0),
|
|
459
|
+
rotated = np.pad(rotated, ((0, h_pad2), (0, 0), *channels))
|
|
443
460
|
|
|
444
461
|
# Analytic crop: project the four content corners through the rotation matrix
|
|
445
462
|
corners = np.array(
|
|
@@ -527,6 +544,8 @@ def extract_crops(img: np.ndarray, boxes: np.ndarray) -> list[np.ndarray]:
|
|
|
527
544
|
_boxes = _boxes.round().astype(int)
|
|
528
545
|
# Add last index
|
|
529
546
|
_boxes[:, 2:] += 1
|
|
547
|
+
# A box starting before the image would slice from its end: crop its visible part instead (empty if none)
|
|
548
|
+
_boxes = np.maximum(_boxes, 0)
|
|
530
549
|
|
|
531
550
|
return [np.ascontiguousarray(img[box[1] : box[3], box[0] : box[2]]) for box in _boxes]
|
|
532
551
|
|
|
@@ -570,6 +589,9 @@ def extract_rcrops(
|
|
|
570
589
|
# Divide the points into left and right
|
|
571
590
|
left_points = box[box[:, 0] < centroid[0]]
|
|
572
591
|
right_points = box[box[:, 0] >= centroid[0]]
|
|
592
|
+
if len(left_points) == 0 or len(right_points) == 0:
|
|
593
|
+
crops.append(np.zeros((0, 0, *img.shape[2:]), dtype=img.dtype))
|
|
594
|
+
continue
|
|
573
595
|
|
|
574
596
|
# Sort the left points according to the y-axis
|
|
575
597
|
left_points = left_points[np.argsort(left_points[:, 1])]
|
doctr/utils/metrics.py
CHANGED
|
@@ -4,10 +4,13 @@
|
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
from collections import Counter
|
|
8
|
+
|
|
7
9
|
import numpy as np
|
|
8
10
|
from anyascii import anyascii
|
|
11
|
+
from rapidfuzz.distance import Levenshtein
|
|
9
12
|
from scipy.optimize import linear_sum_assignment
|
|
10
|
-
from shapely import STRtree, area, intersection, polygons
|
|
13
|
+
from shapely import STRtree, area, convex_hull, intersection, is_valid, polygons
|
|
11
14
|
|
|
12
15
|
__all__ = [
|
|
13
16
|
"TextMatch",
|
|
@@ -19,6 +22,7 @@ __all__ = [
|
|
|
19
22
|
"DetectionMetric",
|
|
20
23
|
"ObjectDetectionMetric",
|
|
21
24
|
"TableCellMetric",
|
|
25
|
+
"FormulaMetric",
|
|
22
26
|
]
|
|
23
27
|
|
|
24
28
|
|
|
@@ -151,6 +155,23 @@ def box_iou(boxes_1: np.ndarray, boxes_2: np.ndarray) -> np.ndarray:
|
|
|
151
155
|
return iou_mat
|
|
152
156
|
|
|
153
157
|
|
|
158
|
+
def _check_gt_polygons(polys: np.ndarray) -> None:
|
|
159
|
+
"""Raise a `ValueError` for ground-truth boxes (N, 4, 2) whose points cross each other, i.e. are not in order.
|
|
160
|
+
|
|
161
|
+
Degenerate boxes (repeated or collinear points) are accepted: their IoU is 0.
|
|
162
|
+
"""
|
|
163
|
+
if polys.ndim != 3 or polys.shape[0] == 0:
|
|
164
|
+
return
|
|
165
|
+
geoms = polygons(polys)
|
|
166
|
+
# An invalid polygon with a non-zero hull area is a real box whose points are out of order
|
|
167
|
+
crossed = np.flatnonzero(~is_valid(geoms) & (area(convex_hull(geoms)) > 0))
|
|
168
|
+
if crossed.size > 0:
|
|
169
|
+
raise ValueError(
|
|
170
|
+
f"Ground truth boxes at indices {crossed.tolist()} are self-intersecting "
|
|
171
|
+
"(points not in TL, TR, BR, BL order); please fix the annotations."
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
154
175
|
def polygon_iou(polys_1: np.ndarray, polys_2: np.ndarray) -> np.ndarray:
|
|
155
176
|
"""Computes the IoU between two sets of rotated bounding boxes
|
|
156
177
|
|
|
@@ -212,7 +233,9 @@ def nms(boxes: np.ndarray, thresh: float = 0.5) -> list[int]:
|
|
|
212
233
|
w = np.maximum(0.0, xx2 - xx1)
|
|
213
234
|
h = np.maximum(0.0, yy2 - yy1)
|
|
214
235
|
inter = w * h
|
|
215
|
-
|
|
236
|
+
union = areas[i] + areas[order[1:]] - inter
|
|
237
|
+
# Two boxes without any area (e.g. collapsed to a point) do not overlap, instead of 0 / 0 suppressing one
|
|
238
|
+
ovr = np.divide(inter, union, out=np.zeros_like(inter), where=union > 0)
|
|
216
239
|
|
|
217
240
|
inds = np.where(ovr <= thresh)[0]
|
|
218
241
|
order = order[inds + 1]
|
|
@@ -272,6 +295,8 @@ class LocalizationConfusion:
|
|
|
272
295
|
gts: a set of relative bounding boxes either of shape (N, 4) or (N, 5) if they are rotated ones
|
|
273
296
|
preds: a set of relative bounding boxes either of shape (M, 4) or (M, 5) if they are rotated ones
|
|
274
297
|
"""
|
|
298
|
+
if self.use_polygons:
|
|
299
|
+
_check_gt_polygons(gts)
|
|
275
300
|
if gts.shape[0] > 0 and preds.shape[0] > 0:
|
|
276
301
|
# Compute IoU
|
|
277
302
|
if self.use_polygons:
|
|
@@ -356,6 +381,8 @@ class TableCellMetric:
|
|
|
356
381
|
pred_cells: predicted cells, shape (M, 4) or (M, 4, 2) when `use_polygons=True`
|
|
357
382
|
pred_logic: predicted logical coordinates, shape (M, 4)
|
|
358
383
|
"""
|
|
384
|
+
if self.use_polygons:
|
|
385
|
+
_check_gt_polygons(gt_cells)
|
|
359
386
|
self.num_gts += gt_cells.shape[0]
|
|
360
387
|
self.num_preds += pred_cells.shape[0]
|
|
361
388
|
if gt_cells.shape[0] == 0 or pred_cells.shape[0] == 0:
|
|
@@ -380,11 +407,10 @@ class TableCellMetric:
|
|
|
380
407
|
"""
|
|
381
408
|
recall = self.matches / self.num_gts if self.num_gts > 0 else None
|
|
382
409
|
precision = self.matches / self.num_preds if self.num_preds > 0 else None
|
|
383
|
-
f1 =
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
else
|
|
387
|
-
)
|
|
410
|
+
f1 = None
|
|
411
|
+
if precision is not None and recall is not None:
|
|
412
|
+
# No match at all gives a precision and a recall of 0, so an F1 of 0
|
|
413
|
+
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
|
|
388
414
|
structure_acc = self.struct_matches / self.matches if self.matches > 0 else None
|
|
389
415
|
return {"recall": recall, "precision": precision, "f1": f1, "structure_acc": structure_acc}
|
|
390
416
|
|
|
@@ -395,6 +421,102 @@ class TableCellMetric:
|
|
|
395
421
|
self.struct_matches = 0
|
|
396
422
|
|
|
397
423
|
|
|
424
|
+
class FormulaMetric:
|
|
425
|
+
r"""Implements formula recognition metrics, computed on LaTeX tokens (cf. :func:`doctr.datasets.tokenize_latex`),
|
|
426
|
+
so they do not depend on the whitespaces of the LaTeX sources.
|
|
427
|
+
|
|
428
|
+
It reports the **exact match** rate (the share of formulas whose token sequences are identical), the **edit
|
|
429
|
+
similarity** (the mean over formulas of :math:`1 - \frac{d(X, Y)}{\max(|X|, |Y|)}` with :math:`d` the
|
|
430
|
+
token-level Levenshtein distance) and the corpus-level **BLEU-4** score (geometric mean of the 1- to 4-gram
|
|
431
|
+
precisions with a brevity penalty, without smoothing).
|
|
432
|
+
|
|
433
|
+
>>> from doctr.utils import FormulaMetric
|
|
434
|
+
>>> metric = FormulaMetric()
|
|
435
|
+
>>> metric.update([r"\frac{a}{b}"], [r"\frac { a } { c }"])
|
|
436
|
+
>>> metric.summary()
|
|
437
|
+
"""
|
|
438
|
+
|
|
439
|
+
max_order: int = 4
|
|
440
|
+
# Scalar accumulators, which can be summed over several processes
|
|
441
|
+
counters: tuple[str, ...] = (
|
|
442
|
+
"exact",
|
|
443
|
+
"edit_similarity",
|
|
444
|
+
"total",
|
|
445
|
+
"pred_len",
|
|
446
|
+
"gt_len",
|
|
447
|
+
*(f"ngram_matches_{n}" for n in range(1, max_order + 1)),
|
|
448
|
+
*(f"ngram_totals_{n}" for n in range(1, max_order + 1)),
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
def __init__(self) -> None:
|
|
452
|
+
self.reset()
|
|
453
|
+
|
|
454
|
+
def update(self, gt: list[str], pred: list[str]) -> None:
|
|
455
|
+
"""Update the state of the metric with new predictions
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
gt: list of ground-truth LaTeX strings
|
|
459
|
+
pred: list of predicted LaTeX strings
|
|
460
|
+
"""
|
|
461
|
+
from doctr.datasets import tokenize_latex
|
|
462
|
+
|
|
463
|
+
if len(gt) != len(pred):
|
|
464
|
+
raise AssertionError("prediction size does not match with ground-truth labels size")
|
|
465
|
+
|
|
466
|
+
for gt_latex, pred_latex in zip(gt, pred):
|
|
467
|
+
gt_tokens, pred_tokens = tokenize_latex(gt_latex), tokenize_latex(pred_latex)
|
|
468
|
+
self.exact += int(gt_tokens == pred_tokens)
|
|
469
|
+
length = max(len(gt_tokens), len(pred_tokens))
|
|
470
|
+
self.edit_similarity += 1 - Levenshtein.distance(gt_tokens, pred_tokens) / length if length > 0 else 1.0
|
|
471
|
+
self.pred_len += len(pred_tokens)
|
|
472
|
+
self.gt_len += len(gt_tokens)
|
|
473
|
+
for n in range(1, self.max_order + 1):
|
|
474
|
+
gt_ngrams = Counter(tuple(gt_tokens[i : i + n]) for i in range(len(gt_tokens) - n + 1))
|
|
475
|
+
pred_ngrams = Counter(tuple(pred_tokens[i : i + n]) for i in range(len(pred_tokens) - n + 1))
|
|
476
|
+
matches = sum((gt_ngrams & pred_ngrams).values())
|
|
477
|
+
setattr(self, f"ngram_matches_{n}", getattr(self, f"ngram_matches_{n}") + matches)
|
|
478
|
+
setattr(
|
|
479
|
+
self, f"ngram_totals_{n}", getattr(self, f"ngram_totals_{n}") + max(len(pred_tokens) - n + 1, 0)
|
|
480
|
+
)
|
|
481
|
+
self.total += len(gt)
|
|
482
|
+
|
|
483
|
+
def summary(self) -> dict[str, float]:
|
|
484
|
+
"""Computes the aggregated metrics
|
|
485
|
+
|
|
486
|
+
Returns:
|
|
487
|
+
a dictionary with the `exact_match` rate, the mean `edit_similarity` and the corpus `bleu` score
|
|
488
|
+
"""
|
|
489
|
+
if self.total == 0:
|
|
490
|
+
raise AssertionError("you need to update the metric before getting the summary")
|
|
491
|
+
|
|
492
|
+
precisions = [
|
|
493
|
+
getattr(self, f"ngram_matches_{n}") / getattr(self, f"ngram_totals_{n}")
|
|
494
|
+
if getattr(self, f"ngram_totals_{n}") > 0
|
|
495
|
+
else 0.0
|
|
496
|
+
for n in range(1, self.max_order + 1)
|
|
497
|
+
]
|
|
498
|
+
if min(precisions) > 0 and self.pred_len > 0:
|
|
499
|
+
brevity_penalty = 1.0 if self.pred_len > self.gt_len else float(np.exp(1 - self.gt_len / self.pred_len))
|
|
500
|
+
bleu = brevity_penalty * float(np.exp(np.mean(np.log(precisions))))
|
|
501
|
+
else:
|
|
502
|
+
bleu = 0.0
|
|
503
|
+
return dict(
|
|
504
|
+
exact_match=self.exact / self.total,
|
|
505
|
+
edit_similarity=self.edit_similarity / self.total,
|
|
506
|
+
bleu=bleu,
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
def reset(self) -> None:
|
|
510
|
+
self.exact = 0
|
|
511
|
+
self.edit_similarity = 0.0
|
|
512
|
+
self.total = 0
|
|
513
|
+
self.pred_len = 0
|
|
514
|
+
self.gt_len = 0
|
|
515
|
+
for n in range(1, self.max_order + 1):
|
|
516
|
+
setattr(self, f"ngram_matches_{n}", 0)
|
|
517
|
+
setattr(self, f"ngram_totals_{n}", 0)
|
|
518
|
+
|
|
519
|
+
|
|
398
520
|
class OCRMetric:
|
|
399
521
|
r"""Implements an end-to-end OCR metric.
|
|
400
522
|
|
|
@@ -460,6 +582,8 @@ class OCRMetric:
|
|
|
460
582
|
gt_labels: a list of N string labels
|
|
461
583
|
pred_labels: a list of M string labels
|
|
462
584
|
"""
|
|
585
|
+
if self.use_polygons:
|
|
586
|
+
_check_gt_polygons(gt_boxes)
|
|
463
587
|
if gt_boxes.shape[0] != len(gt_labels) or pred_boxes.shape[0] != len(pred_labels):
|
|
464
588
|
raise AssertionError(
|
|
465
589
|
"there should be the same number of boxes and string both for the ground truth and the predictions"
|
|
@@ -589,6 +713,8 @@ class DetectionMetric:
|
|
|
589
713
|
gt_labels: an array of class indices of shape (N,)
|
|
590
714
|
pred_labels: an array of class indices of shape (M,)
|
|
591
715
|
"""
|
|
716
|
+
if self.use_polygons:
|
|
717
|
+
_check_gt_polygons(gt_boxes)
|
|
592
718
|
if gt_boxes.shape[0] != gt_labels.shape[0] or pred_boxes.shape[0] != pred_labels.shape[0]:
|
|
593
719
|
raise AssertionError(
|
|
594
720
|
"there should be the same number of boxes and string both for the ground truth and the predictions"
|
|
@@ -661,8 +787,7 @@ class ObjectDetectionMetric:
|
|
|
661
787
|
- :math:`\mathcal{C}` is the set of possible class indices,
|
|
662
788
|
- :math:`S` are confidence scores associated to predictions,
|
|
663
789
|
- :math:`\mathcal{T} = \{0.5, 0.55, \dots, 0.95\}` is the set of IoU thresholds,
|
|
664
|
-
- :math:`AP_t(c)` is the Average Precision for class :math:`c`
|
|
665
|
-
at IoU threshold :math:`t`.
|
|
790
|
+
- :math:`AP_t(c)` is the Average Precision for class :math:`c` at IoU threshold :math:`t`.
|
|
666
791
|
|
|
667
792
|
For a given class and IoU threshold, predictions from all images are
|
|
668
793
|
aggregated and sorted globally by decreasing confidence score.
|
|
@@ -718,6 +843,8 @@ class ObjectDetectionMetric:
|
|
|
718
843
|
pred_labels: np.ndarray,
|
|
719
844
|
pred_scores: np.ndarray,
|
|
720
845
|
) -> None:
|
|
846
|
+
if self.use_polygons:
|
|
847
|
+
_check_gt_polygons(gt_boxes)
|
|
721
848
|
if (
|
|
722
849
|
gt_boxes.shape[0] != gt_labels.shape[0]
|
|
723
850
|
or pred_boxes.shape[0] != pred_labels.shape[0]
|
|
@@ -822,12 +949,13 @@ class ObjectDetectionMetric:
|
|
|
822
949
|
np.expand_dims(pred_box, axis=0),
|
|
823
950
|
)
|
|
824
951
|
|
|
825
|
-
|
|
952
|
+
# Ground truths already matched by a higher-scored detection are not candidates anymore
|
|
953
|
+
ious = np.where(gt_data["matched"], -1.0, iou_mat[:, 0])
|
|
826
954
|
|
|
827
955
|
best_gt = np.argmax(ious)
|
|
828
956
|
best_iou = ious[best_gt]
|
|
829
957
|
|
|
830
|
-
if best_iou >= iou_thresh
|
|
958
|
+
if best_iou >= iou_thresh:
|
|
831
959
|
tp[det_idx] = 1
|
|
832
960
|
gt_data["matched"][best_gt] = True
|
|
833
961
|
else:
|
|
@@ -846,8 +974,10 @@ class ObjectDetectionMetric:
|
|
|
846
974
|
ap_per_iou[float(iou_thresh)] = float(np.mean(class_aps)) if len(class_aps) > 0 else 0.0
|
|
847
975
|
|
|
848
976
|
map_value = float(np.mean(list(ap_per_iou.values())))
|
|
849
|
-
|
|
850
|
-
|
|
977
|
+
# Match the thresholds with a tolerance: user-provided ones may carry floating-point noise
|
|
978
|
+
# (e.g. `np.arange(0.5, 1.0, 0.05)` yields 0.7500000000000002 instead of 0.75)
|
|
979
|
+
ap50 = next((ap for thresh, ap in ap_per_iou.items() if np.isclose(thresh, 0.5)), 0.0)
|
|
980
|
+
ap75 = next((ap for thresh, ap in ap_per_iou.items() if np.isclose(thresh, 0.75)), 0.0)
|
|
851
981
|
|
|
852
982
|
return {
|
|
853
983
|
"mAP@[.5:.95]": map_value,
|
doctr/utils/multithreading.py
CHANGED
|
@@ -6,13 +6,18 @@
|
|
|
6
6
|
|
|
7
7
|
import multiprocessing as mp
|
|
8
8
|
import os
|
|
9
|
-
|
|
9
|
+
import threading
|
|
10
|
+
from collections.abc import Callable, Generator, Iterable, Iterator
|
|
11
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
12
|
+
from itertools import islice
|
|
10
13
|
from multiprocessing.pool import ThreadPool
|
|
11
14
|
from typing import Any
|
|
12
15
|
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
13
18
|
from doctr.file_utils import ENV_VARS_TRUE_VALUES
|
|
14
19
|
|
|
15
|
-
__all__ = ["multithread_exec"]
|
|
20
|
+
__all__ = ["multithread_exec", "chunked", "prefetch", "prefetch_chunks"]
|
|
16
21
|
|
|
17
22
|
|
|
18
23
|
def multithread_exec(func: Callable[[Any], Any], seq: Iterable[Any], threads: int | None = None) -> Iterator[Any]:
|
|
@@ -49,3 +54,118 @@ def multithread_exec(func: Callable[[Any], Any], seq: Iterable[Any], threads: in
|
|
|
49
54
|
# That's why wrapping result in map to return iterator
|
|
50
55
|
results = map(lambda x: x, tp.map(func, items)) # noqa: C417
|
|
51
56
|
return results
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def chunked(seq: Iterable[Any], size: int) -> Iterator[list[Any]]:
|
|
60
|
+
"""Split an iterable into consecutive lists of at most `size` elements, consuming it lazily
|
|
61
|
+
|
|
62
|
+
>>> from doctr.utils.multithreading import chunked
|
|
63
|
+
>>> list(chunked(range(5), 2))
|
|
64
|
+
[[0, 1], [2, 3], [4]]
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
seq: iterable
|
|
68
|
+
size: the maximum number of elements per chunk
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
iterator of chunks
|
|
72
|
+
"""
|
|
73
|
+
if size < 1:
|
|
74
|
+
raise ValueError("the chunk size must be a positive integer")
|
|
75
|
+
iterator = iter(seq)
|
|
76
|
+
while chunk := list(islice(iterator, size)):
|
|
77
|
+
yield chunk
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_EXHAUSTED = object()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def prefetch(seq: Iterable[Any], enabled: bool = True) -> Generator[Any, None, None]:
|
|
84
|
+
"""Iterate over an iterable while producing its next element in a background thread
|
|
85
|
+
|
|
86
|
+
This overlaps the production of the next element (e.g. decoding the next pages of a document) with the
|
|
87
|
+
processing of the current one (e.g. running the models). At most one element is produced ahead, and the
|
|
88
|
+
iterable is only ever advanced by one thread at a time.
|
|
89
|
+
|
|
90
|
+
>>> from doctr.utils.multithreading import prefetch
|
|
91
|
+
>>> for item in prefetch(expensive_generator()):
|
|
92
|
+
... process(item)
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
seq: iterable
|
|
96
|
+
enabled: whether the elements are produced in a background thread
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
generator over the elements of the iterable: closing it waits for the element being produced, if any
|
|
100
|
+
|
|
101
|
+
Notes:
|
|
102
|
+
Prefetching is disabled when 'DOCTR_MULTIPROCESSING_DISABLE' is set to 'TRUE'.
|
|
103
|
+
"""
|
|
104
|
+
if not enabled or os.environ.get("DOCTR_MULTIPROCESSING_DISABLE", "").upper() in ENV_VARS_TRUE_VALUES:
|
|
105
|
+
yield from seq
|
|
106
|
+
return
|
|
107
|
+
|
|
108
|
+
iterator = iter(seq)
|
|
109
|
+
try:
|
|
110
|
+
# On early exit, leaving the context waits for the element being produced, so that the iterable is
|
|
111
|
+
# never closed while it is advanced in the background thread
|
|
112
|
+
with ThreadPoolExecutor(max_workers=1, thread_name_prefix="doctr-prefetch") as executor:
|
|
113
|
+
future = executor.submit(next, iterator, _EXHAUSTED)
|
|
114
|
+
while (item := future.result()) is not _EXHAUSTED:
|
|
115
|
+
future = executor.submit(next, iterator, _EXHAUSTED)
|
|
116
|
+
yield item
|
|
117
|
+
finally:
|
|
118
|
+
close = getattr(iterator, "close", None)
|
|
119
|
+
if callable(close):
|
|
120
|
+
close()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def prefetch_chunks(seq: Iterable[Any], size: int, enabled: bool = True) -> Generator[list[Any], None, None]:
|
|
124
|
+
"""Split an iterable into consecutive lists of at most `size` elements, producing the next chunk in a background
|
|
125
|
+
thread while the current one is processed
|
|
126
|
+
|
|
127
|
+
This is how the predictors consume their inputs: a lazy page source (or any iterator) has its next chunk decoded
|
|
128
|
+
ahead, while in-memory inputs (lists, tuples, arrays) have nothing to decode and are only sliced, without a
|
|
129
|
+
background thread.
|
|
130
|
+
|
|
131
|
+
>>> from doctr.utils.multithreading import prefetch_chunks
|
|
132
|
+
>>> for chunk in prefetch_chunks(lazy_source, 32):
|
|
133
|
+
... process(chunk)
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
seq: iterable
|
|
137
|
+
size: the maximum number of elements per chunk
|
|
138
|
+
enabled: whether the next chunk is produced in a background thread (ignored for in-memory inputs)
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
generator of chunks. Closing it (e.g. when the consumer stops early, or on error) stops producing ahead after
|
|
142
|
+
the element in progress rather than completing a whole chunk, and releases the resources held by the
|
|
143
|
+
iteration over `seq` (e.g. an open PDF).
|
|
144
|
+
|
|
145
|
+
Notes:
|
|
146
|
+
Prefetching is disabled when 'DOCTR_MULTIPROCESSING_DISABLE' is set to 'TRUE'.
|
|
147
|
+
"""
|
|
148
|
+
in_memory = isinstance(seq, (list, tuple, np.ndarray))
|
|
149
|
+
stop = threading.Event()
|
|
150
|
+
|
|
151
|
+
def _until_stopped() -> Iterator[Any]:
|
|
152
|
+
iterator = iter(seq)
|
|
153
|
+
try:
|
|
154
|
+
for item in iterator:
|
|
155
|
+
yield item
|
|
156
|
+
if stop.is_set():
|
|
157
|
+
return
|
|
158
|
+
finally:
|
|
159
|
+
# Release the resources held by the iteration (e.g. an open PDF) as soon as it is over
|
|
160
|
+
close = getattr(iterator, "close", None)
|
|
161
|
+
if callable(close):
|
|
162
|
+
close()
|
|
163
|
+
|
|
164
|
+
chunks = prefetch(chunked(_until_stopped(), size), enabled=enabled and not in_memory)
|
|
165
|
+
try:
|
|
166
|
+
# Not `yield from`: on early exit, it would close `chunks` (waiting for a whole chunk) before `stop` is set
|
|
167
|
+
for chunk in chunks:
|
|
168
|
+
yield chunk
|
|
169
|
+
finally:
|
|
170
|
+
stop.set()
|
|
171
|
+
chunks.close()
|
doctr/utils/visualization.py
CHANGED
|
@@ -42,7 +42,7 @@ def rect_patch(
|
|
|
42
42
|
Returns:
|
|
43
43
|
a rectangular Patch
|
|
44
44
|
"""
|
|
45
|
-
if len(geometry) != 2 or any(not isinstance(elt, tuple) or len(elt) != 2 for elt in geometry):
|
|
45
|
+
if len(geometry) != 2 or any(not isinstance(elt, (tuple, list)) or len(elt) != 2 for elt in geometry):
|
|
46
46
|
raise ValueError("invalid geometry format")
|
|
47
47
|
|
|
48
48
|
# Unpack
|
|
@@ -96,11 +96,13 @@ def polygon_patch(
|
|
|
96
96
|
|
|
97
97
|
# Unpack
|
|
98
98
|
height, width = page_dimensions
|
|
99
|
-
|
|
100
|
-
|
|
99
|
+
if preserve_aspect_ratio:
|
|
100
|
+
width = height = max(height, width)
|
|
101
|
+
# Scale a copy, so that the caller's geometry (e.g. the one of a word) stays relative
|
|
102
|
+
abs_geometry = geometry * (width, height)
|
|
101
103
|
|
|
102
104
|
return patches.Polygon(
|
|
103
|
-
|
|
105
|
+
abs_geometry,
|
|
104
106
|
fill=fill,
|
|
105
107
|
linewidth=linewidth,
|
|
106
108
|
edgecolor=(*color, alpha),
|
|
@@ -124,7 +126,8 @@ def create_obj_patch(
|
|
|
124
126
|
Returns:
|
|
125
127
|
a matplotlib Patch
|
|
126
128
|
"""
|
|
127
|
-
|
|
129
|
+
# A page export read back from a JSON file stores the geometries as lists instead of tuples
|
|
130
|
+
if isinstance(geometry, (tuple, list)):
|
|
128
131
|
if len(geometry) == 2: # straight word BB (2 pts)
|
|
129
132
|
return rect_patch(geometry, page_dimensions, **kwargs)
|
|
130
133
|
elif len(geometry) == 4: # rotated word BB (4 pts)
|
|
@@ -144,8 +147,9 @@ def get_colors(num_colors: int) -> list[tuple[float, float, float]]:
|
|
|
144
147
|
colors: list of generated colors
|
|
145
148
|
"""
|
|
146
149
|
colors = []
|
|
147
|
-
|
|
148
|
-
|
|
150
|
+
# Integer steps give exactly num_colors hues (a float step can add one more, close to 360°, i.e. red again)
|
|
151
|
+
for i in range(num_colors):
|
|
152
|
+
hue = i / num_colors
|
|
149
153
|
lightness = (50 + np.random.rand() * 10) / 100.0
|
|
150
154
|
saturation = (90 + np.random.rand() * 10) / 100.0
|
|
151
155
|
colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))
|
doctr/version.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '
|
|
1
|
+
__version__ = '1.2.0'
|