python-doctr 1.0.0__py3-none-any.whl → 1.1.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 (138) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -0
  3. doctr/contrib/artefacts.py +1 -1
  4. doctr/contrib/base.py +1 -1
  5. doctr/datasets/__init__.py +2 -0
  6. doctr/datasets/coco_text.py +5 -3
  7. doctr/datasets/cord.py +3 -2
  8. doctr/datasets/datasets/base.py +13 -25
  9. doctr/datasets/datasets/pytorch.py +15 -5
  10. doctr/datasets/detection.py +3 -2
  11. doctr/datasets/doc_artefacts.py +3 -2
  12. doctr/datasets/funsd.py +3 -2
  13. doctr/datasets/generator/base.py +6 -5
  14. doctr/datasets/generator/pytorch.py +5 -6
  15. doctr/datasets/ic03.py +4 -3
  16. doctr/datasets/ic13.py +5 -3
  17. doctr/datasets/iiit5k.py +3 -2
  18. doctr/datasets/iiithws.py +5 -3
  19. doctr/datasets/imgur5k.py +5 -3
  20. doctr/datasets/layout.py +123 -0
  21. doctr/datasets/mjsynth.py +5 -3
  22. doctr/datasets/ocr.py +3 -2
  23. doctr/datasets/orientation.py +3 -2
  24. doctr/datasets/recognition.py +3 -2
  25. doctr/datasets/sroie.py +3 -2
  26. doctr/datasets/svhn.py +3 -2
  27. doctr/datasets/svt.py +4 -3
  28. doctr/datasets/synthtext.py +3 -2
  29. doctr/datasets/table_structure.py +97 -0
  30. doctr/datasets/utils.py +15 -6
  31. doctr/datasets/vocabs.py +3 -1
  32. doctr/datasets/wildreceipt.py +5 -3
  33. doctr/file_utils.py +4 -2
  34. doctr/io/__init__.py +1 -0
  35. doctr/io/elements.py +253 -261
  36. doctr/io/exporters.py +1275 -0
  37. doctr/io/html.py +1 -1
  38. doctr/io/image/base.py +4 -3
  39. doctr/io/image/pytorch.py +6 -4
  40. doctr/io/pdf.py +1 -1
  41. doctr/io/reader.py +1 -1
  42. doctr/models/__init__.py +2 -0
  43. doctr/models/_utils.py +111 -25
  44. doctr/models/builder.py +533 -62
  45. doctr/models/classification/__init__.py +2 -0
  46. doctr/models/classification/magc_resnet/pytorch.py +2 -2
  47. doctr/models/classification/mobilenet/pytorch.py +7 -7
  48. doctr/models/classification/predictor/pytorch.py +7 -3
  49. doctr/models/classification/resnet/pytorch.py +6 -6
  50. doctr/models/classification/starnet/__init__.py +1 -0
  51. doctr/models/classification/starnet/pytorch.py +202 -0
  52. doctr/models/classification/textnet/pytorch.py +7 -6
  53. doctr/models/classification/vgg/pytorch.py +4 -3
  54. doctr/models/classification/vip/layers/pytorch.py +5 -5
  55. doctr/models/classification/vip/pytorch.py +5 -5
  56. doctr/models/classification/vit/pytorch.py +4 -4
  57. doctr/models/classification/vit_det/__init__.py +1 -0
  58. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  60. doctr/models/classification/vit_det/pytorch.py +346 -0
  61. doctr/models/classification/zoo.py +4 -1
  62. doctr/models/core.py +1 -1
  63. doctr/models/detection/_utils/base.py +24 -8
  64. doctr/models/detection/_utils/pytorch.py +1 -1
  65. doctr/models/detection/core.py +34 -19
  66. doctr/models/detection/differentiable_binarization/base.py +7 -5
  67. doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
  68. doctr/models/detection/fast/base.py +6 -2
  69. doctr/models/detection/fast/pytorch.py +4 -4
  70. doctr/models/detection/linknet/base.py +6 -2
  71. doctr/models/detection/linknet/pytorch.py +4 -4
  72. doctr/models/detection/predictor/pytorch.py +4 -3
  73. doctr/models/detection/zoo.py +3 -3
  74. doctr/models/factory/hub.py +72 -52
  75. doctr/models/kie_predictor/base.py +17 -2
  76. doctr/models/kie_predictor/pytorch.py +42 -11
  77. doctr/models/layout/__init__.py +2 -0
  78. doctr/models/layout/lw_detr/__init__.py +1 -0
  79. doctr/models/layout/lw_detr/base.py +309 -0
  80. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  81. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  82. doctr/models/layout/lw_detr/pytorch.py +838 -0
  83. doctr/models/layout/predictor/__init__.py +1 -0
  84. doctr/models/layout/predictor/pytorch.py +82 -0
  85. doctr/models/layout/zoo.py +90 -0
  86. doctr/models/modules/layers/pytorch.py +140 -4
  87. doctr/models/modules/transformer/pytorch.py +1 -1
  88. doctr/models/modules/vision_transformer/pytorch.py +1 -1
  89. doctr/models/predictor/base.py +138 -16
  90. doctr/models/predictor/pytorch.py +151 -9
  91. doctr/models/preprocessor/pytorch.py +78 -23
  92. doctr/models/reading_order/__init__.py +1 -0
  93. doctr/models/reading_order/base.py +667 -0
  94. doctr/models/recognition/core.py +1 -1
  95. doctr/models/recognition/crnn/pytorch.py +6 -8
  96. doctr/models/recognition/master/base.py +1 -1
  97. doctr/models/recognition/master/pytorch.py +7 -8
  98. doctr/models/recognition/parseq/base.py +1 -1
  99. doctr/models/recognition/parseq/pytorch.py +5 -5
  100. doctr/models/recognition/predictor/_utils.py +1 -1
  101. doctr/models/recognition/predictor/pytorch.py +2 -2
  102. doctr/models/recognition/sar/pytorch.py +2 -2
  103. doctr/models/recognition/utils.py +9 -11
  104. doctr/models/recognition/viptr/pytorch.py +4 -6
  105. doctr/models/recognition/vitstr/base.py +1 -1
  106. doctr/models/recognition/vitstr/pytorch.py +6 -6
  107. doctr/models/recognition/zoo.py +6 -7
  108. doctr/models/table_structure/__init__.py +2 -0
  109. doctr/models/table_structure/predictor/__init__.py +1 -0
  110. doctr/models/table_structure/predictor/pytorch.py +80 -0
  111. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  112. doctr/models/table_structure/tablecenternet/base.py +485 -0
  113. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  114. doctr/models/table_structure/zoo.py +82 -0
  115. doctr/models/utils/pytorch.py +316 -16
  116. doctr/models/zoo.py +91 -3
  117. doctr/transforms/functional/base.py +3 -2
  118. doctr/transforms/functional/pytorch.py +1 -1
  119. doctr/transforms/modules/base.py +248 -83
  120. doctr/transforms/modules/pytorch.py +213 -74
  121. doctr/utils/common_types.py +22 -2
  122. doctr/utils/data.py +5 -4
  123. doctr/utils/fonts.py +56 -17
  124. doctr/utils/geometry.py +136 -19
  125. doctr/utils/metrics.py +351 -19
  126. doctr/utils/multithreading.py +6 -3
  127. doctr/utils/reconstitution.py +697 -133
  128. doctr/utils/repr.py +1 -1
  129. doctr/utils/visualization.py +63 -4
  130. doctr/version.py +1 -1
  131. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
  132. python_doctr-1.1.0.dist-info/RECORD +179 -0
  133. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  134. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  135. python_doctr-1.0.0.dist-info/RECORD +0 -149
  136. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  137. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  138. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
