python-doctr 1.1.0__py3-none-any.whl → 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/cli/main.py CHANGED
@@ -6,15 +6,19 @@
6
6
  import argparse
7
7
  import json
8
8
  import logging
9
+ import os
9
10
  import sys
10
11
  from pathlib import Path
11
12
  from typing import Any
12
13
 
13
- import numpy as np
14
14
  import torch
15
+ from tqdm import tqdm
15
16
 
16
- from doctr.io import DocumentFile
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
17
20
  from doctr.models import ocr_predictor
21
+ from doctr.models._utils import _CONFIDENCE_AGGREGATIONS
18
22
  from doctr.version import __version__
19
23
 
20
24
  logger = logging.getLogger(__name__)
@@ -92,38 +96,87 @@ def _resolve_format(args: argparse.Namespace) -> str:
92
96
  return SUFFIX_ALIASES.get(Path(args.output).suffix.lower(), "json")
93
97
 
94
98
 
95
- def _load_document(args: argparse.Namespace) -> list[np.ndarray]:
96
- """Load every input into a single list of pages
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
97
101
 
98
102
  Args:
99
103
  args: the parsed command-line arguments
100
104
 
101
105
  Returns:
102
- the list of pages decoded as numpy ndarray of shape H x W x 3
106
+ the concatenation of the inputs, decoding its pages on demand
103
107
  """
104
108
  pdf_kwargs: dict[str, Any] = {"scale": args.pdf_scale, "password": args.pdf_password}
105
109
 
106
- pages: list[np.ndarray] = []
110
+ sources: list[PageSource] = []
107
111
  for input_path in args.input_path:
108
112
  try:
109
113
  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))
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)
113
126
  else:
114
- pages.extend(DocumentFile.from_images(input_path))
127
+ sources.append(DocumentFile.from_images(input_path, lazy=True))
115
128
  logger.info(f"Document loaded successfully from {input_path}")
116
129
  except FileNotFoundError:
117
130
  logger.error(f"File not found: {input_path}")
118
131
  sys.exit(1)
119
- except ValueError:
120
- logger.error(f"File could not be read as a valid image or PDF: {input_path}")
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})")
121
135
  sys.exit(1)
122
136
  except Exception as e:
123
137
  logger.error(f"Error occurred while loading the document: {e}")
124
138
  sys.exit(1)
125
139
 
126
- return pages
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
127
180
 
128
181
 
129
182
  def _resolve_device(device: str | None) -> torch.device:
@@ -219,10 +272,12 @@ def _build_predictor(args: argparse.Namespace) -> Any:
219
272
  "ignore_regions": args.ignore_regions or None,
220
273
  "det_bs": args.det_bs,
221
274
  "reco_bs": args.reco_bs,
275
+ "confidence_aggregation": args.confidence_aggregation,
222
276
  # `_OCRPredictor` keyword args
223
277
  "disable_page_orientation": args.disable_page_orientation,
224
278
  "disable_crop_orientation": args.disable_crop_orientation,
225
279
  "preserve_original_coords": args.preserve_original_coords,
280
+ "page_chunk_size": args.page_chunk_size,
226
281
  # `DocumentBuilder` keyword args
227
282
  "resolve_lines": args.resolve_lines,
228
283
  "resolve_blocks": args.resolve_blocks,
@@ -230,12 +285,45 @@ def _build_predictor(args: argparse.Namespace) -> Any:
230
285
  "keep_reading_order": args.keep_reading_order,
231
286
  }
232
287
 
233
- model = ocr_predictor(detect_tables=args.detect_tables, **kwargs)
288
+ model = ocr_predictor(detect_tables=args.detect_tables, detect_formulas=args.detect_formulas, **kwargs)
234
289
 
235
290
  _set_thresholds(model, args)
236
291
  return _to_device(model, args)
237
292
 
238
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
+
239
327
  def _export_kwargs(fmt: str, args: argparse.Namespace) -> dict[str, Any]:
