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.
Files changed (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/io/__init__.py CHANGED
@@ -1,6 +1,8 @@
1
1
  from .elements import *
2
2
  from .exporters import *
3
+ from .figures import *
3
4
  from .html import *
4
5
  from .image import *
5
6
  from .pdf import *
6
7
  from .reader import *
8
+ from .sources import *
doctr/io/elements.py CHANGED
@@ -3,6 +3,8 @@
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
 
6
+ from collections.abc import Callable
7
+ from functools import cmp_to_key
6
8
  from typing import Any
7
9
 
8
10
  import numpy as np
@@ -33,6 +35,7 @@ __all__ = [
33
35
  "LayoutElement",
34
36
  "TableCell",
35
37
  "Table",
38
+ "Formula",
36
39
  ]
37
40
 
38
41
 
@@ -41,6 +44,50 @@ def _empty_page_image(page: np.ndarray | None) -> np.ndarray:
41
44
  return page if page is not None else np.zeros((0, 0, 3), dtype=np.uint8)
42
45
 
43
46
 
47
+ # A page image, or a zero-argument callable decoding it on demand. Predictions made on a lazy page source
48
+ # (cf. `doctr.io.PageSource`) only keep a reference to their page, so that their memory footprint does not grow
49
+ # with the image of every page of a long document.
50
+ PageImage = np.ndarray | Callable[[], np.ndarray]
51
+
52
+
53
+ def _get_page_image(self: Any) -> np.ndarray:
54
+ state = self.__dict__
55
+ if "_page" in state:
56
+ image = state["_page"]
57
+ elif "page" in state:
58
+ # Pages pickled by a previous release store their image under `page` (a plain instance attribute back then)
59
+ image = state["page"]
60
+ else:
61
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute 'page'")
62
+ return image() if callable(image) else image
63
+
64
+
65
+ def _set_page_image(self: Any, image: PageImage) -> None:
66
+ # Drop the legacy entry of a page unpickled from a previous release, so that it cannot shadow the new image
67
+ self.__dict__.pop("page", None)
68
+ self._page = image
69
+
70
+
71
+ _page_image_property = property(
72
+ _get_page_image,
73
+ _set_page_image,
74
+ doc="the page image as a numpy array (decoded on access when the page was predicted from a lazy page source)",
75
+ )
76
+
77
+
78
+ def _reading_order(a: "TableCell", b: "TableCell") -> int:
79
+ """Compare 2 table cells in reading order: cells overlapping by half their height are on the same line and read
80
+ left to right, the other ones top to bottom."""
81
+ (ax0, ay0), (ax1, ay1) = (pts := np.asarray(a.geometry).reshape(-1, 2)).min(axis=0), pts.max(axis=0)
82
+ (bx0, by0), (bx1, by1) = (pts := np.asarray(b.geometry).reshape(-1, 2)).min(axis=0), pts.max(axis=0)
83
+ overlap = min(ay1, by1) - max(ay0, by0)
84
+ if overlap >= 0.5 * min(ay1 - ay0, by1 - by0):
85
+ delta = (ax0 + ax1) - (bx0 + bx1)
86
+ else:
87
+ delta = (ay0 + ay1) - (by0 + by1)
88
+ return int(np.sign(delta))
89
+
90
+
44
91
  class Element(NestedObject):
45
92
  """Implements an abstract document element with exporting and text rendering capabilities"""
46
93
 
@@ -186,13 +233,15 @@ class TableCell(Element):
186
233
 
187
234
  Args:
188
235
  value: the text content of the cell (words assigned to the cell, joined together)
189
- confidence: the mean recognition confidence of the words assigned to the cell
236
+ confidence: the mean recognition confidence of the words assigned to the cell (its `objectness_score` if
237
+ no word is assigned to it)
190
238
  geometry: bounding box of the cell in format ((xmin, ymin), (xmax, ymax)) or a (4, 2) polygon,
191
239
  with coordinates relative to the page's size
192
240
  row_start: index of the first row spanned by the cell (0-indexed)
193
241
  row_end: index of the last row spanned by the cell (0-indexed, inclusive)
194
242
  col_start: index of the first column spanned by the cell (0-indexed)
195
243
  col_end: index of the last column spanned by the cell (0-indexed, inclusive)
244
+ objectness_score: the score of the cell predicted by the table structure model, None if unknown
196
245
  """
197
246
 
198
247
  _exported_keys: list[str] = [
@@ -203,6 +252,7 @@ class TableCell(Element):
203
252
  "row_end",
204
253
  "col_start",
205
254
  "col_end",
255
+ "objectness_score",
206
256
  ]
207
257
  _children_names: list[str] = []
208
258
 
@@ -215,6 +265,7 @@ class TableCell(Element):
215
265
  row_end: int,
216
266
  col_start: int,
217
267
  col_end: int,
268
+ objectness_score: float | None = None,
218
269
  ) -> None:
219
270
  super().__init__()
220
271
  self.value = value
@@ -224,6 +275,7 @@ class TableCell(Element):
224
275
  self.row_end = row_end
225
276
  self.col_start = col_start
226
277
  self.col_end = col_end
278
+ self.objectness_score = objectness_score
227
279
 
228
280
  @property
229
281
  def row_span(self) -> int:
@@ -244,8 +296,9 @@ class TableCell(Element):
244
296
 
245
297
  @classmethod
246
298
  def from_dict(cls, save_dict: dict[str, Any], **kwargs):
247
- kwargs = {k: save_dict[k] for k in cls._exported_keys}
248
- return cls(**kwargs)
299
+ # `objectness_score` is missing from the exports of earlier versions
300
+ kwargs = {k: save_dict[k] for k in cls._exported_keys if k != "objectness_score"}
301
+ return cls(**kwargs, objectness_score=save_dict.get("objectness_score"))
249
302
 
250
303
 
251
304
  class Table(Element):
@@ -260,7 +313,7 @@ class Table(Element):
260
313
  num_rows: number of rows of the table
261
314
  num_cols: number of columns of the table
262
315
  geometry: bounding box enclosing the whole table, with coordinates relative to the page's size
263
- confidence: the confidence of the table structure prediction
316
+ confidence: the confidence of the table structure prediction (mean of the `objectness_score` of its cells)
264
317
  """
265
318
 
266
319
  _exported_keys: list[str] = ["geometry", "num_rows", "num_cols", "confidence"]
@@ -285,16 +338,18 @@ class Table(Element):
285
338
  """Return the table content as a dense `num_rows` x `num_cols` grid of strings.
286
339
 
287
340
  Cells spanning several rows/columns have their value placed at their top-left position; the
288
- remaining positions they span are left empty. The result is directly loadable into pandas via
341
+ remaining positions they span are left empty. Cells sharing the same top-left position have their
342
+ values joined in reading order, so no text is lost. The result is directly loadable into pandas via
289
343
  `pd.DataFrame(table.to_grid())`.
290
344
 
291
345
  Returns:
292
346
  a list of `num_rows` lists, each of length `num_cols`
293
347
  """
294
348
  grid = [["" for _ in range(self.num_cols)] for _ in range(self.num_rows)]
295
- for cell in self.cells:
296
- if 0 <= cell.row_start < self.num_rows and 0 <= cell.col_start < self.num_cols:
297
- grid[cell.row_start][cell.col_start] = cell.value
349
+ for cell in sorted(self.cells, key=cmp_to_key(_reading_order)):
350
+ if 0 <= cell.row_start < self.num_rows and 0 <= cell.col_start < self.num_cols and cell.value:
351
+ current = grid[cell.row_start][cell.col_start]
352
+ grid[cell.row_start][cell.col_start] = f"{current} {cell.value}" if current else cell.value
298
353
  return grid
299
354
 
300
355
  def render(self, row_break: str = "\n", col_break: str = "\t") -> str:
@@ -311,6 +366,50 @@ class Table(Element):
311
366
  return cls(**kwargs)
312
367
 
313
368
 
369
+ class Formula(Element):
370
+ r"""Implements a mathematical formula recognized on a page as LaTeX
371
+
372
+ The formula regions are located by the layout model and kept out of the regular text recognition, so the
373
+ formula is not duplicated in the `blocks` of the page.
374
+
375
+ Args:
376
+ value: the LaTeX source of the formula (tokens separated by spaces, e.g. `\frac { a } { b }`), without
377
+ math delimiters
378
+ confidence: the confidence of the formula recognition
379
+ geometry: bounding box of the formula in format ((xmin, ymin), (xmax, ymax)) or a (4, 2) polygon, with
380
+ coordinates relative to the page's size
381
+ objectness_score: the score of the formula region predicted by the layout model, None if unknown
382
+ """
383
+
384
+ _exported_keys: list[str] = ["geometry", "value", "confidence", "objectness_score"]
385
+ _children_names: list[str] = []
386
+
387
+ def __init__(
388
+ self,
389
+ value: str,
390
+ confidence: float,
391
+ geometry: BoundingBox | np.ndarray,
392
+ objectness_score: float | None = None,
393
+ ) -> None:
394
+ super().__init__()
395
+ self.value = value
396
+ self.confidence = confidence
397
+ self.geometry = geometry
398
+ self.objectness_score = objectness_score
399
+
400
+ def render(self) -> str:
401
+ """Renders the LaTeX source of the formula"""
402
+ return self.value
403
+
404
+ def extra_repr(self) -> str:
405
+ return f"value='{self.value}', confidence={self.confidence:.2}"
406
+
407
+ @classmethod
408
+ def from_dict(cls, save_dict: dict[str, Any], **kwargs):
409
+ kwargs = {k: save_dict[k] for k in cls._exported_keys if k != "objectness_score"}
410
+ return cls(**kwargs, objectness_score=save_dict.get("objectness_score"))
411
+
412
+
314
413
  class Line(Element):
315
414
  """Implements a line element as a collection of words
316
415
 
@@ -331,6 +430,8 @@ class Line(Element):
331
430
  geometry: BoundingBox | np.ndarray | None = None,
332
431
  objectness_score: float | None = None,
333
432
  ) -> None:
433
+ if geometry is None and not words:
434
+ raise ValueError("the geometry of a line without any word can not be resolved, please pass it")
334
435
  # Compute the objectness score of the line
335
436
  if objectness_score is None:
336
437
  objectness_score = float(np.mean([w.objectness_score for w in words]))
@@ -386,21 +487,29 @@ class Block(Element):
386
487
 
387
488
  def __init__(
388
489
  self,
389
- lines: list[Line] = [],
390
- artefacts: list[Artefact] = [],
490
+ lines: list[Line] | None = None,
491
+ artefacts: list[Artefact] | None = None,
391
492
  geometry: BoundingBox | np.ndarray | None = None,
392
493
  objectness_score: float | None = None,
393
494
  ) -> None:
394
- # Compute the objectness score of the line
495
+ if lines is None:
496
+ lines = []
497
+ if artefacts is None:
498
+ artefacts = []
499
+ if geometry is None and not lines and not artefacts:
500
+ raise ValueError("the geometry of a block without any line or artefact can not be resolved, please pass it")
501
+ # Compute the objectness score of the block
395
502
  if objectness_score is None:
396
- objectness_score = float(np.mean([w.objectness_score for line in lines for w in line.words]))
503
+ # A block without any word (only artefacts) takes the confidence of its artefacts, instead of NaN
504
+ scores = [w.objectness_score for line in lines for w in line.words] or [a.confidence for a in artefacts]
505
+ objectness_score = float(np.mean(scores))
397
506
  # Resolve the geometry using the smallest enclosing bounding box
398
507
  if geometry is None:
399
508
  line_boxes = [word.geometry for line in lines for word in line.words]
400
509
  artefact_boxes = [artefact.geometry for artefact in artefacts]
401
- box_resolution_fn = (
402
- resolve_enclosing_rbbox if isinstance(lines[0].geometry, np.ndarray) else resolve_enclosing_bbox
403
- )
510
+ # Check whether this is a rotated or straight box (geometries read back from an export are lists)
511
+ first_geometry = lines[0].geometry if lines else artefacts[0].geometry
512
+ box_resolution_fn = resolve_enclosing_rbbox if len(first_geometry) == 4 else resolve_enclosing_bbox
404
513
  geometry = box_resolution_fn(line_boxes + artefact_boxes) # type: ignore
405
514
 
406
515
  super().__init__(lines=lines, artefacts=artefacts)
@@ -425,7 +534,7 @@ class Page(PageExportsMixin, Element):
425
534
  """Implements a page element as a collection of blocks
426
535
 
427
536
  Args:
428
- page: image encoded as a numpy array in uint8
537
+ page: image encoded as a numpy array in uint8, or a callable returning it (decoded on access)
429
538
  blocks: list of block elements
430
539
  page_idx: the index of the page in the input raw document
431
540
  dimensions: the page size in pixels in format (height, width)
@@ -433,17 +542,21 @@ class Page(PageExportsMixin, Element):
433
542
  language: a dictionary with the language value and confidence of the prediction
434
543
  layout: optional list of layout regions detected on the page
435
544
  tables: optional list of tables recognized on the page. Words assigned to a table are removed from `blocks`.
545
+ formulas: optional list of formulas recognized on the page. Formula regions are not part of `blocks`.
436
546
  """
437
547
 
438
548
  _exported_keys: list[str] = ["page_idx", "dimensions", "orientation", "language"]
439
- _children_names: list[str] = ["blocks", "layout", "tables"]
549
+ _children_names: list[str] = ["blocks", "layout", "tables", "formulas"]
440
550
  blocks: list[Block] = []
441
551
  layout: list[LayoutElement] = []
442
552
  tables: list[Table] = []
553
+ formulas: list[Formula] = []
554
+
555
+ page = _page_image_property
443
556
 
444
557
  def __init__(
445
558
  self,
446
- page: np.ndarray,
559
+ page: PageImage,
447
560
  blocks: list[Block],
448
561
  page_idx: int,
449
562
  dimensions: tuple[int, int],
@@ -451,11 +564,13 @@ class Page(PageExportsMixin, Element):
451
564
  language: dict[str, Any] | None = None,
452
565
  layout: list[LayoutElement] | None = None,
453
566
  tables: list[Table] | None = None,
567
+ formulas: list[Formula] | None = None,
454
568
  ) -> None:
455
569
  super().__init__(
456
570
  blocks=blocks,
457
571
  layout=layout if layout is not None else [],
458
572
  tables=tables if tables is not None else [],
573
+ formulas=formulas if formulas is not None else [],
459
574
  )
460
575
  self.page = page
461
576
  self.page_idx = page_idx
@@ -507,6 +622,7 @@ class Page(PageExportsMixin, Element):
507
622
  "blocks": [Block.from_dict(block_dict) for block_dict in save_dict["blocks"]],
508
623
  "layout": [LayoutElement.from_dict(region_dict) for region_dict in save_dict.get("layout", [])],
509
624
  "tables": [Table.from_dict(table_dict) for table_dict in save_dict.get("tables", [])],
625
+ "formulas": [Formula.from_dict(formula_dict) for formula_dict in save_dict.get("formulas", [])],
510
626
  })
511
627
  # The page image is not part of the export: pass it back explicitly to restore a fully usable page
512
628
  return cls(page=_empty_page_image(page), **_kwargs)
@@ -517,7 +633,7 @@ class KIEPage(KIEPageExportsMixin, Element):
517
633
 
518
634
  Args:
519
635
  predictions: Dictionary with list of block elements for each detection class
520
- page: image encoded as a numpy array in uint8
636
+ page: image encoded as a numpy array in uint8, or a callable returning it (decoded on access)
521
637
  page_idx: the index of the page in the input raw document
522
638
  dimensions: the page size in pixels in format (height, width)
523
639
  orientation: a dictionary with the value of the rotation angle in degress and confidence of the prediction
@@ -530,9 +646,11 @@ class KIEPage(KIEPageExportsMixin, Element):
530
646
  predictions: dict[str, list[Prediction]] = {}
531
647
  layout: list[LayoutElement] = []
532
648
 
649
+ page = _page_image_property
650
+
533
651
  def __init__(
534
652
  self,
535
- page: np.ndarray,
653
+ page: PageImage,
536
654
  predictions: dict[str, list[Prediction]],
537
655
  page_idx: int,
538
656
  dimensions: tuple[int, int],