doctr/io/elements.py CHANGED
@@ -1,21 +1,14 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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
6
  from typing import Any
7
7
 
8
- from defusedxml import defuse_stdlib
9
-
10
- defuse_stdlib()
11
- from xml.etree import ElementTree as ET
12
- from xml.etree.ElementTree import Element as ETElement
13
- from xml.etree.ElementTree import SubElement
14
-
15
8
  import numpy as np
16
9
 
17
- import doctr
18
10
  from doctr.file_utils import requires_package
11
+ from doctr.io.exporters import DocumentExportsMixin, KIEPageExportsMixin, PageExportsMixin, to_json_safe
19
12
  from doctr.utils.common_types import BoundingBox
20
13
  from doctr.utils.geometry import resolve_enclosing_bbox, resolve_enclosing_rbbox
21
14
  from doctr.utils.reconstitution import synthesize_kie_page, synthesize_page
@@ -23,10 +16,29 @@ from doctr.utils.repr import NestedObject
23
16
 
24
17
  try: # optional dependency for visualization
25
18
  from doctr.utils.visualization import visualize_kie_page, visualize_page
26
- except ModuleNotFoundError:
19
+ except ModuleNotFoundError: # pragma: no cover
27
20
  pass
28
21
 
29
- __all__ = ["Element", "Word", "Artefact", "Line", "Prediction", "Block", "Page", "KIEPage", "Document"]
22
+ __all__ = [
23
+ "Element",
24
+ "Word",
25
+ "Artefact",
26
+ "Line",
27
+ "Prediction",
28
+ "Block",
29
+ "Page",
30
+ "KIEPage",
31
+ "KIEDocument",
32
+ "Document",
33
+ "LayoutElement",
34
+ "TableCell",
35
+ "Table",
36
+ ]
37
+
38
+
39
+ def _empty_page_image(page: np.ndarray | None) -> np.ndarray:
40
+ """Return the given page image, or an empty placeholder when the page was restored from an export."""
41
+ return page if page is not None else np.zeros((0, 0, 3), dtype=np.uint8)
30
42
 
