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/cli/__init__.py ADDED
File without changes
doctr/cli/main.py ADDED
@@ -0,0 +1,669 @@
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 os
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import torch
15
+ from tqdm import tqdm
16
+
17
+ from doctr.io import ConcatSource, Document, DocumentFile, PageDecodeError, PageSource
18
+ from doctr.io.figures import IMAGE_FORMATS, IMAGE_MODES, FigureEncoder
19
+ from doctr.io.sources import _is_pdf
20
+ from doctr.models import ocr_predictor
21
+ from doctr.models._utils import _CONFIDENCE_AGGREGATIONS
22
+ from doctr.version import __version__
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # Name of the handler installed by the CLI, so that repeated `main` calls do not stack handlers
27
+ _CLI_HANDLER_NAME = "doctr-cli"
28
+
29
+ # Canonical export formats and their aliases, mirroring `Document.export_as`
30
+ FORMAT_ALIASES: dict[str, str] = {
31
+ "json": "json",
32
+ "dict": "json",
33
+ "txt": "txt",
34
+ "text": "txt",
35
+ "md": "md",
36
+ "markdown": "md",
37
+ "adoc": "adoc",
38
+ "asciidoc": "adoc",
39
+ "html": "html",
40
+ "xml": "xml",
41
+ "hocr": "xml",
42
+ }
43
+
44
+ # Used to infer the export format from the `--output` extension when `--format` is not given
45
+ SUFFIX_ALIASES: dict[str, str] = {
46
+ ".json": "json",
47
+ ".txt": "txt",
48
+ ".text": "txt",
49
+ ".md": "md",
50
+ ".markdown": "md",
51
+ ".adoc": "adoc",
52
+ ".asciidoc": "adoc",
53
+ ".html": "html",
54
+ ".htm": "html",
55
+ ".xml": "xml",
56
+ ".hocr": "xml",
57
+ }
58
+
59
+ READING_DIRECTIONS = ["auto", "ltr", "rtl", "ttb-rtl", "ttb-ltr"]
60
+
61
+
62
+ def _setup_logging(quiet: bool = False) -> None:
63
+ """Configure the logging of the `doctr` package for the CLI
64
+
65
+ Only the library logger is configured, so that the CLI output stays free of the third-party
66
+ logs the root logger would otherwise pick up.
67
+
68
+ Args:
69
+ quiet: whether only errors should be logged
70
+ """
71
+ doctr_logger = logging.getLogger("doctr")
72
+
73
+ # `main` can be called several times in the same process, so the previous handler is replaced
74
+ for handler in list(doctr_logger.handlers):
75
+ if handler.name == _CLI_HANDLER_NAME:
76
+ doctr_logger.removeHandler(handler)
77
+
78
+ handler = logging.StreamHandler()
79
+ handler.set_name(_CLI_HANDLER_NAME)
80
+ handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
81
+ doctr_logger.addHandler(handler)
82
+ doctr_logger.setLevel(logging.ERROR if quiet else logging.INFO)
83
+
84
+
85
+ def _resolve_format(args: argparse.Namespace) -> str:
86
+ """Resolve the canonical export format, inferring it from the output extension if needed
87
+
88
+ Args:
89
+ args: the parsed command-line arguments
90
+
91
+ Returns:
92
+ one of 'json', 'txt', 'md', 'adoc', 'html', 'xml'
93
+ """
94
+ if args.format is not None:
95
+ return FORMAT_ALIASES[args.format.strip().lower()]
96
+ return SUFFIX_ALIASES.get(Path(args.output).suffix.lower(), "json")
97
+
98
+
99
+ def _load_document(args: argparse.Namespace) -> ConcatSource:
100
+ """Open every input as a single lazy document: pages are only decoded when they are processed
101
+
102
+ Args:
103
+ args: the parsed command-line arguments
104
+
105
+ Returns:
106
+ the concatenation of the inputs, decoding its pages on demand
107
+ """
108
+ pdf_kwargs: dict[str, Any] = {"scale": args.pdf_scale, "password": args.pdf_password}
109
+
110
+ sources: list[PageSource] = []
111
+ for input_path in args.input_path:
112
+ try:
113
+ if input_path.lower().startswith(("http://", "https://")):
114
+ sources.append(DocumentFile.from_url(input_path, lazy=True, **pdf_kwargs))
115
+ elif _is_pdf(input_path):
116
+ # A PDF from its extension, or from its header for a file without any (e.g. `scan`)
117
+ sources.append(DocumentFile.from_pdf(input_path, lazy=True, **pdf_kwargs))
118
+ elif Path(input_path).is_dir():
119
+ # A folder is expanded to the PDFs and the images it contains (non-recursively, sorted by name). With
120
+ # `--on_error skip`, the files that cannot be read are skipped with a warning naming them
121
+ folder = DocumentFile.from_files(input_path, lazy=True, pdf_kwargs=pdf_kwargs, on_error=args.on_error)
122
+ if len(folder) == 0:
123
+ logger.error(f"No readable PDF or image found in {input_path}")
124
+ sys.exit(1)
125
+ sources.append(folder)
126
+ else:
127
+ sources.append(DocumentFile.from_images(input_path, lazy=True))
128
+ logger.info(f"Document loaded successfully from {input_path}")
129
+ except FileNotFoundError:
130
+ logger.error(f"File not found: {input_path}")
131
+ sys.exit(1)
132
+ except ValueError as e:
133
+ # The error names the faulty file, e.g. among the files of a folder
134
+ logger.error(f"File could not be read as a valid image or PDF: {input_path} ({e})")
135
+ sys.exit(1)
136
+ except Exception as e:
137
+ logger.error(f"Error occurred while loading the document: {e}")
138
+ sys.exit(1)
139
+
140
+ return ConcatSource(sources)
141
+
142
+
143
+ def _predict(model: Any, doc: ConcatSource, args: argparse.Namespace) -> tuple[Document, Exception | None]:
144
+ """Run the predictor on the document chunk by chunk, with a progress bar
145
+
146
+ Invalid files are reported by `_load_document`: only a page that cannot be decoded (e.g. an image with a valid
147
+ header but corrupted content) or an input deleted in the meantime fails here. With `--on_error skip`, such a page
148
+ is skipped with a warning. Otherwise the run stops at that page, and the pages before it are returned with the
149
+ error, so that they are not lost. Other errors (e.g. raised by the models) propagate as-is.
150
+
151
+ Args:
152
+ model: the predictor
153
+ doc: the lazy document
154
+ args: the parsed command-line arguments
155
+
156
+ Returns:
157
+ the predicted document, and the error that stopped the run (if any)
158
+ """
159
+ pages: list[Any] = []
160
+ skipped: list[int] = []
161
+ error: Exception | None = None
162
+ with tqdm(total=len(doc), unit="page", desc="OCR", disable=args.quiet, file=sys.stderr) as progress:
163
+
164
+ def _skip(page_idx: int, page_error: Exception) -> None:
165
+ skipped.append(page_idx)
166
+ logger.warning(f"Skipping page {page_idx + 1} of {len(doc)}: {page_error}")
167
+ progress.update(1)
168
+
169
+ try:
170
+ for page in model.stream(doc, on_error=_skip if args.on_error == "skip" else "raise"):
171
+ pages.append(page)
172
+ progress.update(1)
173
+ except (FileNotFoundError, PageDecodeError) as e:
174
+ error = e
175
+ finally:
176
+ doc.close()
177
+ if skipped:
178
+ logger.warning(f"{len(skipped)} of {len(doc)} page(s) could not be read and were skipped")
179
+ return Document(pages=pages), error
180
+
181
+
182
+ def _resolve_device(device: str | None) -> torch.device:
183
+ """Resolve the device the models should be loaded on
184
+
185
+ Args:
186
+ device: the `--device` value
187
+
188
+ Returns:
189
+ the resolved torch device
190
+ """
191
+ if device is None or device.strip().lower() == "auto":
192
+ return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
193
+ try:
194
+ return torch.device(device)
195
+ except (RuntimeError, ValueError) as e:
196
+ logger.error(f"Invalid device '{device}': {e}")
197
+ sys.exit(1)
198
+
199
+
200
+ def _set_thresholds(model: Any, args: argparse.Namespace) -> None:
201
+ """Override the post-processing thresholds of the detection model
202
+
203
+ Args:
204
+ model: the predictor
205
+ args: the parsed command-line arguments
206
+ """
207
+ if args.bin_thresh is None and args.box_thresh is None:
208
+ return
209
+
210
+ det_model = getattr(getattr(model, "det_predictor", None), "model", None)
211
+ postprocessor = getattr(det_model, "postprocessor", None)
212
+ if postprocessor is None:
213
+ logger.warning("The detection model exposes no postprocessor: --bin_thresh & --box_thresh are ignored")
214
+ return
215
+
216
+ if args.bin_thresh is not None:
217
+ postprocessor.bin_thresh = args.bin_thresh
218
+ if args.box_thresh is not None:
219
+ postprocessor.box_thresh = args.box_thresh
220
+
221
+
222
+ def _to_device(model: Any, args: argparse.Namespace) -> Any:
223
+ """Load the predictor on the requested device
224
+
225
+ Args:
226
+ model: the predictor
227
+ args: the parsed command-line arguments
228
+
229
+ Returns:
230
+ the predictor, loaded on the requested device
231
+ """
232
+ device = _resolve_device(args.device)
233
+ try:
234
+ model = model.to(device)
235
+ if device.type == "cuda" and torch.cuda.get_device_capability(device) >= (8, 0):
236
+ model = model.bfloat16()
237
+ logger.info(f"Model loaded on {device} with bfloat16 precision")
238
+ except (RuntimeError, AssertionError, ValueError) as e:
239
+ logger.error(f"Could not load the model on device '{device}': {e}")
240
+ sys.exit(1)
241
+ logger.info(f"Model loaded on {device}")
242
+ return model
243
+
244
+
245
+ def _build_predictor(args: argparse.Namespace) -> Any:
246
+ """Instantiate the OCR predictor matching the requested options
247
+
248
+ Args:
249
+ args: the parsed command-line arguments
250
+
251
+ Returns:
252
+ the predictor
253
+ """
254
+ # Region masking is resolved by the layout model, so it has to be enabled along with `ignore_regions`
255
+ detect_layout = args.detect_layout or bool(args.ignore_regions)
256
+ if detect_layout and not args.detect_layout:
257
+ logger.info("--ignore_regions requires the layout model: layout detection has been enabled")
258
+
259
+ kwargs: dict[str, Any] = {
260
+ "det_arch": args.det_arch,
261
+ "reco_arch": args.reco_arch,
262
+ "pretrained": True,
263
+ "assume_straight_pages": args.assume_straight_pages,
264
+ "preserve_aspect_ratio": args.preserve_aspect_ratio,
265
+ "symmetric_pad": args.symmetric_pad,
266
+ "export_as_straight_boxes": args.export_as_straight_boxes,
267
+ "detect_orientation": args.detect_orientation,
268
+ "straighten_pages": args.straighten_pages,
269
+ "detect_language": args.detect_language,
270
+ "detect_layout": detect_layout,
271
+ "layout_arch": args.layout_arch,
272
+ "ignore_regions": args.ignore_regions or None,
273
+ "det_bs": args.det_bs,
274
+ "reco_bs": args.reco_bs,
275
+ "confidence_aggregation": args.confidence_aggregation,
276
+ # `_OCRPredictor` keyword args
277
+ "disable_page_orientation": args.disable_page_orientation,
278
+ "disable_crop_orientation": args.disable_crop_orientation,
279
+ "preserve_original_coords": args.preserve_original_coords,
280
+ "page_chunk_size": args.page_chunk_size,
281
+ # `DocumentBuilder` keyword args
282
+ "resolve_lines": args.resolve_lines,
283
+ "resolve_blocks": args.resolve_blocks,
284
+ "paragraph_break": args.paragraph_break,
285
+ "keep_reading_order": args.keep_reading_order,
286
+ }
287
+
288
+ model = ocr_predictor(detect_tables=args.detect_tables, detect_formulas=args.detect_formulas, **kwargs)
289
+
290
+ _set_thresholds(model, args)
291
+ return _to_device(model, args)
292
+
293
+
294
+ def _default_image_dir(output: str) -> Path:
295
+ """Return the default image directory in 'referenced' mode: `<output name>_images`, next to the output
296
+
297
+ Args:
298
+ output: the `--output` value
299
+
300
+ Returns:
301
+ the image directory
302
+ """
303
+ path = Path(output)
304
+ return path.with_name(f"{path.stem}_images")
305
+
306
+
307
+ def _figure_encoder(args: argparse.Namespace) -> FigureEncoder:
308
+ """Build the figure encoder of the Markdown, AsciiDoc and HTML exports (links relative to the output file)
309
+
310
+ Args:
311
+ args: the parsed command-line arguments
312
+
313
+ Returns:
314
+ the figure encoder
315
+ """
316
+ if args.images != "referenced":
317
+ return FigureEncoder(args.images, image_format=args.image_format)
318
+ image_dir = Path(args.image_dir) if args.image_dir is not None else _default_image_dir(args.output)
319
+ output_dir = Path(args.output).parent
320
+ try:
321
+ path_prefix = os.path.relpath(image_dir.absolute(), output_dir.absolute())
322
+ except ValueError: # pragma: no cover (Windows: image directory on another drive)
323
+ path_prefix = str(image_dir.absolute())
324
+ return FigureEncoder("referenced", image_dir=image_dir, path_prefix=path_prefix, image_format=args.image_format)
325
+
326
+
327
+ def _export_kwargs(fmt: str, args: argparse.Namespace) -> dict[str, Any]:
328
+ """Build the keyword arguments accepted by the exporter of the requested format
329
+
330
+ Args:
331
+ fmt: the canonical export format
332
+ args: the parsed command-line arguments
333
+
334
+ Returns:
335
+ the keyword arguments to pass to `Document.export_as`
336
+ """
337
+ kwargs: dict[str, Any] = {}
338
+ if fmt in {"json", "xml"}:
339
+ kwargs["reading_order"] = args.reading_order
340
+ if fmt == "xml":
341
+ kwargs["file_title"] = args.file_title
342
+ if fmt in {"txt", "md", "adoc", "html", "xml"}:
343
+ kwargs["direction"] = args.direction
344
+ if fmt in {"md", "adoc"}:
345
+ kwargs["escape"] = args.escape
346
+ if fmt in {"txt", "md", "adoc", "html"}:
347
+ kwargs["include_furniture"] = args.include_furniture
348
+ if fmt in {"md", "adoc", "html"}:
349
+ kwargs["images"] = _figure_encoder(args)
350
+ return kwargs
351
+
352
+
353
+ def _xml_paths(output: str, num_pages: int, page_indices: list[int] | None = None) -> list[Path]:
354
+ """Build one output path per page, since hOCR describes a single page per file
355
+
356
+ Args:
357
+ output: the `--output` value
358
+ num_pages: the number of exported pages
359
+ page_indices: the index of each exported page in the input, so that the file names keep matching the pages
360
+ when some of them were skipped (defaults to `range(num_pages)`)
361
+
362
+ Returns:
363
+ the list of paths to write to
364
+ """
365
+ path = Path(output)
366
+ if num_pages <= 1:
367
+ return [path]
368
+ indices = range(num_pages) if page_indices is None else page_indices
369
+ return [path.with_name(f"{path.stem}_page_{idx + 1}{path.suffix}") for idx in indices]
370
+
371
+
372
+ def _save_results(result: Any, fmt: str, args: argparse.Namespace) -> None:
373
+ """Export the predictions and write them to disk
374
+
375
+ Args:
376
+ result: the document returned by the predictor
377
+ fmt: the canonical export format
378
+ args: the parsed command-line arguments
379
+ """
380
+ kwargs = _export_kwargs(fmt, args)
381
+ try:
382
+ exported = result.export_as(fmt, **kwargs)
383
+ except Exception as e:
384
+ logger.error(f"Results could not be exported as '{fmt}': {e}")
385
+ sys.exit(1)
386
+ encoder = kwargs.get("images")
387
+ if isinstance(encoder, FigureEncoder) and encoder.written:
388
+ logger.info(f"{len(encoder.written)} figure(s) saved to {encoder.image_dir}")
389
+
390
+ try:
391
+ if fmt == "xml":
392
+ # `export_as_xml` returns one (bytes, ElementTree) tuple per page
393
+ paths = _xml_paths(args.output, len(exported), [page.page_idx for page in result.pages])
394
+ for path, (xml_bytes, _) in zip(paths, exported):
395
+ path.write_bytes(xml_bytes)
396
+ logger.info(f"Results saved to {', '.join(str(path) for path in paths)}")
397
+ else:
398
+ with open(args.output, "w", encoding="utf-8") as f:
399
+ if fmt == "json":
400
+ json.dump(exported, f, indent=args.indent, ensure_ascii=False)
401
+ else:
402
+ f.write(exported)
403
+ logger.info(f"Results saved to {args.output}")
404
+ except FileNotFoundError:
405
+ logger.error(f"Could not write output file at given path: {args.output}")
406
+ sys.exit(1)
407
+ except Exception as e:
408
+ logger.error(f"Results could not be saved: {e}")
409
+ sys.exit(1)
410
+
411
+
412
+ def main(argv=None):
413
+ """Main function for the docTR CLI tool"""
414
+ # parse command-line arguments and set up the model
415
+ args = _parse_args(argv)
416
+ _setup_logging(args.quiet)
417
+
418
+ fmt = _resolve_format(args)
419
+
420
+ # open the inputs first (pages are decoded on demand): missing or invalid files fail before the models load
421
+ doc = _load_document(args)
422
+
423
+ model = _build_predictor(args)
424
+
425
+ # perform OCR
426
+ logger.info(f"Performing OCR on {len(doc)} page(s)...")
427
+ result, error = _predict(model, doc, args)
428
+
429
+ if error is not None:
430
+ logger.error(f"File could not be read as a valid image or PDF: {error}")
431
+ if not result.pages:
432
+ sys.exit(1)
433
+ # Do not lose the pages processed before the error
434
+ logger.error(
435
+ f"Saving the results of the {len(result.pages)} page(s) processed before the error "
436
+ "(pass `--on_error skip` to skip the pages that cannot be read)"
437
+ )
438
+
439
+ # save results to the requested format
440
+ _save_results(result, fmt, args)
441
+ if error is not None:
442
+ sys.exit(1)
443
+
444
+
445
+ def _parse_args(argv=None):
446
+ parser = argparse.ArgumentParser(
447
+ description="docTR CLI tool for OCR prediction on images and PDFs",
448
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
449
+ )
450
+
451
+ parser.add_argument("--version", action="version", version=f"docTR {__version__}")
452
+
453
+ # required input path(s)
454
+ parser.add_argument(
455
+ "--input_path",
456
+ type=str,
457
+ nargs="+",
458
+ required=True,
459
+ help="paths to images, PDFs or folders of those (non-recursive, sorted by name), or URLs of web pages",
460
+ )
461
+ parser.add_argument("--pdf_password", type=str, default=None, help="password to unlock encrypted PDF files")
462
+ parser.add_argument("--pdf_scale", type=int, default=2, help="PDF rendering scale (1 corresponds to 72dpi)")
463
+
464
+ # architecture selection
465
+ parser.add_argument(
466
+ "--det_arch",
467
+ type=str,
468
+ default="fast_base",
469
+ help="name of the detection architecture or the model itself to use",
470
+ )
471
+ parser.add_argument(
472
+ "--reco_arch",
473
+ type=str,
474
+ default="crnn_vgg16_bn",
475
+ help="name of the recognition architecture or the model itself to use",
476
+ )
477
+ parser.add_argument("--layout_arch", type=str, default="lw_detr_s", help="name of the layout architecture to use")
478
+ parser.add_argument(
479
+ "--device",
480
+ type=str,
481
+ default="auto",
482
+ help="device to load the models on, e.g. 'cpu', 'cuda', 'cuda:1' or 'mps' ('auto' picks a GPU if available)",
483
+ )
484
+
485
+ # processing options
486
+ parser.add_argument(
487
+ "--assume_straight_pages",
488
+ action=argparse.BooleanOptionalAction,
489
+ default=True,
490
+ help="assume only straight pages without rotated textual elements",
491
+ )
492
+ parser.add_argument(
493
+ "--straighten_pages", action="store_true", help="attempt to straighten skewed pages before analysis"
494
+ )
495
+ parser.add_argument(
496
+ "--preserve_aspect_ratio",
497
+ action=argparse.BooleanOptionalAction,
498
+ default=True,
499
+ help="preserve aspect ratio when resizing pages",
500
+ )
501
+ parser.add_argument(
502
+ "--symmetric_pad",
503
+ action=argparse.BooleanOptionalAction,
504
+ default=True,
505
+ help="apply symmetric padding",
506
+ )
507
+ parser.add_argument(
508
+ "--bin_thresh",
509
+ type=float,
510
+ default=None,
511
+ help="binarization threshold of the detection segmentation map (defaults to the architecture value)",
512
+ )
513
+ parser.add_argument(
514
+ "--box_thresh",
515
+ type=float,
516
+ default=None,
517
+ help="minimal objectness score to consider a detected box (defaults to the architecture value)",
518
+ )
519
+ parser.add_argument(
520
+ "--confidence_aggregation",
521
+ type=str,
522
+ default=None,
523
+ choices=list(_CONFIDENCE_AGGREGATIONS),
524
+ help="aggregation method of the character probabilities into the word confidence (defaults to the method of "
525
+ "the recognition architecture)",
526
+ )
527
+ parser.add_argument("--det_bs", type=int, default=2, help="batch size for detection")
528
+ parser.add_argument("--reco_bs", type=int, default=128, help="batch size for recognition")
529
+ parser.add_argument(
530
+ "--page_chunk_size",
531
+ type=int,
532
+ default=32,
533
+ help="number of pages decoded & processed at once: bounds the memory footprint on long documents",
534
+ )
535
+ parser.add_argument(
536
+ "--on_error",
537
+ type=str,
538
+ default="raise",
539
+ choices=["raise", "skip"],
540
+ help="what to do with a file of a folder or a page that cannot be read: stop with an error (the results of "
541
+ "the pages processed so far are still saved), or skip it with a warning",
542
+ )
543
+ parser.add_argument("--detect_orientation", action="store_true", help="automatically detect page orientation")
544
+ parser.add_argument("--detect_language", action="store_true", help="detect language of the text")
545
+ parser.add_argument("--detect_layout", action="store_true", help="attach the detected layout regions to each page")
546
+ parser.add_argument(
547
+ "--detect_tables",
548
+ action="store_true",
549
+ help="regroup the words of the detected tables into structured tables (enables the layout model)",
550
+ )
551
+ parser.add_argument(
552
+ "--detect_formulas",
553
+ action="store_true",
554
+ help="read the detected formulas as LaTeX, exported as display math (enables the layout model)",
555
+ )
556
+ parser.add_argument(
557
+ "--ignore_regions",
558
+ type=str,
559
+ nargs="+",
560
+ default=None,
561
+ metavar="CLASS",
562
+ help="layout class names to mask out before detection & recognition (enables the layout model), "
563
+ "e.g. Picture Table",
564
+ )
565
+ parser.add_argument(
566
+ "--export_as_straight_boxes",
567
+ action="store_true",
568
+ help="export rotated predictions as straight boxes (only with --no-assume_straight_pages)",
569
+ )
570
+ parser.add_argument(
571
+ "--preserve_original_coords",
572
+ action="store_true",
573
+ help="map the boxes back to the original page coordinates (only with --straighten_pages)",
574
+ )
575
+ parser.add_argument("--disable_page_orientation", action="store_true", help="disable the page orientation model")
576
+ parser.add_argument("--disable_crop_orientation", action="store_true", help="disable the crop orientation model")
577
+
578
+ # document assembling options
579
+ parser.add_argument(
580
+ "--resolve_lines",
581
+ action=argparse.BooleanOptionalAction,
582
+ default=True,
583
+ help="automatically group words into lines",
584
+ )
585
+ parser.add_argument("--resolve_blocks", action="store_true", help="automatically group lines into blocks")
586
+ parser.add_argument(
587
+ "--paragraph_break",
588
+ type=float,
589
+ default=0.035,
590
+ help="relative length of the minimum space separating paragraphs",
591
+ )
592
+ parser.add_argument(
593
+ "--keep_reading_order", action="store_true", help="arrange the content of every page in reading order"
594
+ )
595
+
596
+ # output options
597
+ parser.add_argument("--output", type=str, default="results.json", help="path to output the results")
598
+ parser.add_argument(
599
+ "--format",
600
+ type=str,
601
+ default=None,
602
+ choices=sorted(FORMAT_ALIASES),
603
+ help="export format (inferred from the --output extension, or JSON, when not set)",
604
+ )
605
+ parser.add_argument(
606
+ "--direction", type=str, default="auto", choices=READING_DIRECTIONS, help="reading direction of the document"
607
+ )
608
+ parser.add_argument(
609
+ "--reading_order",
610
+ action=argparse.BooleanOptionalAction,
611
+ default=True,
612
+ help="linearize the content in reading order (JSON & hOCR exports)",
613
+ )
614
+ parser.add_argument(
615
+ "--escape",
616
+ action=argparse.BooleanOptionalAction,
617
+ default=True,
618
+ help="escape the characters carrying a structural meaning (Markdown & AsciiDoc exports)",
619
+ )
620
+ parser.add_argument(
621
+ "--include_furniture",
622
+ action=argparse.BooleanOptionalAction,
623
+ default=True,
624
+ help="include page headers, page footers and footnotes (text-like exports)",
625
+ )
626
+ parser.add_argument(
627
+ "--images",
628
+ type=str,
629
+ default="placeholder",
630
+ choices=list(IMAGE_MODES),
631
+ help="how figures are rendered in the Markdown, AsciiDoc and HTML exports (requires the layout model)",
632
+ )
633
+ parser.add_argument(
634
+ "--image_dir",
635
+ type=str,
636
+ default=None,
637
+ help="directory of the figures with --images referenced (default: '<output name>_images' next to the output)",
638
+ )
639
+ parser.add_argument(
640
+ "--image_format",
641
+ type=str,
642
+ default="png",
643
+ choices=list(IMAGE_FORMATS),
644
+ help="file format of the figures (--images embedded or referenced)",
645
+ )
646
+ parser.add_argument(
647
+ "--file_title", type=str, default="docTR - XML export (hOCR)", help="title of the exported hOCR files"
648
+ )
649
+ parser.add_argument("--indent", type=int, default=4, help="indentation of the JSON export")
650
+ parser.add_argument("--quiet", action="store_true", help="only log errors")
651
+
652
+ args = parser.parse_args(argv)
653
+
654
+ if args.image_dir is not None and args.images != "referenced":
655
+ parser.error("--image_dir is only used with --images referenced")
656
+
657
+ for name in ("bin_thresh", "box_thresh"):
658
+ value = getattr(args, name)
659
+ if value is not None and not 0.0 <= value <= 1.0:
660
+ parser.error(f"--{name} must be between 0 and 1")
661
+
662
+ if args.page_chunk_size < 1:
663
+ parser.error("--page_chunk_size must be a positive integer")
664
+
665
+ return args
666
+
667
+
668
+ if __name__ == "__main__":
669
+ main()
@@ -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 *