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/cli/__init__.py ADDED
File without changes
doctr/cli/main.py ADDED
@@ -0,0 +1,506 @@
1
+ # Copyright (C) 2021-2026, Mindee.
2
+
3
+ # This program is licensed under the Apache License 2.0.
4
+ # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
+
6
+ import argparse
7
+ import json
8
+ import logging
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+ from doctr.io import DocumentFile
17
+ from doctr.models import ocr_predictor
18
+ from doctr.version import __version__
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Name of the handler installed by the CLI, so that repeated `main` calls do not stack handlers
23
+ _CLI_HANDLER_NAME = "doctr-cli"
24
+
25
+ # Canonical export formats and their aliases, mirroring `Document.export_as`
26
+ FORMAT_ALIASES: dict[str, str] = {
27
+ "json": "json",
28
+ "dict": "json",
29
+ "txt": "txt",
30
+ "text": "txt",
31
+ "md": "md",
32
+ "markdown": "md",
33
+ "adoc": "adoc",
34
+ "asciidoc": "adoc",
35
+ "html": "html",
36
+ "xml": "xml",
37
+ "hocr": "xml",
38
+ }
39
+
40
+ # Used to infer the export format from the `--output` extension when `--format` is not given
41
+ SUFFIX_ALIASES: dict[str, str] = {
42
+ ".json": "json",
43
+ ".txt": "txt",
44
+ ".text": "txt",
45
+ ".md": "md",
46
+ ".markdown": "md",
47
+ ".adoc": "adoc",
48
+ ".asciidoc": "adoc",
49
+ ".html": "html",
50
+ ".htm": "html",
51
+ ".xml": "xml",
52
+ ".hocr": "xml",
53
+ }
54
+
55
+ READING_DIRECTIONS = ["auto", "ltr", "rtl", "ttb-rtl", "ttb-ltr"]
56
+
57
+
58
+ def _setup_logging(quiet: bool = False) -> None:
59
+ """Configure the logging of the `doctr` package for the CLI
60
+
61
+ Only the library logger is configured, so that the CLI output stays free of the third-party
62
+ logs the root logger would otherwise pick up.
63
+
64
+ Args:
65
+ quiet: whether only errors should be logged
66
+ """
67
+ doctr_logger = logging.getLogger("doctr")
68
+
69
+ # `main` can be called several times in the same process, so the previous handler is replaced
70
+ for handler in list(doctr_logger.handlers):
71
+ if handler.name == _CLI_HANDLER_NAME:
72
+ doctr_logger.removeHandler(handler)
73
+
74
+ handler = logging.StreamHandler()
75
+ handler.set_name(_CLI_HANDLER_NAME)
76
+ handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
77
+ doctr_logger.addHandler(handler)
78
+ doctr_logger.setLevel(logging.ERROR if quiet else logging.INFO)
79
+
80
+
81
+ def _resolve_format(args: argparse.Namespace) -> str:
82
+ """Resolve the canonical export format, inferring it from the output extension if needed
83
+
84
+ Args:
85
+ args: the parsed command-line arguments
86
+
87
+ Returns:
88
+ one of 'json', 'txt', 'md', 'adoc', 'html', 'xml'
89
+ """
90
+ if args.format is not None:
91
+ return FORMAT_ALIASES[args.format.strip().lower()]
92
+ return SUFFIX_ALIASES.get(Path(args.output).suffix.lower(), "json")
93
+
94
+
95
+ def _load_document(args: argparse.Namespace) -> list[np.ndarray]:
96
+ """Load every input into a single list of pages
97
+
98
+ Args:
99
+ args: the parsed command-line arguments
100
+
101
+ Returns:
102
+ the list of pages decoded as numpy ndarray of shape H x W x 3
103
+ """
104
+ pdf_kwargs: dict[str, Any] = {"scale": args.pdf_scale, "password": args.pdf_password}
105
+
106
+ pages: list[np.ndarray] = []
107
+ for input_path in args.input_path:
108
+ try:
109
+ if input_path.lower().startswith(("http://", "https://")):
110
+ pages.extend(DocumentFile.from_url(input_path, **pdf_kwargs))
111
+ elif input_path.lower().endswith(".pdf"):
112
+ pages.extend(DocumentFile.from_pdf(input_path, **pdf_kwargs))
113
+ else:
114
+ pages.extend(DocumentFile.from_images(input_path))
115
+ logger.info(f"Document loaded successfully from {input_path}")
116
+ except FileNotFoundError:
117
+ logger.error(f"File not found: {input_path}")
118
+ sys.exit(1)
119
+ except ValueError:
120
+ logger.error(f"File could not be read as a valid image or PDF: {input_path}")
121
+ sys.exit(1)
122
+ except Exception as e:
123
+ logger.error(f"Error occurred while loading the document: {e}")
124
+ sys.exit(1)
125
+
126
+ return pages
127
+
128
+
129
+ def _resolve_device(device: str | None) -> torch.device:
130
+ """Resolve the device the models should be loaded on
131
+
132
+ Args:
133
+ device: the `--device` value
134
+
135
+ Returns:
136
+ the resolved torch device
137
+ """
138
+ if device is None or device.strip().lower() == "auto":
139
+ return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
140
+ try:
141
+ return torch.device(device)
142
+ except (RuntimeError, ValueError) as e:
143
+ logger.error(f"Invalid device '{device}': {e}")
144
+ sys.exit(1)
145
+
146
+
147
+ def _set_thresholds(model: Any, args: argparse.Namespace) -> None:
148
+ """Override the post-processing thresholds of the detection model
149
+
150
+ Args:
151
+ model: the predictor
152
+ args: the parsed command-line arguments
153
+ """
154
+ if args.bin_thresh is None and args.box_thresh is None:
155
+ return
156
+
157
+ det_model = getattr(getattr(model, "det_predictor", None), "model", None)
158
+ postprocessor = getattr(det_model, "postprocessor", None)
159
+ if postprocessor is None:
160
+ logger.warning("The detection model exposes no postprocessor: --bin_thresh & --box_thresh are ignored")
161
+ return
162
+
163
+ if args.bin_thresh is not None:
164
+ postprocessor.bin_thresh = args.bin_thresh
165
+ if args.box_thresh is not None:
166
+ postprocessor.box_thresh = args.box_thresh
167
+
168
+
169
+ def _to_device(model: Any, args: argparse.Namespace) -> Any:
170
+ """Load the predictor on the requested device
171
+
172
+ Args:
173
+ model: the predictor
174
+ args: the parsed command-line arguments
175
+
176
+ Returns:
177
+ the predictor, loaded on the requested device
178
+ """
179
+ device = _resolve_device(args.device)
180
+ try:
181
+ model = model.to(device)
182
+ if device.type == "cuda" and torch.cuda.get_device_capability(device) >= (8, 0):
183
+ model = model.bfloat16()
184
+ logger.info(f"Model loaded on {device} with bfloat16 precision")
185
+ except (RuntimeError, AssertionError, ValueError) as e:
186
+ logger.error(f"Could not load the model on device '{device}': {e}")
187
+ sys.exit(1)
188
+ logger.info(f"Model loaded on {device}")
189
+ return model
190
+
191
+
192
+ def _build_predictor(args: argparse.Namespace) -> Any:
193
+ """Instantiate the OCR predictor matching the requested options
194
+
195
+ Args:
196
+ args: the parsed command-line arguments
197
+
198
+ Returns:
199
+ the predictor
200
+ """
201
+ # Region masking is resolved by the layout model, so it has to be enabled along with `ignore_regions`
202
+ detect_layout = args.detect_layout or bool(args.ignore_regions)
203
+ if detect_layout and not args.detect_layout:
204
+ logger.info("--ignore_regions requires the layout model: layout detection has been enabled")
205
+
206
+ kwargs: dict[str, Any] = {
207
+ "det_arch": args.det_arch,
208
+ "reco_arch": args.reco_arch,
209
+ "pretrained": True,
210
+ "assume_straight_pages": args.assume_straight_pages,
211
+ "preserve_aspect_ratio": args.preserve_aspect_ratio,
212
+ "symmetric_pad": args.symmetric_pad,
213
+ "export_as_straight_boxes": args.export_as_straight_boxes,
214
+ "detect_orientation": args.detect_orientation,
215
+ "straighten_pages": args.straighten_pages,
216
+ "detect_language": args.detect_language,
217
+ "detect_layout": detect_layout,
218
+ "layout_arch": args.layout_arch,
219
+ "ignore_regions": args.ignore_regions or None,
220
+ "det_bs": args.det_bs,
221
+ "reco_bs": args.reco_bs,
222
+ # `_OCRPredictor` keyword args
223
+ "disable_page_orientation": args.disable_page_orientation,
224
+ "disable_crop_orientation": args.disable_crop_orientation,
225
+ "preserve_original_coords": args.preserve_original_coords,
226
+ # `DocumentBuilder` keyword args
227
+ "resolve_lines": args.resolve_lines,
228
+ "resolve_blocks": args.resolve_blocks,
229
+ "paragraph_break": args.paragraph_break,
230
+ "keep_reading_order": args.keep_reading_order,
231
+ }
232
+
233
+ model = ocr_predictor(detect_tables=args.detect_tables, **kwargs)
234
+
235
+ _set_thresholds(model, args)
236
+ return _to_device(model, args)
237
+
238
+
239
+ def _export_kwargs(fmt: str, args: argparse.Namespace) -> dict[str, Any]:
240
+ """Build the keyword arguments accepted by the exporter of the requested format
241
+
242
+ Args:
243
+ fmt: the canonical export format
244
+ args: the parsed command-line arguments
245
+
246
+ Returns:
247
+ the keyword arguments to pass to `Document.export_as`
248
+ """
249
+ kwargs: dict[str, Any] = {}
250
+ if fmt in {"json", "xml"}:
251
+ kwargs["reading_order"] = args.reading_order
252
+ if fmt == "xml":
253
+ kwargs["file_title"] = args.file_title
254
+ if fmt in {"txt", "md", "adoc", "html", "xml"}:
255
+ kwargs["direction"] = args.direction
256
+ if fmt in {"md", "adoc"}:
257
+ kwargs["escape"] = args.escape
258
+ if fmt in {"txt", "md", "adoc", "html"}:
259
+ kwargs["include_furniture"] = args.include_furniture
260
+ return kwargs
261
+
262
+
263
+ def _xml_paths(output: str, num_pages: int) -> list[Path]:
264
+ """Build one output path per page, since hOCR describes a single page per file
265
+
266
+ Args:
267
+ output: the `--output` value
268
+ num_pages: the number of exported pages
269
+
270
+ Returns:
271
+ the list of paths to write to
272
+ """
273
+ path = Path(output)
274
+ if num_pages <= 1:
275
+ return [path]
276
+ return [path.with_name(f"{path.stem}_page_{idx + 1}{path.suffix}") for idx in range(num_pages)]
277
+
278
+
279
+ def _save_results(result: Any, fmt: str, args: argparse.Namespace) -> None:
280
+ """Export the predictions and write them to disk
281
+
282
+ Args:
283
+ result: the document returned by the predictor
284
+ fmt: the canonical export format
285
+ args: the parsed command-line arguments
286
+ """
287
+ try:
288
+ exported = result.export_as(fmt, **_export_kwargs(fmt, args))
289
+ except Exception as e:
290
+ logger.error(f"Results could not be exported as '{fmt}': {e}")
291
+ sys.exit(1)
292
+
293
+ try:
294
+ if fmt == "xml":
295
+ # `export_as_xml` returns one (bytes, ElementTree) tuple per page
296
+ paths = _xml_paths(args.output, len(exported))
297
+ for path, (xml_bytes, _) in zip(paths, exported):
298
+ path.write_bytes(xml_bytes)
299
+ logger.info(f"Results saved to {', '.join(str(path) for path in paths)}")
300
+ else:
301
+ with open(args.output, "w", encoding="utf-8") as f:
302
+ if fmt == "json":
303
+ json.dump(exported, f, indent=args.indent, ensure_ascii=False)
304
+ else:
305
+ f.write(exported)
306
+ logger.info(f"Results saved to {args.output}")
307
+ except FileNotFoundError:
308
+ logger.error(f"Could not write output file at given path: {args.output}")
309
+ sys.exit(1)
310
+ except Exception as e:
311
+ logger.error(f"Results could not be saved: {e}")
312
+ sys.exit(1)
313
+
314
+
315
+ def main(argv=None):
316
+ """Main function for the docTR CLI tool"""
317
+ # parse command-line arguments and set up the model
318
+ args = _parse_args(argv)
319
+ _setup_logging(args.quiet)
320
+
321
+ fmt = _resolve_format(args)
322
+ model = _build_predictor(args)
323
+
324
+ # load the document
325
+ doc = _load_document(args)
326
+
327
+ # perform OCR
328
+ logger.info("Performing OCR...")
329
+ result = model(doc)
330
+
331
+ # save results to the requested format
332
+ _save_results(result, fmt, args)
333
+
334
+
335
+ def _parse_args(argv=None):
336
+ parser = argparse.ArgumentParser(
337
+ description="docTR CLI tool for OCR prediction on images and PDFs",
338
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
339
+ )
340
+
341
+ parser.add_argument("--version", action="version", version=f"docTR {__version__}")
342
+
343
+ # required input path(s)
344
+ parser.add_argument(
345
+ "--input_path",
346
+ type=str,
347
+ nargs="+",
348
+ required=True,
349
+ help="path to one or more input image / PDF files, or URLs of web pages to render as PDF",
350
+ )
351
+ parser.add_argument("--pdf_password", type=str, default=None, help="password to unlock encrypted PDF files")
352
+ parser.add_argument("--pdf_scale", type=int, default=2, help="PDF rendering scale (1 corresponds to 72dpi)")
353
+
354
+ # architecture selection
355
+ parser.add_argument(
356
+ "--det_arch",
357
+ type=str,
358
+ default="fast_base",
359
+ help="name of the detection architecture or the model itself to use",
360
+ )
361
+ parser.add_argument(
362
+ "--reco_arch",
363
+ type=str,
364
+ default="crnn_vgg16_bn",
365
+ help="name of the recognition architecture or the model itself to use",
366
+ )
367
+ parser.add_argument("--layout_arch", type=str, default="lw_detr_s", help="name of the layout architecture to use")
368
+ parser.add_argument(
369
+ "--device",
370
+ type=str,
371
+ default="auto",
372
+ help="device to load the models on, e.g. 'cpu', 'cuda', 'cuda:1' or 'mps' ('auto' picks a GPU if available)",
373
+ )
374
+
375
+ # processing options
376
+ parser.add_argument(
377
+ "--assume_straight_pages",
378
+ action=argparse.BooleanOptionalAction,
379
+ default=True,
380
+ help="assume only straight pages without rotated textual elements",
381
+ )
382
+ parser.add_argument(
383
+ "--straighten_pages", action="store_true", help="attempt to straighten skewed pages before analysis"
384
+ )
385
+ parser.add_argument(
386
+ "--preserve_aspect_ratio",
387
+ action=argparse.BooleanOptionalAction,
388
+ default=True,
389
+ help="preserve aspect ratio when resizing pages",
390
+ )
391
+ parser.add_argument(
392
+ "--symmetric_pad",
393
+ action=argparse.BooleanOptionalAction,
394
+ default=True,
395
+ help="apply symmetric padding",
396
+ )
397
+ parser.add_argument(
398
+ "--bin_thresh",
399
+ type=float,
400
+ default=None,
401
+ help="binarization threshold of the detection segmentation map (defaults to the architecture value)",
402
+ )
403
+ parser.add_argument(
404
+ "--box_thresh",
405
+ type=float,
406
+ default=None,
407
+ help="minimal objectness score to consider a detected box (defaults to the architecture value)",
408
+ )
409
+ parser.add_argument("--det_bs", type=int, default=2, help="batch size for detection")
410
+ parser.add_argument("--reco_bs", type=int, default=128, help="batch size for recognition")
411
+ parser.add_argument("--detect_orientation", action="store_true", help="automatically detect page orientation")
412
+ parser.add_argument("--detect_language", action="store_true", help="detect language of the text")
413
+ parser.add_argument("--detect_layout", action="store_true", help="attach the detected layout regions to each page")
414
+ parser.add_argument(
415
+ "--detect_tables",
416
+ action="store_true",
417
+ help="regroup the words of the detected tables into structured tables (enables the layout model)",
418
+ )
419
+ parser.add_argument(
420
+ "--ignore_regions",
421
+ type=str,
422
+ nargs="+",
423
+ default=None,
424
+ metavar="CLASS",
425
+ help="layout class names to mask out before detection & recognition (enables the layout model), "
426
+ "e.g. Picture Table",
427
+ )
428
+ parser.add_argument(
429
+ "--export_as_straight_boxes",
430
+ action="store_true",
431
+ help="export rotated predictions as straight boxes (only with --no-assume_straight_pages)",
432
+ )
433
+ parser.add_argument(
434
+ "--preserve_original_coords",
435
+ action="store_true",
436
+ help="map the boxes back to the original page coordinates (only with --straighten_pages)",
437
+ )
438
+ parser.add_argument("--disable_page_orientation", action="store_true", help="disable the page orientation model")
439
+ parser.add_argument("--disable_crop_orientation", action="store_true", help="disable the crop orientation model")
440
+
441
+ # document assembling options
442
+ parser.add_argument(
443
+ "--resolve_lines",
444
+ action=argparse.BooleanOptionalAction,
445
+ default=True,
446
+ help="automatically group words into lines",
447
+ )
448
+ parser.add_argument("--resolve_blocks", action="store_true", help="automatically group lines into blocks")
449
+ parser.add_argument(
450
+ "--paragraph_break",
451
+ type=float,
452
+ default=0.035,
453
+ help="relative length of the minimum space separating paragraphs",
454
+ )
455
+ parser.add_argument(
456
+ "--keep_reading_order", action="store_true", help="arrange the content of every page in reading order"
457
+ )
458
+
459
+ # output options
460
+ parser.add_argument("--output", type=str, default="results.json", help="path to output the results")
461
+ parser.add_argument(
462
+ "--format",
463
+ type=str,
464
+ default=None,
465
+ choices=sorted(FORMAT_ALIASES),
466
+ help="export format (inferred from the --output extension, or JSON, when not set)",
467
+ )
468
+ parser.add_argument(
469
+ "--direction", type=str, default="auto", choices=READING_DIRECTIONS, help="reading direction of the document"
470
+ )
471
+ parser.add_argument(
472
+ "--reading_order",
473
+ action=argparse.BooleanOptionalAction,
474
+ default=True,
475
+ help="linearize the content in reading order (JSON & hOCR exports)",
476
+ )
477
+ parser.add_argument(
478
+ "--escape",
479
+ action=argparse.BooleanOptionalAction,
480
+ default=True,
481
+ help="escape the characters carrying a structural meaning (Markdown & AsciiDoc exports)",
482
+ )
483
+ parser.add_argument(
484
+ "--include_furniture",
485
+ action=argparse.BooleanOptionalAction,
486
+ default=True,
487
+ help="include page headers, page footers and footnotes (text-like exports)",
488
+ )
489
+ parser.add_argument(
490
+ "--file_title", type=str, default="docTR - XML export (hOCR)", help="title of the exported hOCR files"
491
+ )
492
+ parser.add_argument("--indent", type=int, default=4, help="indentation of the JSON export")
493
+ parser.add_argument("--quiet", action="store_true", help="only log errors")
494
+
495
+ args = parser.parse_args(argv)
496
+
497
+ for name in ("bin_thresh", "box_thresh"):
498
+ value = getattr(args, name)
499
+ if value is not None and not 0.0 <= value <= 1.0:
500
+ parser.error(f"--{name} must be between 0 and 1")
501
+
502
+ return args
503
+
504
+
505
+ if __name__ == "__main__":
506
+ main()
@@ -1,4 +1,4 @@
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.
doctr/contrib/base.py CHANGED
@@ -1,4 +1,4 @@
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.
@@ -2,6 +2,7 @@ from .generator import *
2
2
  from .coco_text import *
