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.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
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.geometry import Polygon
13
+ from shapely import STRtree, area, convex_hull, intersection, is_valid, polygons
11
14
 
12
15
  __all__ = [
13
16
  "TextMatch",
@@ -17,6 +20,9 @@ __all__ = [
17
20
  "LocalizationConfusion",
18
21
  "OCRMetric",
19
22
  "DetectionMetric",
23
+ "ObjectDetectionMetric",
24
+ "TableCellMetric",
25
+ "FormulaMetric",
20
26
  ]
21
27
 
22
28
 
@@ -144,19 +150,34 @@ def box_iou(boxes_1: np.ndarray, boxes_2: np.ndarray) -> np.ndarray:
144
150
 
145
151
  intersection = np.clip(right - left, 0, np.inf) * np.clip(bot - top, 0, np.inf)
146
152
  union = (r1 - l1) * (b1 - t1) + ((r2 - l2) * (b2 - t2)).T - intersection
147
- iou_mat = intersection / union
153
+ iou_mat = np.divide(intersection, union, out=np.zeros_like(intersection), where=union > 0)
148
154
 
149
155
  return iou_mat
150
156
 
151
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
+
152
175
  def polygon_iou(polys_1: np.ndarray, polys_2: np.ndarray) -> np.ndarray:
153
176
  """Computes the IoU between two sets of rotated bounding boxes
154
177
 
155
178
  Args:
156
179
  polys_1: rotated bounding boxes of shape (N, 4, 2)
157
180
  polys_2: rotated bounding boxes of shape (M, 4, 2)
158
- mask_shape: spatial shape of the intermediate masks
159
- use_broadcasting: if set to True, leverage broadcasting speedup by consuming more memory
160
181
 
161
182
  Returns:
162
183
  the IoU matrix of shape (N, M)
@@ -164,17 +185,20 @@ def polygon_iou(polys_1: np.ndarray, polys_2: np.ndarray) -> np.ndarray:
164
185
  if polys_1.ndim != 3 or polys_2.ndim != 3:
165
186
  raise AssertionError("expects boxes to be in format (N, 4, 2)")
166
187
 
167
- iou_mat = np.zeros((polys_1.shape[0], polys_2.shape[0]), dtype=np.float32)
168
-
169
- shapely_polys_1 = [Polygon(poly) for poly in polys_1]
170
- shapely_polys_2 = [Polygon(poly) for poly in polys_2]
188
+ n, m = polys_1.shape[0], polys_2.shape[0]
189
+ if n == 0 or m == 0:
190
+ return np.zeros((n, m), dtype=np.float32)
171
191
 
172
- for i, poly1 in enumerate(shapely_polys_1):
173
- for j, poly2 in enumerate(shapely_polys_2):
174
- intersection_area = poly1.intersection(poly2).area
175
- union_area = poly1.area + poly2.area - intersection_area
176
- iou_mat[i, j] = intersection_area / union_area
192
+ geoms_1 = polygons(polys_1)
193
+ geoms_2 = polygons(polys_2)
177
194
 
195
+ iou_mat = np.zeros((n, m), dtype=np.float32)
196
+ idcs_1, idcs_2 = STRtree(geoms_2).query(geoms_1)
197
+ if idcs_1.size > 0:
198
+ # Compute intersections and areas for the candidate pairs only
199
+ intersections = area(intersection(geoms_1[idcs_1], geoms_2[idcs_2]))
200
+ unions = area(geoms_1)[idcs_1] + area(geoms_2)[idcs_2] - intersections
201
+ iou_mat[idcs_1, idcs_2] = np.divide(intersections, unions, out=np.zeros_like(intersections), where=unions > 0)
178
202
  return iou_mat
179
203
 
180
204
 
@@ -209,7 +233,9 @@ def nms(boxes: np.ndarray, thresh: float = 0.5) -> list[int]:
209
233
  w = np.maximum(0.0, xx2 - xx1)
210
234
  h = np.maximum(0.0, yy2 - yy1)
211
235
  inter = w * h
212
- ovr = inter / (areas[i] + areas[order[1:]] - inter)
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)
213
239
 
214
240
  inds = np.where(ovr <= thresh)[0]
215
241
  order = order[inds + 1]
@@ -269,7 +295,9 @@ class LocalizationConfusion:
269
295
  gts: a set of relative bounding boxes either of shape (N, 4) or (N, 5) if they are rotated ones
270
296
  preds: a set of relative bounding boxes either of shape (M, 4) or (M, 5) if they are rotated ones
271
297
  """
272
- if preds.shape[0] > 0:
298
+ if self.use_polygons:
299
+ _check_gt_polygons(gts)
300
+ if gts.shape[0] > 0 and preds.shape[0] > 0:
273
301
  # Compute IoU
274
302
  if self.use_polygons:
275
303
  iou_mat = polygon_iou(gts, preds)
@@ -309,6 +337,186 @@ class LocalizationConfusion:
309
337
  self.tot_iou = 0.0
310
338
 
311
339
 
340
+ class TableCellMetric:
341
+ r"""Implements a table-structure-recognition metric.
342
+
343
+ Predicted cells are matched to ground-truth cells by maximising the total IoU (Hungarian assignment); a pair
344
+ counts as a match when its IoU is at least `iou_thresh`. From the matches it reports cell-detection recall,
345
+ precision, F1 and the **structure accuracy** (the fraction of matched cells whose logical coordinates
346
+ `[start_col, end_col, start_row, end_row]` exactly equal the ground-truth ones).
347
+
348
+ >>> import numpy as np
349
+ >>> from doctr.utils import TableCellMetric
350
+ >>> metric = TableCellMetric(iou_thresh=0.5)
351
+ >>> gt = np.array([[0, 0, 1, 1]], dtype=np.float32)
352
+ >>> metric.update(gt, np.array([[0, 0, 0, 0]]), gt, np.array([[0, 0, 0, 0]]))
353
+ >>> metric.summary()
354
+
355
+ Args:
356
+ iou_thresh: minimum IoU for a predicted/ground-truth cell pair to be considered a match
357
+ use_polygons: if set to True, predictions and targets will be expected to have polygon format
358
+ """
359
+
360
+ def __init__(
361
+ self,
362
+ iou_thresh: float = 0.5,
363
+ use_polygons: bool = False,
364
+ ) -> None:
365
+ self.iou_thresh = iou_thresh
366
+ self.use_polygons = use_polygons
367
+ self.reset()
368
+
369
+ def update(
370
+ self,
371
+ gt_cells: np.ndarray,
372
+ gt_logic: np.ndarray,
373
+ pred_cells: np.ndarray,
374
+ pred_logic: np.ndarray,
375
+ ) -> None:
376
+ """Update the metric with one sample.
377
+
378
+ Args:
379
+ gt_cells: ground-truth cells, shape (N, 4) or (N, 4, 2) when `use_polygons=True`
380
+ gt_logic: ground-truth logical coordinates, shape (N, 4)
381
+ pred_cells: predicted cells, shape (M, 4) or (M, 4, 2) when `use_polygons=True`
382
+ pred_logic: predicted logical coordinates, shape (M, 4)
383
+ """
384
+ if self.use_polygons:
385
+ _check_gt_polygons(gt_cells)
386
+ self.num_gts += gt_cells.shape[0]
387
+ self.num_preds += pred_cells.shape[0]
388
+ if gt_cells.shape[0] == 0 or pred_cells.shape[0] == 0:
389
+ return
390
+
391
+ if self.use_polygons:
392
+ iou_mat = polygon_iou(gt_cells, pred_cells)
393
+ else:
394
+ iou_mat = box_iou(gt_cells, pred_cells)
395
+ gt_idx, pred_idx = linear_sum_assignment(-iou_mat)
396
+ for gi, pi in zip(gt_idx, pred_idx):
397
+ if iou_mat[gi, pi] >= self.iou_thresh:
398
+ self.matches += 1
399
+ if np.array_equal(np.asarray(gt_logic[gi]), np.asarray(pred_logic[pi])):
400
+ self.struct_matches += 1
401
+
402
+ def summary(self) -> dict[str, float | None]:
403
+ """Compute the aggregated metrics.
404
+
405
+ Returns:
406
+ a dict with `recall`, `precision`, `f1` (cell detection) and `structure_acc`
407
+ """
408
+ recall = self.matches / self.num_gts if self.num_gts > 0 else None
409
+ precision = self.matches / self.num_preds if self.num_preds > 0 else None
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
414
+ structure_acc = self.struct_matches / self.matches if self.matches > 0 else None
415
+ return {"recall": recall, "precision": precision, "f1": f1, "structure_acc": structure_acc}
416
+
417
+ def reset(self) -> None:
418
+ self.num_gts = 0
419
+ self.num_preds = 0
420
+ self.matches = 0
421
+ self.struct_matches = 0
422
+
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
+
312
520
  class OCRMetric:
313
521
  r"""Implements an end-to-end OCR metric.
314
522
 
@@ -374,13 +582,14 @@ class OCRMetric:
374
582
  gt_labels: a list of N string labels
375
583
  pred_labels: a list of M string labels
376
584
  """
585
+ if self.use_polygons:
586
+ _check_gt_polygons(gt_boxes)
377
587
  if gt_boxes.shape[0] != len(gt_labels) or pred_boxes.shape[0] != len(pred_labels):
378
588
  raise AssertionError(
379
589
  "there should be the same number of boxes and string both for the ground truth and the predictions"
380
590
  )
381
591
 
382
- # Compute IoU
383
- if pred_boxes.shape[0] > 0:
592
+ if gt_boxes.shape[0] > 0 and pred_boxes.shape[0] > 0:
384
593
  if self.use_polygons:
385
594
  iou_mat = polygon_iou(gt_boxes, pred_boxes)
386
595
  else:
@@ -504,13 +713,14 @@ class DetectionMetric:
504
713
  gt_labels: an array of class indices of shape (N,)
505
714
  pred_labels: an array of class indices of shape (M,)
506
715
  """
716
+ if self.use_polygons:
717
+ _check_gt_polygons(gt_boxes)
507
718
  if gt_boxes.shape[0] != gt_labels.shape[0] or pred_boxes.shape[0] != pred_labels.shape[0]:
508
719
  raise AssertionError(
509
720
  "there should be the same number of boxes and string both for the ground truth and the predictions"
510
721
  )
511
722
 
512
- # Compute IoU
513
- if pred_boxes.shape[0] > 0:
723
+ if gt_boxes.shape[0] > 0 and pred_boxes.shape[0] > 0:
514
724
  if self.use_polygons:
515
725
  iou_mat = polygon_iou(gt_boxes, pred_boxes)
516
726
  else:
@@ -549,3 +759,255 @@ class DetectionMetric:
549
759
  self.num_preds = 0
550
760
  self.tot_iou = 0.0
551
761
  self.num_matches = 0
762
+
763
+
764
+ class ObjectDetectionMetric:
765
+ r"""Implements a COCO-style object detection metric (mAP@[.5:.95]) inspired by the COCO evaluation protocol.
766
+
767
+ The aggregated metrics are computed as follows:
768
+
769
+ .. math::
770
+
771
+ \forall (B, C) \in \mathcal{B}^N \times \mathcal{C}^N,
772
+ \forall (\hat{B}, \hat{C}, S) \in \mathcal{B}^M \times \mathcal{C}^M \times \mathbb{R}^M, \\
773
+
774
+ AP_t(C) =
775
+ \frac{1}{101}
776
+ \sum\limits_{r \in \{0, 0.01, \dots, 1.0\}}
777
+ \max_{\tilde{r} \geq r} Precision_t(\tilde{r}, C) \\
778
+
779
+ mAP@[.5:.95] =
780
+ \frac{1}{|\mathcal{T}|}
781
+ \sum\limits_{t \in \mathcal{T}}
782
+ \frac{1}{|\mathcal{C}|}
783
+ \sum\limits_{c \in \mathcal{C}} AP_t(c)
784
+
785
+ where:
786
+ - :math:`\mathcal{B}` is the set of possible bounding boxes,
787
+ - :math:`\mathcal{C}` is the set of possible class indices,
788
+ - :math:`S` are confidence scores associated to predictions,
789
+ - :math:`\mathcal{T} = \{0.5, 0.55, \dots, 0.95\}` is the set of IoU thresholds,
790
+ - :math:`AP_t(c)` is the Average Precision for class :math:`c` at IoU threshold :math:`t`.
791
+
792
+ For a given class and IoU threshold, predictions from all images are
793
+ aggregated and sorted globally by decreasing confidence score.
794
+
795
+ Each prediction is greedily matched to the unmatched ground-truth box
796
+ with the highest IoU, provided that:
797
+
798
+ - the IoU is greater than or equal to the threshold,
799
+ - the ground-truth box has not already been matched.
800
+
801
+ True positives and false positives are accumulated to build a
802
+ precision-recall curve.
803
+
804
+ Average Precision is computed using the COCO 101-point interpolated
805
+ precision-recall curve.
806
+
807
+ >>> import numpy as np
808
+ >>> from doctr.utils import ObjectDetectionMetric
809
+ >>> metric = ObjectDetectionMetric()
810
+ >>> metric.update(
811
+ ... np.asarray([[0, 0, 100, 100]]),
812
+ ... np.asarray([[0, 0, 80, 80], [120, 120, 200, 200]]),
813
+ ... np.asarray([0]),
814
+ ... np.asarray([0, 1]),
815
+ ... np.asarray([0.9, 0.3])
816
+ ... )
817
+ >>> metric.summary()
818
+
819
+ Args:
820
+ iou_thresholds: sequence of IoU thresholds used to compute the metric
821
+ (defaults to np.arange(0.5, 1.0, 0.05))
822
+ num_classes: total number of classes. If None, inferred from data
823
+ use_polygons: if set to True, predictions and targets will be expected
824
+ to have rotated format
825
+ """
826
+
827
+ def __init__(
828
+ self,
829
+ iou_thresholds: np.ndarray | None = None,
830
+ num_classes: int | None = None,
831
+ use_polygons: bool = False,
832
+ ) -> None:
833
+ self.iou_thresholds = iou_thresholds if iou_thresholds is not None else np.round(np.arange(0.5, 1.0, 0.05), 2)
834
+ self.num_classes = num_classes
835
+ self.use_polygons = use_polygons
836
+ self.reset()
837
+
838
+ def update(
839
+ self,
840
+ gt_boxes: np.ndarray,
841
+ pred_boxes: np.ndarray,
842
+ gt_labels: np.ndarray,
843
+ pred_labels: np.ndarray,
844
+ pred_scores: np.ndarray,
845
+ ) -> None:
846
+ if self.use_polygons:
847
+ _check_gt_polygons(gt_boxes)
848
+ if (
849
+ gt_boxes.shape[0] != gt_labels.shape[0]
850
+ or pred_boxes.shape[0] != pred_labels.shape[0]
851
+ or pred_boxes.shape[0] != pred_scores.shape[0]
852
+ ):
853
+ raise AssertionError("Mismatch between boxes, labels, scores")
854
+
855
+ self._gts.append({"boxes": gt_boxes, "labels": gt_labels})
856
+ self._preds.append({"boxes": pred_boxes, "labels": pred_labels, "scores": pred_scores})
857
+
858
+ def summary(self) -> dict[str, float | dict[float, float]]:
859
+ """Computes the aggregated metrics
860
+
861
+ Returns:
862
+ a dictionary with the mAP@[.5:.95], AP@[.5], AP@[.75] and AP per IoU threshold
863
+ """
864
+ if len(self._gts) == 0:
865
+ raise AssertionError("No samples added")
866
+
867
+ # Determine classes
868
+ if self.num_classes is None:
869
+ labels = []
870
+ for g in self._gts:
871
+ labels.extend(g["labels"].tolist())
872
+ for p in self._preds:
873
+ labels.extend(p["labels"].tolist())
874
+ classes = np.unique(labels)
875
+ else:
876
+ classes = np.arange(self.num_classes)
877
+
878
+ ap_per_iou = {}
879
+
880
+ for iou_thresh in self.iou_thresholds:
881
+ class_aps = []
882
+
883
+ for c in classes:
884
+ # Collect GTs per image
885
+ gt_by_image = {}
886
+ total_gt = 0
887
+
888
+ for img_idx, gt in enumerate(self._gts):
889
+ mask = gt["labels"] == c
890
+ gt_boxes = gt["boxes"][mask]
891
+
892
+ gt_by_image[img_idx] = {
893
+ "boxes": gt_boxes,
894
+ "matched": np.zeros(len(gt_boxes), dtype=bool),
895
+ }
896
+
897
+ total_gt += len(gt_boxes)
898
+
899
+ if total_gt == 0:
900
+ continue
901
+
902
+ # Collect all detections globally
903
+ detections = []
904
+
905
+ for img_idx, pred in enumerate(self._preds):
906
+ mask = pred["labels"] == c
907
+
908
+ pred_boxes = pred["boxes"][mask]
909
+ pred_scores = pred["scores"][mask]
910
+
911
+ for box, score in zip(pred_boxes, pred_scores):
912
+ detections.append({
913
+ "image_id": img_idx,
914
+ "box": box,
915
+ "score": float(score),
916
+ })
917
+
918
+ if len(detections) == 0:
919
+ class_aps.append(0.0)
920
+ continue
921
+
922
+ # Global sorting COCO-style
923
+ detections.sort(key=lambda x: -x["score"])
924
+
925
+ tp = np.zeros(len(detections))
926
+ fp = np.zeros(len(detections))
927
+
928
+ # Evaluate detections
929
+ for det_idx, det in enumerate(detections):
930
+ img_idx = det["image_id"]
931
+ pred_box = det["box"]
932
+
933
+ gt_data = gt_by_image[img_idx]
934
+ gt_boxes = gt_data["boxes"]
935
+
936
+ if len(gt_boxes) == 0:
937
+ fp[det_idx] = 1
938
+ continue
939
+
940
+ # Compute IoUs
941
+ if self.use_polygons:
942
+ iou_mat = polygon_iou(
943
+ gt_boxes,
944
+ np.expand_dims(pred_box, axis=0),
945
+ )
946
+ else:
947
+ iou_mat = box_iou(
948
+ gt_boxes,
949
+ np.expand_dims(pred_box, axis=0),
950
+ )
951
+
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])
954
+
955
+ best_gt = np.argmax(ious)
956
+ best_iou = ious[best_gt]
957
+
958
+ if best_iou >= iou_thresh:
959
+ tp[det_idx] = 1
960
+ gt_data["matched"][best_gt] = True
961
+ else:
962
+ fp[det_idx] = 1
963
+
964
+ # Precision / Recall
965
+ tp_cum = np.cumsum(tp)
966
+ fp_cum = np.cumsum(fp)
967
+
968
+ recall = tp_cum / total_gt
969
+ precision = tp_cum / np.maximum(tp_cum + fp_cum, 1e-8)
970
+
971
+ ap = self._compute_ap(recall, precision)
972
+ class_aps.append(ap)
973
+
974
+ ap_per_iou[float(iou_thresh)] = float(np.mean(class_aps)) if len(class_aps) > 0 else 0.0
975
+
976
+ map_value = float(np.mean(list(ap_per_iou.values())))
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)
981
+
982
+ return {
983
+ "mAP@[.5:.95]": map_value,
984
+ "AP@[.5]": ap50,
985
+ "AP@[.75]": ap75,
986
+ "AP_per_IoU": ap_per_iou,
987
+ }
988
+
989
+ def _compute_ap(self, recall: np.ndarray, precision: np.ndarray) -> float:
990
+ """Computes the Average Precision using the 101-point interpolation method from COCO
991
+
992
+ Args:
993
+ recall: array of recall values
994
+ precision: array of precision values
995
+
996
+ Returns:
997
+ the Average Precision score
998
+ """
999
+ # 101-point interpolation as per COCO
1000
+ precision = np.maximum.accumulate(precision[::-1])[::-1]
1001
+
1002
+ recall_levels = np.linspace(0, 1, 101)
1003
+ precisions = np.zeros_like(recall_levels)
1004
+
1005
+ for i, r in enumerate(recall_levels):
1006
+ p = precision[recall >= r]
1007
+ precisions[i] = np.max(p) if p.size > 0 else 0.0
1008
+
1009
+ return float(np.mean(precisions))
1010
+
1011
+ def reset(self):
1012
+ self._gts = []
1013
+ self._preds = []