31
43
 
32
44
  class Element(NestedObject):
@@ -44,7 +56,7 @@ class Element(NestedObject):
44
56
 
45
57
  def export(self) -> dict[str, Any]:
46
58
  """Exports the object into a nested dict format"""
47
- export_dict = {k: getattr(self, k) for k in self._exported_keys}
59
+ export_dict = {k: to_json_safe(getattr(self, k)) for k in self._exported_keys}
48
60
  for children_name in self._children_names:
49
61
  if children_name in ["predictions"]:
50
62
  export_dict[children_name] = {
@@ -70,7 +82,7 @@ class Word(Element):
70
82
  value: the text string of the word
71
83
  confidence: the confidence associated with the text prediction
72
84
  geometry: bounding box of the word in format ((xmin, ymin), (xmax, ymax)) where coordinates are relative to
73
- the page's size
85
+ the page's size
74
86
  objectness_score: the objectness score of the detection
75
87
  crop_orientation: the general orientation of the crop in degrees and its confidence
76
88
  """
@@ -126,18 +138,179 @@ class Artefact(Element):
126
138
  self.confidence = confidence
127
139
 
128
140
  def render(self) -> str:
129
- """Renders the full text of the element"""
130
- return f"[{self.type.upper()}]"
141
+ """Renders the region as a tag"""
142
+ return f"<[{self.type.upper()}]>"
131
143
 
132
144
  def extra_repr(self) -> str:
133
145
  return f"type='{self.type}', confidence={self.confidence:.2}"
134
146
 
147
+ @classmethod
148
+ def from_dict(cls, save_dict: dict[str, Any], **kwargs):
149
+ return cls(artefact_type=save_dict["type"], confidence=save_dict["confidence"], geometry=save_dict["geometry"])
150
+
151
+
152
+ class LayoutElement(Element):
153
+ """Implements a layout region predicted by a layout detection model
154
+
155
+ Args:
156
+ layout_type: the predicted region class (e.g. 'Title', 'Text', 'Table', 'Page-header')
157
+ confidence: the confidence of the region prediction
158
+ geometry: bounding box of the word in format ((xmin, ymin), (xmax, ymax)) where coordinates are relative to
159
+ the page's size
160
+ """
161
+
162
+ _exported_keys: list[str] = ["geometry", "type", "confidence"]
163
+ _children_names: list[str] = []
164
+
165
+ def __init__(self, layout_type: str, confidence: float, geometry: BoundingBox | np.ndarray) -> None:
166
+ super().__init__()
167
+ self.geometry = geometry
168
+ self.type = layout_type
169
+ self.confidence = confidence
170
+
171
+ def render(self) -> str:
172
+ """Renders the region as a tag"""
173
+ return f"<[{self.type.upper()}]>"
174
+
175
+ def extra_repr(self) -> str:
176
+ return f"type='{self.type}', confidence={self.confidence:.2}"
177
+
178
+ @classmethod
179
+ def from_dict(cls, save_dict: dict[str, Any], **kwargs):
180
+ kwargs = {k: save_dict[k] for k in cls._exported_keys}
181
+ return cls(layout_type=kwargs["type"], confidence=kwargs["confidence"], geometry=kwargs["geometry"])
182
+
183
+
184
+ class TableCell(Element):
185
+ """Implements a single cell of a recognized table
186
+
187
+ Args:
188
+ 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
190
+ geometry: bounding box of the cell in format ((xmin, ymin), (xmax, ymax)) or a (4, 2) polygon,
191
+ with coordinates relative to the page's size
192
+ row_start: index of the first row spanned by the cell (0-indexed)
193
+ row_end: index of the last row spanned by the cell (0-indexed, inclusive)
194
+ col_start: index of the first column spanned by the cell (0-indexed)
195
+ col_end: index of the last column spanned by the cell (0-indexed, inclusive)
196
+ """
197
+
198
+ _exported_keys: list[str] = [
199
+ "geometry",
200
+ "value",
201
+ "confidence",
202
+ "row_start",
203
+ "row_end",
204
+ "col_start",
205
+ "col_end",
206
+ ]
207
+ _children_names: list[str] = []
208
+
209
+ def __init__(
210
+ self,
211
+ value: str,
212
+ confidence: float,
213
+ geometry: BoundingBox | np.ndarray,
214
+ row_start: int,
215
+ row_end: int,
216
+ col_start: int,
217
+ col_end: int,
218
+ ) -> None:
219
+ super().__init__()
220
+ self.value = value
221
+ self.confidence = confidence
222
+ self.geometry = geometry
223
+ self.row_start = row_start
224
+ self.row_end = row_end
225
+ self.col_start = col_start
226
+ self.col_end = col_end
227
+
228
+ @property
229
+ def row_span(self) -> int:
230
+ """Number of rows spanned by the cell"""
231
+ return self.row_end - self.row_start + 1
232
+
233
+ @property
234
+ def col_span(self) -> int:
235
+ """Number of columns spanned by the cell"""
236
+ return self.col_end - self.col_start + 1
237
+
238
+ def render(self) -> str:
239
+ """Renders the cell text"""
240
+ return self.value
241
+
242
+ def extra_repr(self) -> str:
243
+ return f"value='{self.value}', rows=({self.row_start}, {self.row_end}), cols=({self.col_start}, {self.col_end})"
244
+
135
245
  @classmethod
136
246
  def from_dict(cls, save_dict: dict[str, Any], **kwargs):
137
247
  kwargs = {k: save_dict[k] for k in cls._exported_keys}
138
248
  return cls(**kwargs)
139
249
 
140
250
 
251
+ class Table(Element):
252
+ """Implements a table recognized on a page as a grid of cells
253
+
254
+ The recognized text of the words falling inside the table is regrouped here and removed from the
255
+ regular `blocks` output of the page, so it is not duplicated. The structured content can be loaded
256
+ directly into pandas, e.g. `pd.DataFrame(table.to_grid())`.
257
+
258
+ Args:
259
+ cells: list of `TableCell` objects composing the table
260
+ num_rows: number of rows of the table
261
+ num_cols: number of columns of the table
262
+ geometry: bounding box enclosing the whole table, with coordinates relative to the page's size
263
+ confidence: the confidence of the table structure prediction
264
+ """
265
+
266
+ _exported_keys: list[str] = ["geometry", "num_rows", "num_cols", "confidence"]
267
+ _children_names: list[str] = ["cells"]
268
+ cells: list[TableCell] = []
269
+
270
+ def __init__(
271
+ self,
272
+ cells: list[TableCell],
273
+ num_rows: int,
274
+ num_cols: int,
275
+ geometry: BoundingBox | np.ndarray,
276
+ confidence: float = 1.0,
277
+ ) -> None:
278
+ super().__init__(cells=cells)
279
+ self.num_rows = num_rows
280
+ self.num_cols = num_cols
281
+ self.geometry = geometry
282
+ self.confidence = confidence
283
+
284
+ def to_grid(self) -> list[list[str]]:
285
+ """Return the table content as a dense `num_rows` x `num_cols` grid of strings.
286
+
287
+ 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
289
+ `pd.DataFrame(table.to_grid())`.
290
+
291
+ Returns:
292
+ a list of `num_rows` lists, each of length `num_cols`
293
+ """
294
+ 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
298
+ return grid
299
+
300
+ def render(self, row_break: str = "\n", col_break: str = "\t") -> str:
301
+ """Renders the table as plain text (tab-separated values)"""
302
+ return row_break.join(col_break.join(row) for row in self.to_grid())
303
+
304
+ def extra_repr(self) -> str:
305
+ return f"num_rows={self.num_rows}, num_cols={self.num_cols}, confidence={self.confidence:.2}"
306
+
307
+ @classmethod
308
+ def from_dict(cls, save_dict: dict[str, Any], **kwargs):
309
+ kwargs = {k: save_dict[k] for k in cls._exported_keys}
310
+ kwargs["cells"] = [TableCell.from_dict(cell) for cell in save_dict["cells"]]
311
+ return cls(**kwargs)
312
+
313
+
141
314
  class Line(Element):
142
315
  """Implements a line element as a collection of words
143
316
 
@@ -248,7 +421,7 @@ class Block(Element):
248
421
  return cls(**kwargs)
249
422
 
250
423
 
251
- class Page(Element):
424
+ class Page(PageExportsMixin, Element):
252
425
  """Implements a page element as a collection of blocks
253
426
 
254
427
  Args:
@@ -258,11 +431,15 @@ class Page(Element):
258
431
  dimensions: the page size in pixels in format (height, width)
259
432
  orientation: a dictionary with the value of the rotation angle in degress and confidence of the prediction
260
433
  language: a dictionary with the language value and confidence of the prediction
434
+ layout: optional list of layout regions detected on the page
435
+ tables: optional list of tables recognized on the page. Words assigned to a table are removed from `blocks`.
261
436
  """
262
437
 
263
438
  _exported_keys: list[str] = ["page_idx", "dimensions", "orientation", "language"]
264
- _children_names: list[str] = ["blocks"]
439
+ _children_names: list[str] = ["blocks", "layout", "tables"]
265
440
  blocks: list[Block] = []
441
+ layout: list[LayoutElement] = []
442
+ tables: list[Table] = []
266
443
 
267
444
  def __init__(
268
445
  self,
@@ -272,18 +449,20 @@ class Page(Element):
272
449
  dimensions: tuple[int, int],
273
450
  orientation: dict[str, Any] | None = None,
274
451
  language: dict[str, Any] | None = None,
452
+ layout: list[LayoutElement] | None = None,
453
+ tables: list[Table] | None = None,
275
454
  ) -> None:
276
- super().__init__(blocks=blocks)
455
+ super().__init__(
456
+ blocks=blocks,
457
+ layout=layout if layout is not None else [],
458
+ tables=tables if tables is not None else [],
459
+ )
277
460
  self.page = page
278
461
  self.page_idx = page_idx
279
462
  self.dimensions = dimensions
280
463
  self.orientation = orientation if isinstance(orientation, dict) else dict(value=None, confidence=None)
281
464
  self.language = language if isinstance(language, dict) else dict(value=None, confidence=None)
282
465
 
283
- def render(self, block_break: str = "\n\n") -> str:
284
- """Renders the full text of the element"""
285
- return block_break.join(b.render() for b in self.blocks)
286
-
287
466
  def extra_repr(self) -> str:
288
467
  return f"dimensions={self.dimensions}"
289
468
 
@@ -294,12 +473,20 @@ class Page(Element):
294
473
  interactive: whether the display should be interactive
295
474
  preserve_aspect_ratio: pass True if you passed True to the predictor
296
475
  **kwargs: additional keyword arguments passed to the matplotlib.pyplot.show method
476
+ (e.g. `display_layout=False` to hide detected layout regions)
297
477
  """
298
478
  requires_package("matplotlib", "`.show()` requires matplotlib & mplcursors installed")
299
479
  requires_package("mplcursors", "`.show()` requires matplotlib & mplcursors installed")
300
480
  import matplotlib.pyplot as plt
301
481
 
302
- visualize_page(self.export(), self.page, interactive=interactive, preserve_aspect_ratio=preserve_aspect_ratio)
482
+ show_kwargs = {k: kwargs.pop(k) for k in ("words_only", "display_artefacts", "display_layout") if k in kwargs}
483
+ visualize_page(
484
+ self.export(),
485
+ self.page,
486
+ interactive=interactive,
487
+ preserve_aspect_ratio=preserve_aspect_ratio,
488
+ **show_kwargs,
489
+ )
303
490
  plt.show(**kwargs)
304
491
 
305
492
  def synthesize(self, **kwargs) -> np.ndarray:
@@ -313,118 +500,19 @@ class Page(Element):
313
500
  """
314
501
  return synthesize_page(self.export(), **kwargs)
315
502
 
316
- def export_as_xml(self, file_title: str = "docTR - XML export (hOCR)") -> tuple[bytes, ET.ElementTree]:
317
- """Export the page as XML (hOCR-format)
318
- convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
319
-
320
- Args:
321
- file_title: the title of the XML file
322
-
323
- Returns:
324
- a tuple of the XML byte string, and its ElementTree
325
- """
326
- p_idx = self.page_idx
327
- block_count: int = 1
328
- line_count: int = 1
329
- word_count: int = 1
330
- height, width = self.dimensions
331
- language = self.language if "language" in self.language.keys() else "en"
332
- # Create the XML root element
333
- page_hocr = ETElement("html", attrib={"xmlns": "http://www.w3.org/1999/xhtml", "xml:lang": str(language)})
334
- # Create the header / SubElements of the root element
335
- head = SubElement(page_hocr, "head")
336
- SubElement(head, "title").text = file_title
337
- SubElement(head, "meta", attrib={"http-equiv": "Content-Type", "content": "text/html; charset=utf-8"})
338
- SubElement(
339
- head,
340
- "meta",
341
- attrib={"name": "ocr-system", "content": f"python-doctr {doctr.__version__}"}, # type: ignore[attr-defined]
342
- )
343
- SubElement(
344
- head,
345
- "meta",
346
- attrib={"name": "ocr-capabilities", "content": "ocr_page ocr_carea ocr_par ocr_line ocrx_word"},
347
- )
348
- # Create the body
349
- body = SubElement(page_hocr, "body")
350
- page_div = SubElement(
351
- body,
352
- "div",
353
- attrib={
354
- "class": "ocr_page",
355
- "id": f"page_{p_idx + 1}",
356
- "title": f"image; bbox 0 0 {width} {height}; ppageno 0",
357
- },
358
- )
359
- # iterate over the blocks / lines / words and create the XML elements in body line by line with the attributes
360
- for block in self.blocks:
361
- if len(block.geometry) != 2:
362
- raise TypeError("XML export is only available for straight bounding boxes for now.")
363
- (xmin, ymin), (xmax, ymax) = block.geometry
364
- block_div = SubElement(
365
- page_div,
366
- "div",
367
- attrib={
368
- "class": "ocr_carea",
369
- "id": f"block_{block_count}",
370
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
371
- {int(round(xmax * width))} {int(round(ymax * height))}",
372
- },
373
- )
374
- paragraph = SubElement(
375
- block_div,
376
- "p",
377
- attrib={
378
- "class": "ocr_par",
379
- "id": f"par_{block_count}",
380
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
381
- {int(round(xmax * width))} {int(round(ymax * height))}",
382
- },
383
- )
384
- block_count += 1
385
- for line in block.lines:
386
- (xmin, ymin), (xmax, ymax) = line.geometry
387
- # NOTE: baseline, x_size, x_descenders, x_ascenders is currently initalized to 0
388
- line_span = SubElement(
389
- paragraph,
390
- "span",
391
- attrib={
392
- "class": "ocr_line",
393
- "id": f"line_{line_count}",
394
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
395
- {int(round(xmax * width))} {int(round(ymax * height))}; \
396
- baseline 0 0; x_size 0; x_descenders 0; x_ascenders 0",
397
- },
398
- )
399
- line_count += 1
400
- for word in line.words:
401
- (xmin, ymin), (xmax, ymax) = word.geometry
402
- conf = word.confidence
403
- word_div = SubElement(
404
- line_span,
405
- "span",
406
- attrib={
407
- "class": "ocrx_word",
408
- "id": f"word_{word_count}",
409
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
410
- {int(round(xmax * width))} {int(round(ymax * height))}; \
411
- x_wconf {int(round(conf * 100))}",
412
- },
413
- )
414
- # set the text
415
- word_div.text = word.value
416
- word_count += 1
417
-
418
- return (ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr))
419
-
420
503
  @classmethod