3
3
  from .cord import *
4
4
  from .detection import *
5
+ from .layout import *
5
6
  from .doc_artefacts import *
6
7
  from .funsd import *
7
8
  from .ic03 import *
@@ -17,6 +18,7 @@ from .sroie import *
17
18
  from .svhn import *
18
19
  from .svt import *
19
20
  from .synthtext import *
21
+ from .table_structure import *
20
22
  from .utils import *
21
23
  from .vocabs import *
22
24
  from .wildreceipt import *
@@ -1,4 +1,4 @@
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.
@@ -27,10 +27,12 @@ class COCOTEXT(AbstractDataset):
27
27
  >>> from doctr.datasets import COCOTEXT
28
28
  >>> train_set = COCOTEXT(train=True, img_folder="/path/to/coco_text/train2014/",
29
29
  >>> label_path="/path/to/coco_text/cocotext.v2.json")
30
- >>> img, target = train_set[0]
30
+ >>> sample = train_set[0]
31
+ >>> img, target = sample.image, sample.target
31
32
  >>> test_set = COCOTEXT(train=False, img_folder="/path/to/coco_text/train2014/",
32
33
  >>> label_path = "/path/to/coco_text/cocotext.v2.json")
33
- >>> img, target = test_set[0]
34
+ >>> sample = test_set[0]
35
+ >>> img, target = sample.image, sample.target
34
36
 