240
328
  """Build the keyword arguments accepted by the exporter of the requested format
241
329
 
@@ -257,15 +345,19 @@ def _export_kwargs(fmt: str, args: argparse.Namespace) -> dict[str, Any]:
257
345
  kwargs["escape"] = args.escape
258
346
  if fmt in {"txt", "md", "adoc", "html"}:
259
347
  kwargs["include_furniture"] = args.include_furniture
348
+ if fmt in {"md", "adoc", "html"}:
349
+ kwargs["images"] = _figure_encoder(args)
260
350
  return kwargs
261
351
 
262
352
 
263
- def _xml_paths(output: str, num_pages: int) -> list[Path]:
353
+ def _xml_paths(output: str, num_pages: int, page_indices: list[int] | None = None) -> list[Path]:
264
354
  """Build one output path per page, since hOCR describes a single page per file
265
355
 
266
356
  Args:
267
357
  output: the `--output` value
268
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)`)
269
361
 
270
362
  Returns:
271
363
  the list of paths to write to
@@ -273,7 +365,8 @@ def _xml_paths(output: str, num_pages: int) -> list[Path]:
273
365
  path = Path(output)
274
366
  if num_pages <= 1:
275
367
  return [path]
276
- return [path.with_name(f"{path.stem}_page_{idx + 1}{path.suffix}") for idx in range(num_pages)]
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]
277
370
 
278
371
 
279
372
  def _save_results(result: Any, fmt: str, args: argparse.Namespace) -> None:
@@ -284,16 +377,20 @@ def _save_results(result: Any, fmt: str, args: argparse.Namespace) -> None:
284
377
  fmt: the canonical export format
285
378
  args: the parsed command-line arguments
286
379
  """
380
+ kwargs = _export_kwargs(fmt, args)
287
381
  try:
288
- exported = result.export_as(fmt, **_export_kwargs(fmt, args))
382
+ exported = result.export_as(fmt, **kwargs)
289
383
  except Exception as e:
290
384
  logger.error(f"Results could not be exported as '{fmt}': {e}")
291
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}")
292
389
 
293
390
  try:
294
391
  if fmt == "xml":
295
392
  # `export_as_xml` returns one (bytes, ElementTree) tuple per page
296
- paths = _xml_paths(args.output, len(exported))
393
+ paths = _xml_paths(args.output, len(exported), [page.page_idx for page in result.pages])
297
394
  for path, (xml_bytes, _) in zip(paths, exported):
298
395
  path.write_bytes(xml_bytes)
299
396
  logger.info(f"Results saved to {', '.join(str(path) for path in paths)}")
@@ -319,17 +416,30 @@ def main(argv=None):
319
416
  _setup_logging(args.quiet)
320
417
 
321
418
  fmt = _resolve_format(args)
322
- model = _build_predictor(args)
323
419
 
324
- # load the document
420
+ # open the inputs first (pages are decoded on demand): missing or invalid files fail before the models load
325
421
  doc = _load_document(args)
326
422
 
423
+ model = _build_predictor(args)
424
+
327
425
  # perform OCR
328
- logger.info("Performing OCR...")
329
- result = model(doc)
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
+ )
330
438
 
331
439
  # save results to the requested format
332
440
  _save_results(result, fmt, args)
441
+ if error is not None:
442
+ sys.exit(1)
333
443
 
334
444
 
335
445
  def _parse_args(argv=None):
@@ -346,7 +456,7 @@ def _parse_args(argv=None):
346
456
  type=str,
347
457
  nargs="+",
348
458
  required=True,
349
- help="path to one or more input image / PDF files, or URLs of web pages to render as PDF",
459
+ help="paths to images, PDFs or folders of those (non-recursive, sorted by name), or URLs of web pages",
350
460
  )
351
461
  parser.add_argument("--pdf_password", type=str, default=None, help="password to unlock encrypted PDF files")
352
462
  parser.add_argument("--pdf_scale", type=int, default=2, help="PDF rendering scale (1 corresponds to 72dpi)")
@@ -406,8 +516,30 @@ def _parse_args(argv=None):
406
516
  default=None,
407
517
  help="minimal objectness score to consider a detected box (defaults to the architecture value)",
408
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
+ )
409
527
  parser.add_argument("--det_bs", type=int, default=2, help="batch size for detection")
410
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
+ )
411
543
  parser.add_argument("--detect_orientation", action="store_true", help="automatically detect page orientation")
412
544
  parser.add_argument("--detect_language", action="store_true", help="detect language of the text")
413
545
  parser.add_argument("--detect_layout", action="store_true", help="attach the detected layout regions to each page")
@@ -416,6 +548,11 @@ def _parse_args(argv=None):
416
548
  action="store_true",
417
549
  help="regroup the words of the detected tables into structured tables (enables the layout model)",
418
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
+ )
419
556
  parser.add_argument(
420
557
  "--ignore_regions",
421
558
  type=str,
@@ -486,6 +623,26 @@ def _parse_args(argv=None):
486
623
  default=True,
487
624
  help="include page headers, page footers and footnotes (text-like exports)",
488
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
+ )
489
646
  parser.add_argument(
490
647
  "--file_title", type=str, default="docTR - XML export (hOCR)", help="title of the exported hOCR files"
491
648
  )
@@ -494,11 +651,17 @@ def _parse_args(argv=None):
494
651
 
495
652
  args = parser.parse_args(argv)
496
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
+
497
657
  for name in ("bin_thresh", "box_thresh"):
498
658
  value = getattr(args, name)
499
659
  if value is not None and not 0.0 <= value <= 1.0:
500
660
  parser.error(f"--{name} must be between 0 and 1")
501
661
 
662
+ if args.page_chunk_size < 1:
663
+ parser.error("--page_chunk_size must be a positive integer")
664
+
502
665
  return args
503
666
 
504
667
 
@@ -5,6 +5,7 @@
5
5
 
6
6
  import json
7
7
  import os
8
+ from functools import partial
8
9
  from typing import Any
9
10
 
10
11
  import numpy as np
@@ -64,6 +65,10 @@ class DetectionDataset(AbstractDataset):
64
65
 
65
66
  self.data.append((img_name, (np.asarray(geoms, dtype=np_dtype), polygons_classes)))
66
67
 
68
+ # Every sample exposes the full (sorted) set of classes so that the class -> channel mapping
69
+ # is identical across samples, even when a class has no box in a given image.
70
+ self._pre_transforms = partial(pre_transform_multiclass, class_names=self.class_names)
71
+
67
72
  def format_polygons(
68
73
  self, polygons: list | dict, use_polygons: bool, np_dtype: type
69
74
  ) -> tuple[np.ndarray, list[str]]:
@@ -81,11 +86,16 @@ class DetectionDataset(AbstractDataset):
81
86
  if isinstance(polygons, list):
82
87
  self._class_names += [CLASS_NAME]
83
88
  polygons_classes = [CLASS_NAME for _ in polygons]
84
- _polygons: np.ndarray = np.asarray(polygons, dtype=np_dtype)
89
+ _polygons: np.ndarray = (
90
+ np.asarray(polygons, dtype=np_dtype) if polygons else np.zeros((0, 4, 2), dtype=np_dtype)
91
+ )
85
92
  elif isinstance(polygons, dict):
86
93
  self._class_names += list(polygons.keys())
87
94
  polygons_classes = [k for k, v in polygons.items() for _ in v]
88
- _polygons = np.concatenate([np.asarray(poly, dtype=np_dtype) for poly in polygons.values() if poly], axis=0)
95
+ arrays: list[np.ndarray] = [np.asarray(poly, dtype=np_dtype) for poly in polygons.values() if poly]
96
+ _polygons = (
97
+ np.concatenate(arrays, axis=0) if arrays else np.zeros((0, 4, 2), dtype=np_dtype)
98
+ ) # image without any box
89
99
  else:
90
100
  raise TypeError(f"polygons should be a dictionary or list, it was {type(polygons)}")
91
101
  geoms = _polygons if use_polygons else np.concatenate((_polygons.min(axis=1), _polygons.max(axis=1)), axis=1)
@@ -4,21 +4,91 @@
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
6
  import random
7
- from collections.abc import Callable
7
+ from collections.abc import Callable, Sequence
8
+ from functools import lru_cache
8
9
  from typing import Any
9
10
 
10
- from PIL import Image, ImageDraw
11
+ from PIL import Image, ImageDraw, ImageFont
11
12
 
12
13
  from doctr.io.image import tensor_from_pil
13
14
  from doctr.utils import Sample
14
- from doctr.utils.fonts import get_font
15
+ from doctr.utils.fonts import get_font, get_font_candidates
15
16
 
16
17
  from ..datasets import AbstractDataset
17
18
 
19
+ # Size the synthetic samples are rendered at, and therefore the size the vocabulary is
20
+ # probed at: whether a glyph carries ink is a property of the rasterized outline.
21
+ DEFAULT_FONT_SIZE = 32
22
+ # Unicode non-characters: permanently unassigned, so a font never maps them and always
23
+ # falls back to ".notdef". Rendering them is how we learn what that fallback looks like.
24
+ NON_CHARACTERS = ("\ufffe", "\U0010ffff")
25
+
26
+
27
+ @lru_cache(maxsize=32)
28
+ def _load_font(font_family: str | None, font_size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
29
+ return get_font(font_family, font_size)
30
+
31
+
32
+ def _glyph_ink(font: ImageFont.FreeTypeFont | ImageFont.ImageFont, char: str) -> tuple[tuple[int, int], bytes] | None:
33
+ """Rasterized glyph of a character, None if it is drawn without ink."""
34
+ mask = font.getmask(char, mode="L")
35
+ return (mask.size, bytes(mask)) if mask.getbbox() is not None else None
36
+
37
+
38
+ @lru_cache(maxsize=32)
39
+ def _notdef_ink(font_family: str | None, font_size: int) -> frozenset[tuple[tuple[int, int], bytes]]:
40
+ """Glyph a font falls back to for characters it does not cover (the ".notdef" box)."""
41
+ font = _load_font(font_family, font_size)
42
+ return frozenset(ink for char in NON_CHARACTERS if (ink := _glyph_ink(font, char)) is not None)
43
+
44
+
45
+ @lru_cache(maxsize=8192)
46
+ def _renders_char(char: str, font_family: str | None, font_size: int) -> bool:
47
+ """Whether a font draws the actual glyph of a character, rather than nothing or a box."""
48
+ ink = _glyph_ink(_load_font(font_family, font_size), char)
49
+ return ink is not None and ink not in _notdef_ink(font_family, font_size)
50
+
51
+
52
+ def _resolve_fonts(font_family: str | list[str] | None) -> list[str | None]:
53
+ font_families: list[str | None] = [*font_family] if isinstance(font_family, list) else [font_family]
54
+ for font in font_families:
55
+ try:
56
+ _ = _load_font(font, DEFAULT_FONT_SIZE)
57
+ except OSError:
58
+ raise ValueError(f"unable to locate font: {font}")
59
+ return font_families
60
+
61
+
62
+ def _fonts_per_char(
63
+ vocab: str, font_families: Sequence[str | None], font_size: int = DEFAULT_FONT_SIZE
64
+ ) -> dict[str, tuple[str | None, ...]]:
65
+ """Map each character of the vocab to the fonts able to render it."""
66
+ # Whitespace is inkless in every font by design, so no font can be said to "cover" it;
67
+ # judging it by ink would reject any vocabulary containing a space.
68
+ mapping = {
69
+ char: tuple(font for font in font_families if char.isspace() or _renders_char(char, font, font_size))
70
+ for char in dict.fromkeys(vocab)
71
+ }
72
+ missing = [char for char, fonts in mapping.items() if not fonts]
73
+ if missing:
74
+ fallbacks = [font for font in get_font_candidates() if font not in font_families]
75
+ mapping.update({
76
+ char: tuple(font for font in fallbacks if _renders_char(char, font, font_size)) for char in missing
77
+ })
78
+ unrenderable = [char for char in missing if not mapping[char]]
79
+ if unrenderable:
80
+ raise ValueError(
81
+ f"the following characters cannot be rendered, neither by the given fonts {list(font_families)} "
82
+ f"nor by the system fonts {fallbacks}: "
83
+ f"{', '.join(f'{char!r} (U+{ord(char):04X})' for char in unrenderable)}. "
84
+ "They are drawn blank or as a '.notdef' box, please provide font(s) covering the whole vocab."
85
+ )
86
+ return mapping
87
+
18
88
 
19
89
  def synthesize_text_img(
20
90
  text: str,
21
- font_size: int = 32,
91
+ font_size: int = DEFAULT_FONT_SIZE,
22
92
  font_family: str | None = None,
23
93
  background_color: tuple[int, int, int] | None = None,
24
94
  text_color: tuple[int, int, int] | None = None,
@@ -34,13 +104,22 @@ def synthesize_text_img(
34
104
 
35
105
  Returns:
36
106
  PIL image of the text
107
+
108
+ Raises:
109
+ ValueError: if the text is empty or rendered without ink
37
110
  """
111
+ if not text:
112
+ raise ValueError("unable to synthesize an image from an empty text")
113
+
38
114
  background_color = (0, 0, 0) if background_color is None else background_color
39
115
  text_color = (255, 255, 255) if text_color is None else text_color
40
116
 
41
- font = get_font(font_family, font_size)
117
+ font = _load_font(font_family, font_size)
42
118
  left, top, right, bottom = font.getbbox(text)
43
119
  text_w, text_h = right - left, bottom - top
120
+ if text_w <= 0 or text_h <= 0:
121
+ raise ValueError(f"font {font_family!r} draws no ink for {text!r}, resulting in a zero-dimension image")
122
+
44
123
  h, w = int(round(1.3 * text_h)), int(round(1.1 * text_w))
45
124
  # If single letter, make the image square, otherwise expand to meet the text size
46
125
  img_size = (h, w) if len(text) > 1 else (max(h, w), max(h, w))
@@ -48,8 +127,8 @@ def synthesize_text_img(
48
127
  img = Image.new("RGB", img_size[::-1], color=background_color)
49
128
  d = ImageDraw.Draw(img)
50
129
 
51
- # Offset so that the text is centered
52
- text_pos = (int(round((img_size[1] - text_w) / 2)), int(round((img_size[0] - text_h) / 2)))
130
+ # Offset so that the text is centered: the ink starts at (left, top) from the drawing origin, not at (0, 0)
131
+ text_pos = (int(round((img_size[1] - text_w) / 2)) - left, int(round((img_size[0] - text_h) / 2)) - top)
53
132
  # Draw the text
54
133
  d.text(text_pos, text, font=font, fill=text_color)
55
134
  return img
@@ -67,14 +146,8 @@ class _CharacterGenerator(AbstractDataset):
67
146
  ) -> None:
68
147
  self.vocab = vocab
69
148
  self._num_samples = num_samples
70
- self.font_family = font_family if isinstance(font_family, list) else [font_family]
71
- # Validate fonts
72
- if isinstance(font_family, list):
73
- for font in self.font_family:
74
- try:
75
- _ = get_font(font, 10)
76
- except OSError:
77
- raise ValueError(f"unable to locate font: {font}")
149
+ self.font_family = _resolve_fonts(font_family)
150
+ self._fonts_per_char = _fonts_per_char(self.vocab, self.font_family)
78
151
  self.img_transforms = img_transforms
79
152
  self.sample_transforms = sample_transforms
80
153
 
@@ -83,7 +156,7 @@ class _CharacterGenerator(AbstractDataset):
83
156
  self._data = [
84
157
  (synthesize_text_img(char, font_family=font), idx) # type: ignore[misc]
85
158
  for idx, char in enumerate(self.vocab)
86
- for font in self.font_family
159
+ for font in self._fonts_per_char[char]
87
160
  ]
88
161
 
89
162
  def __len__(self) -> int:
@@ -96,7 +169,9 @@ class _CharacterGenerator(AbstractDataset):
96
169
  pil_img, target = self._data[idx] # type: ignore[misc]
97
170
  else:
98
171
  target = index % len(self.vocab)
99
- pil_img = synthesize_text_img(self.vocab[target], font_family=random.choice(self.font_family))
172
+ char = self.vocab[target]
173
+ font = random.choice(self._fonts_per_char[char]) # nosec B311
174
+ pil_img = synthesize_text_img(char, font_family=font)
100
175
  img = tensor_from_pil(pil_img)
101
176
 
102
177
  return img, target
@@ -114,31 +189,40 @@ class _WordGenerator(AbstractDataset):
114
189
  img_transforms: Callable[[Any], Any] | None = None,
115
190
  sample_transforms: Callable[[Sample], Sample] | None = None,
116
191
  ) -> None:
192
+ # An empty word can not be drawn: checked here, instead of failing on random samples during training
193
+ if not 1 <= min_chars <= max_chars:
194
+ raise ValueError(
195
+ f"expected 1 <= min_chars <= max_chars, but got min_chars={min_chars} and max_chars={max_chars}"
196
+ )
117
197
  self.vocab = vocab
118
198
  self.wordlen_range = (min_chars, max_chars)
119
199
  self._num_samples = num_samples
120
- self.font_family = font_family if isinstance(font_family, list) else [font_family]
121
- # Validate fonts
122
- if isinstance(font_family, list):
123
- for font in self.font_family:
124
- try:
125
- _ = get_font(font, 10)
126
- except OSError:
127
- raise ValueError(f"unable to locate font: {font}")
200
+ self.font_family = _resolve_fonts(font_family)
201
+ fonts_per_char = _fonts_per_char(self.vocab, self.font_family)
202
+ # A word is drawn with a single font, so the font is picked first and the word is
203
+ # built from the characters this font can render, weighted by its coverage
204
+ self._vocab_per_font = {
205
+ font: "".join(char for char in self.vocab if font in fonts_per_char[char])
206
+ for font in dict.fromkeys(font for fonts in fonts_per_char.values() for font in fonts)
207
+ }
208
+ self._fonts = list(self._vocab_per_font)
209
+ self._font_weights = [len(vocab_) for vocab_ in self._vocab_per_font.values()]
128
210
  self.img_transforms = img_transforms
129
211
  self.sample_transforms = sample_transforms
130
212
 
131
213
  self._data: list[Image.Image] = []
132
214
  if cache_samples:
133
- _words = [self._generate_string(*self.wordlen_range) for _ in range(num_samples)]
134
- self._data = [
135
- (synthesize_text_img(text, font_family=random.choice(self.font_family)), text) # type: ignore[misc]
136
- for text in _words
137
- ]
215
+ self._data = [self._synthesize_sample() for _ in range(num_samples)] # type: ignore[misc]
216
+
217
+ def _generate_string(self, min_chars: int, max_chars: int, vocab: str | None = None) -> str:
218
+ num_chars = random.randint(min_chars, max_chars) # nosec B311
219
+ characters = self.vocab if vocab is None else vocab
220
+ return "".join(random.choice(characters) for _ in range(num_chars)) # nosec B311
138
221
 
139
- def _generate_string(self, min_chars: int, max_chars: int) -> str:
140
- num_chars = random.randint(min_chars, max_chars)
141
- return "".join(random.choice(self.vocab) for _ in range(num_chars))
222
+ def _synthesize_sample(self) -> tuple[Image.Image, str]:
223
+ font = random.choices(self._fonts, weights=self._font_weights)[0] # nosec B311
224
+ text = self._generate_string(*self.wordlen_range, vocab=self._vocab_per_font[font])
225
+ return synthesize_text_img(text, font_family=font), text
142
226
 
143
227
  def __len__(self) -> int:
144
228
  return self._num_samples
@@ -148,8 +232,7 @@ class _WordGenerator(AbstractDataset):
148
232
  if len(self._data) > 0:
149
233
  pil_img, target = self._data[index] # type: ignore[misc]
150
234
  else:
151
- target = self._generate_string(*self.wordlen_range)
152
- pil_img = synthesize_text_img(target, font_family=random.choice(self.font_family))
235
+ pil_img, target = self._synthesize_sample()
153
236
  img = tensor_from_pil(pil_img)
154
237
 
155
238
  return img, target
@@ -39,7 +39,7 @@ class WordGenerator(_WordGenerator):
39
39
 
40
40
  Args:
41
41
  vocab: vocabulary to take the character from
42
- min_chars: minimum number of characters in a word
42
+ min_chars: minimum number of characters in a word, at least 1
43
43
  max_chars: maximum number of characters in a word
44
44
  num_samples: number of samples that will be generated iterating over the dataset
45
45
  cache_samples: whether generated images should be cached firsthand