421
- def from_dict(cls, save_dict: dict[str, Any], **kwargs):
422
- kwargs = {k: save_dict[k] for k in cls._exported_keys}
423
- kwargs.update({"blocks": [Block.from_dict(block_dict) for block_dict in save_dict["blocks"]]})
424
- return cls(**kwargs)
504
+ def from_dict(cls, save_dict: dict[str, Any], page: np.ndarray | None = None, **kwargs):
505
+ _kwargs: dict[str, Any] = {k: save_dict[k] for k in cls._exported_keys}
506
+ _kwargs.update({
507
+ "blocks": [Block.from_dict(block_dict) for block_dict in save_dict["blocks"]],
508
+ "layout": [LayoutElement.from_dict(region_dict) for region_dict in save_dict.get("layout", [])],
509
+ "tables": [Table.from_dict(table_dict) for table_dict in save_dict.get("tables", [])],
510
+ })
511
+ # The page image is not part of the export: pass it back explicitly to restore a fully usable page
512
+ return cls(page=_empty_page_image(page), **_kwargs)
425
513
 
426
514
 
427
- class KIEPage(Element):
515
+ class KIEPage(KIEPageExportsMixin, Element):
428
516
  """Implements a KIE page element as a collection of predictions
429
517
 
430
518
  Args:
@@ -434,11 +522,13 @@ class KIEPage(Element):
434
522
  dimensions: the page size in pixels in format (height, width)
435
523
  orientation: a dictionary with the value of the rotation angle in degress and confidence of the prediction
436
524
  language: a dictionary with the language value and confidence of the prediction
525
+ layout: optional list of layout regions detected on the page
437
526
  """