35
37
  Args:
36
38
  img_folder: folder with all the images of the dataset
doctr/datasets/cord.py CHANGED
@@ -1,4 +1,4 @@
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.
@@ -26,7 +26,8 @@ class CORD(VisionDataset):
26
26
 
27
27
  >>> from doctr.datasets import CORD
28
28
  >>> train_set = CORD(train=True, download=True)
29
- >>> img, target = train_set[0]
29
+ >>> sample = train_set[0]
30
+ >>> img, target = sample.image, sample.target
30
31
 
31
32
  Args:
32
33
  train: whether the subset should be the training one
@@ -1,4 +1,4 @@
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.
@@ -9,12 +9,8 @@ from collections.abc import Callable
9
9
  from pathlib import Path
10
10
  from typing import Any
11
11
 
12
- import numpy as np
13
-
14
12
  from doctr.io.image import get_img_shape
15
- from doctr.utils.data import download_from_url
16
-
17
- from ...models.utils import _copy_tensor
13
+ from doctr.utils import Sample, download_from_url
18
14
 
19
15
  __all__ = ["_AbstractDataset", "_VisionDataset"]
20
16
 
@@ -26,8 +22,8 @@ class _AbstractDataset:
26
22
  def __init__(
27
23
  self,
28
24
  root: str | Path,
29
- img_transforms: Callable[[Any], Any] | None = None,
30
- sample_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
25
+ img_transforms: Callable[[Sample], Sample] | None = None,
26
+ sample_transforms: Callable[[Sample], Sample] | None = None,
31
27
  pre_transforms: Callable[[Any, Any], tuple[Any, Any]] | None = None,
32
28
  ) -> None:
33
29
  if not Path(root).is_dir():
@@ -45,32 +41,24 @@ class _AbstractDataset:
45
41
  def _read_sample(self, index: int) -> tuple[Any, Any]:
46
42
  raise NotImplementedError
47
43
 
48
- def __getitem__(self, index: int) -> tuple[Any, Any]:
44
+ def __getitem__(self, index: int) -> Sample:
49
45
  # Read image
50
46
  img, target = self._read_sample(index)
47
+ mask = None
48
+
51
49
  # Pre-transforms (format conversion at run-time etc.)
52
50
  if self._pre_transforms is not None:
53
51
  img, target = self._pre_transforms(img, target)
54
52
 
53
+ sample = Sample(image=img, mask=mask, target=target)
54
+
55
55
  if self.img_transforms is not None:
56
- # typing issue cf. https://github.com/python/mypy/issues/5485
57
- img = self.img_transforms(img)
56
+ sample = self.img_transforms(sample)
58
57
 
59
58
  if self.sample_transforms is not None:
60
- # Conditions to assess it is detection model with multiple classes and avoid confusion with other tasks.
61
- if (
62
- isinstance(target, dict)
63
- and all(isinstance(item, np.ndarray) for item in target.values())
64
- and set(target.keys()) != {"boxes", "labels"} # avoid confusion with obj detection target
65
- ):
66
- img_transformed = _copy_tensor(img)
67
- for class_name, bboxes in target.items():
68
- img_transformed, target[class_name] = self.sample_transforms(img, bboxes)
69
- img = img_transformed
70
- else:
71
- img, target = self.sample_transforms(img, target)
72
-
73
- return img, target
59
+ sample = self.sample_transforms(sample)
60
+
61
+ return sample
74
62
 