438
527
 
439
528
  _exported_keys: list[str] = ["page_idx", "dimensions", "orientation", "language"]
440
- _children_names: list[str] = ["predictions"]
529
+ _children_names: list[str] = ["predictions", "layout"]
441
530
  predictions: dict[str, list[Prediction]] = {}
531
+ layout: list[LayoutElement] = []
442
532
 
443
533
  def __init__(
444
534
  self,
@@ -448,20 +538,15 @@ class KIEPage(Element):
448
538
  dimensions: tuple[int, int],
449
539
  orientation: dict[str, Any] | None = None,
450
540
  language: dict[str, Any] | None = None,
541
+ layout: list[LayoutElement] | None = None,
451
542
  ) -> None:
452
- super().__init__(predictions=predictions)
543
+ super().__init__(predictions=predictions, layout=layout if layout is not None else [])
453
544
  self.page = page
454
545
  self.page_idx = page_idx
455
546
  self.dimensions = dimensions
456
547
  self.orientation = orientation if isinstance(orientation, dict) else dict(value=None, confidence=None)
457
548
  self.language = language if isinstance(language, dict) else dict(value=None, confidence=None)
458
549
 
459
- def render(self, prediction_break: str = "\n\n") -> str:
460
- """Renders the full text of the element"""
461
- return prediction_break.join(
462
- f"{class_name}: {p.render()}" for class_name, predictions in self.predictions.items() for p in predictions
463
- )
464
-
465
550
  def extra_repr(self) -> str:
466
551
  return f"dimensions={self.dimensions}"
467
552
 
@@ -477,8 +562,13 @@ class KIEPage(Element):
477
562
  requires_package("mplcursors", "`.show()` requires matplotlib & mplcursors installed")
478
563
  import matplotlib.pyplot as plt
479
564
 
565
+ show_kwargs = {k: kwargs.pop(k) for k in ("words_only", "display_artefacts", "display_layout") if k in kwargs}
480
566
  visualize_kie_page(
481
- self.export(), self.page, interactive=interactive, preserve_aspect_ratio=preserve_aspect_ratio
567
+ self.export(),
568
+ self.page,
569
+ interactive=interactive,
570
+ preserve_aspect_ratio=preserve_aspect_ratio,
571
+ **show_kwargs,
482
572
  )
483
573
  plt.show(**kwargs)
484
574
 
@@ -493,112 +583,21 @@ class KIEPage(Element):
493
583
  """
494
584
  return synthesize_kie_page(self.export(), **kwargs)
495
585
 
496
- def export_as_xml(self, file_title: str = "docTR - XML export (hOCR)") -> tuple[bytes, ET.ElementTree]:
497
- """Export the page as XML (hOCR-format)
498
- convention: https://github.com/kba/hocr-spec/blob/master/1.2/spec.md
499
-
500
- Args:
501
- file_title: the title of the XML file
502
-
503
- Returns:
504
- a tuple of the XML byte string, and its ElementTree
505
- """
506
- p_idx = self.page_idx
507
- prediction_count: int = 1
508
- height, width = self.dimensions
509
- language = self.language if "language" in self.language.keys() else "en"
510
- # Create the XML root element
511
- page_hocr = ETElement("html", attrib={"xmlns": "http://www.w3.org/1999/xhtml", "xml:lang": str(language)})
512
- # Create the header / SubElements of the root element
513
- head = SubElement(page_hocr, "head")
514
- SubElement(head, "title").text = file_title
515
- SubElement(head, "meta", attrib={"http-equiv": "Content-Type", "content": "text/html; charset=utf-8"})
516
- SubElement(
517
- head,
518
- "meta",
519
- attrib={"name": "ocr-system", "content": f"python-doctr {doctr.__version__}"}, # type: ignore[attr-defined]
520
- )
521
- SubElement(
522
- head,
523
- "meta",
524
- attrib={"name": "ocr-capabilities", "content": "ocr_page ocr_carea ocr_par ocr_line ocrx_word"},
525
- )
526
- # Create the body
527
- body = SubElement(page_hocr, "body")
528
- SubElement(
529
- body,
530
- "div",
531
- attrib={
532
- "class": "ocr_page",
533
- "id": f"page_{p_idx + 1}",
534
- "title": f"image; bbox 0 0 {width} {height}; ppageno 0",
535
- },
536
- )
537
- # iterate over the blocks / lines / words and create the XML elements in body line by line with the attributes
538
- for class_name, predictions in self.predictions.items():
539
- for prediction in predictions:
540
- if len(prediction.geometry) != 2:
541
- raise TypeError("XML export is only available for straight bounding boxes for now.")
542
- (xmin, ymin), (xmax, ymax) = prediction.geometry
543
- prediction_div = SubElement(
544
- body,
545
- "div",
546
- attrib={
547
- "class": "ocr_carea",
548
- "id": f"{class_name}_prediction_{prediction_count}",
549
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
550
- {int(round(xmax * width))} {int(round(ymax * height))}",
551
- },
552
- )
553
- # NOTE: ocr_par, ocr_line and ocrx_word are the same because the KIE predictions contain only words
554
- # This is a workaround to make it PDF/A compatible
555
- par_div = SubElement(
556
- prediction_div,
557
- "p",
558
- attrib={
559
- "class": "ocr_par",
560
- "id": f"{class_name}_par_{prediction_count}",
561
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
562
- {int(round(xmax * width))} {int(round(ymax * height))}",
563
- },
564
- )
565
- line_span = SubElement(
566
- par_div,
567
- "span",
568
- attrib={
569
- "class": "ocr_line",
570
- "id": f"{class_name}_line_{prediction_count}",
571
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
572
- {int(round(xmax * width))} {int(round(ymax * height))}; \
573
- baseline 0 0; x_size 0; x_descenders 0; x_ascenders 0",
574
- },
575
- )
576
- word_div = SubElement(
577
- line_span,
578
- "span",
579
- attrib={
580
- "class": "ocrx_word",
581
- "id": f"{class_name}_word_{prediction_count}",
582
- "title": f"bbox {int(round(xmin * width))} {int(round(ymin * height))} \
583
- {int(round(xmax * width))} {int(round(ymax * height))}; \
584
- x_wconf {int(round(prediction.confidence * 100))}",
585
- },
586
- )
587
- word_div.text = prediction.value
588
- prediction_count += 1
589
-
590
- return ET.tostring(page_hocr, encoding="utf-8", method="xml"), ET.ElementTree(page_hocr)
591
-
592
586
  @classmethod
593
- def from_dict(cls, save_dict: dict[str, Any], **kwargs):
594
- kwargs = {k: save_dict[k] for k in cls._exported_keys}
595
- kwargs.update({
596
- "predictions": [Prediction.from_dict(predictions_dict) for predictions_dict in save_dict["predictions"]]
587
+ def from_dict(cls, save_dict: dict[str, Any], page: np.ndarray | None = None, **kwargs):
588
+ _kwargs: dict[str, Any] = {k: save_dict[k] for k in cls._exported_keys}
589
+ _kwargs.update({
590
+ "predictions": {
591
+ class_name: [Prediction.from_dict(pred) for pred in preds]
592
+ for class_name, preds in save_dict["predictions"].items()
593
+ },
594
+ "layout": [LayoutElement.from_dict(region_dict) for region_dict in save_dict.get("layout", [])],
597
595
  })
598
- return cls(**kwargs)
596
+ # The page image is not part of the export: pass it back explicitly to restore a fully usable page
597
+ return cls(page=_empty_page_image(page), **_kwargs)
599
598
 
600
599
 
601
- class Document(Element):
600
+ class Document(DocumentExportsMixin, Element):
602
601
  """Implements a document element as a collection of pages