75
63
  def extra_repr(self) -> str:
76
64
  return ""
@@ -1,4 +1,4 @@
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.
@@ -11,6 +11,7 @@ import numpy as np
11
11
  import torch
12
12
 
13
13
  from doctr.io import read_img_as_tensor, tensor_from_numpy
14
+ from doctr.utils import Sample
14
15
 
15
16
  from .base import _AbstractDataset, _VisionDataset
16
17
 
@@ -48,11 +49,20 @@ class AbstractDataset(_AbstractDataset):
48
49
  return img, deepcopy(target)
49
50
 
50
51
  @staticmethod
51
- def collate_fn(samples: list[tuple[torch.Tensor, Any]]) -> tuple[torch.Tensor, list[Any]]:
52
- images, targets = zip(*samples)
53
- images = torch.stack(images, dim=0) # type: ignore[assignment]
52
+ def collate_fn(
53
+ samples: list[Sample],
54
+ ) -> tuple[torch.Tensor, list[Any]] | tuple[tuple[torch.Tensor, torch.Tensor], list[Any]]:
55
+ _images = [s.image for s in samples]
56
+ targets = [s.target for s in samples]
54
57
 
55
- return images, list(targets) # type: ignore[return-value]
58
+ _masks = [s.mask for s in samples if s.mask is not None]
59
+
60
+ images = torch.stack(_images, dim=0)
61
+ if _masks:
62
+ masks = torch.stack(_masks, dim=0)
63
+ return (images, masks), targets
64
+
65
+ return images, targets
56
66
 
57
67
 
58
68
  class VisionDataset(AbstractDataset, _VisionDataset): # noqa: D101