603
602
 
604
603
  Args:
@@ -614,10 +613,6 @@ class Document(Element):
614
613
  ) -> None:
615
614
  super().__init__(pages=pages)
616
615
 
617
- def render(self, page_break: str = "\n\n\n\n") -> str:
618
- """Renders the full text of the element"""
619
- return page_break.join(p.render() for p in self.pages)
620
-
621
616
  def show(self, **kwargs) -> None:
622
617
  """Overlay the result on a given image"""
623
618
  for result in self.pages:
@@ -634,22 +629,18 @@ class Document(Element):
634
629
  """
635
630
  return [page.synthesize(**kwargs) for page in self.pages]
636
631
 
637
- def export_as_xml(self, **kwargs) -> list[tuple[bytes, ET.ElementTree]]:
638
- """Export the document as XML (hOCR-format)
639
-
640
- Args:
641
- **kwargs: additional keyword arguments passed to the Page.export_as_xml method
642
-
643
- Returns:
644
- list of tuple of (bytes, ElementTree)
645
- """
646
- return [page.export_as_xml(**kwargs) for page in self.pages]
632
+ _page_cls: Any = Page
647
633
 
648
634
  @classmethod
649
- def from_dict(cls, save_dict: dict[str, Any], **kwargs):
650
- kwargs = {k: save_dict[k] for k in cls._exported_keys}
651
- kwargs.update({"pages": [Page.from_dict(page_dict) for page_dict in save_dict["pages"]]})
652
- return cls(**kwargs)
635
+ def from_dict(cls, save_dict: dict[str, Any], pages: list[np.ndarray] | None = None, **kwargs):
636
+ _kwargs: dict[str, Any] = {k: save_dict[k] for k in cls._exported_keys}
637
+ _kwargs.update({
638
+ "pages": [
639
+ cls._page_cls.from_dict(page_dict, page=None if pages is None else pages[idx])
640
+ for idx, page_dict in enumerate(save_dict["pages"])
641
+ ]
642
+ })
643
+ return cls(**_kwargs)
653
644
 
654
645
 
655
646
  class KIEDocument(Document):
@@ -660,6 +651,7 @@ class KIEDocument(Document):
660
651
  """
661
652
 
662
653
  _children_names: list[str] = ["pages"]
654
+ _page_cls: Any = KIEPage
663
655
  pages: list[KIEPage] = [] # type: ignore[assignment]
664
656
 
665
657
  def __init__(