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
@@ -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.
@@ -73,10 +73,8 @@ class CTCPostProcessor(RecognitionPostProcessor):
73
73
  probs = F.softmax(logits, dim=-1).max(dim=-1).values.min(dim=1).values
74
74
 
75
75
  # collapse best path (using itertools.groupby), map to chars, join char list to string
76
- words = [
77
- decode_sequence([k for k, _ in groupby(seq.tolist()) if k != blank], vocab)
78
- for seq in torch.argmax(logits, dim=-1)
79
- ]
76
+ best_paths = torch.argmax(logits, dim=-1).detach().cpu().numpy()
77
+ words = [decode_sequence([k for k, _ in groupby(seq.tolist()) if k != blank], vocab) for seq in best_paths]
80
78
 
81
79
  return list(zip(words, probs.tolist()))
82
80
 
@@ -279,7 +277,7 @@ def crnn_vgg16_bn(pretrained: bool = False, **kwargs: Any) -> CRNN:
279
277
  >>> out = model(input_tensor)
280
278
 
281
279
  Args:
282
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
280
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
283
281
  **kwargs: keyword arguments of the CRNN architecture
284
282
 
285
283
  Returns:
@@ -299,7 +297,7 @@ def crnn_mobilenet_v3_small(pretrained: bool = False, **kwargs: Any) -> CRNN:
299
297
  >>> out = model(input_tensor)
300
298
 
301
299
  Args:
302
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
300
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
303
301
  **kwargs: keyword arguments of the CRNN architecture
304
302
 
305
303
  Returns:
@@ -325,7 +323,7 @@ def crnn_mobilenet_v3_large(pretrained: bool = False, **kwargs: Any) -> CRNN:
325
323
  >>> out = model(input_tensor)
326
324
 
327
325
  Args:
328
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
326
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
329
327
  **kwargs: keyword arguments of the CRNN architecture
330
328
 
331
329
  Returns:
@@ -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.
@@ -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.
@@ -247,14 +247,13 @@ class MASTER(_MASTER, nn.Module):
247
247
  for i in range(self.max_length - 1):
248
248
  source_mask, target_mask = self.make_source_and_target_mask(encoded, ys)
249
249
  output = self.decoder(ys, encoded, source_mask, target_mask)
250
- logits = self.linear(output)
251
- prob = torch.softmax(logits, dim=-1)
252
- next_token = torch.max(prob, dim=-1).indices
253
250
  # update ys with the next token and ignore the first token (SOS)
254
- ys[:, i + 1] = next_token[:, i]
251
+ ys[:, i + 1] = self.linear(output[:, i]).argmax(-1)
252
+ if (ys == self.vocab_size).any(dim=-1).all(): # every sequence has emitted EOS
253
+ break
255
254
 
256
255
  # Shape (N, max_length, vocab_size + 1)
257
- return logits
256
+ return self.linear(output)
258
257
 
259
258
 
260
259
  class MASTERPostProcessor(_MASTERPostProcessor):
@@ -274,7 +273,7 @@ class MASTERPostProcessor(_MASTERPostProcessor):
274
273
  # Manual decoding
275
274
  word_values = [
276
275
  "".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
277
- for encoded_seq in out_idxs.cpu().numpy()
276
+ for encoded_seq in out_idxs.detach().cpu().numpy()
278
277
  ]
279
278
 
280
279
  return list(zip(word_values, probs.numpy().clip(0, 1).tolist()))
@@ -325,7 +324,7 @@ def master(pretrained: bool = False, **kwargs: Any) -> MASTER:
325
324
  >>> out = model(input_tensor)
326
325
 
327
326
  Args:
328
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
327
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
329
328
  **kwargs: keywoard arguments passed to the MASTER architecture
330
329
 
331
330
  Returns:
@@ -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.
@@ -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.
@@ -417,16 +417,16 @@ class PARSeqPostProcessor(_PARSeqPostProcessor):
417
417
  ) -> list[tuple[str, float]]:
418
418
  # compute pred with argmax for attention models
419
419
  out_idxs = logits.argmax(-1)
420
- preds_prob = torch.softmax(logits, -1).max(dim=-1)[0]
420
+ preds_prob = torch.softmax(logits, -1).max(dim=-1)[0].detach().cpu().numpy()
421
421
 
422
422
  # Manual decoding
423
423
  word_values = [
424
424
  "".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
425
- for encoded_seq in out_idxs.cpu().numpy()
425
+ for encoded_seq in out_idxs.detach().cpu().numpy()
426
426
  ]
427
427
  # compute probabilties for each word up to the EOS token
428
428
  probs = [
429
- preds_prob[i, : len(word)].clip(0, 1).mean().item() if word else 0.0 for i, word in enumerate(word_values)
429
+ float(preds_prob[i, : len(word)].clip(0, 1).mean()) if word else 0.0 for i, word in enumerate(word_values)
430
430
  ]
431
431
 
432
432
  return list(zip(word_values, probs))
@@ -482,7 +482,7 @@ def parseq(pretrained: bool = False, **kwargs: Any) -> PARSeq:
482
482
  >>> out = model(input_tensor)
483
483
 
484
484
  Args:
485
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
485
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
486
486
  **kwargs: keyword arguments of the PARSeq architecture
487
487
 
488
488
  Returns:
@@ -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.
@@ -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.
@@ -70,7 +70,7 @@ class RecognitionPredictor(nn.Module):
70
70
 
71
71
  # Forward it
72
72
  _params = next(self.model.parameters())
73
- self.model, processed_batches = set_device_and_dtype(
73
+ self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
74
74
  self.model, processed_batches, _params.device, _params.dtype
75
75
  )
76
76
  raw = [self.model(batch, return_preds=True, **kwargs)["preds"] for batch in processed_batches]
@@ -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.
@@ -389,7 +389,7 @@ def sar_resnet31(pretrained: bool = False, **kwargs: Any) -> SAR:
389
389
  >>> out = model(input_tensor)
390
390
 
391
391
  Args:
392
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
392
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
393
393
  **kwargs: keyword arguments of the SAR architecture
394
394
 
395
395
  Returns:
@@ -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.
@@ -20,12 +20,11 @@ def merge_strings(a: str, b: str, overlap_ratio: float) -> str:
20
20
  Returns:
21
21
  A merged character sequence.
22
22
 
23
- Example::
24
- >>> from doctr.models.recognition.utils import merge_strings
25
- >>> merge_strings('abcd', 'cdefgh', 0.5)
26
- 'abcdefgh'
27
- >>> merge_strings('abcdi', 'cdefgh', 0.5)
28
- 'abcdefgh'
23
+ >>> from doctr.models.recognition.utils import merge_strings
24
+ >>> merge_strings('abcd', 'cdefgh', 0.5)
25
+ 'abcdefgh'
26
+ >>> merge_strings('abcdi', 'cdefgh', 0.5)
27
+ 'abcdefgh'
29
28
  """
30
29
  seq_len = min(len(a), len(b))
31
30
  if seq_len <= 1: # One sequence is empty or will be after cropping in next step, return both to keep data
@@ -78,10 +77,9 @@ def merge_multi_strings(seq_list: list[str], overlap_ratio: float, last_overlap_
78
77
  Returns:
79
78
  A merged character sequence
80
79
 
81
- Example::
82
- >>> from doctr.models.recognition.utils import merge_multi_strings
83
- >>> merge_multi_strings(['abc', 'bcdef', 'difghi', 'aijkl'], 0.5, 0.1)
84
- 'abcdefghijkl'
80
+ >>> from doctr.models.recognition.utils import merge_multi_strings
81
+ >>> merge_multi_strings(['abc', 'bcdef', 'difghi', 'aijkl'], 0.5, 0.1)
82
+ 'abcdefghijkl'
85
83
  """
86
84
  if not seq_list:
87
85
  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.
@@ -61,10 +61,8 @@ class VIPTRPostProcessor(RecognitionPostProcessor):
61
61
  probs = F.softmax(logits, dim=-1).max(dim=-1).values.min(dim=1).values
62
62
 
63
63
  # collapse best path (using itertools.groupby), map to chars, join char list to string
64
- words = [
65
- decode_sequence([k for k, _ in groupby(seq.tolist()) if k != blank], vocab)
66
- for seq in torch.argmax(logits, dim=-1)
67
- ]
64
+ best_paths = torch.argmax(logits, dim=-1).detach().cpu().numpy()
65
+ words = [decode_sequence([k for k, _ in groupby(seq.tolist()) if k != blank], vocab) for seq in best_paths]
68
66
 
69
67
  return list(zip(words, probs.tolist()))
70
68
 
@@ -261,7 +259,7 @@ def viptr_tiny(pretrained: bool = False, **kwargs: Any) -> VIPTR:
261
259
  >>> out = model(input_tensor)
262
260
 
263
261
  Args:
264
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
262
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
265
263
  **kwargs: keyword arguments of the VIPTR architecture
266
264
 
267
265
  Returns:
@@ -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.
@@ -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.
@@ -174,16 +174,16 @@ class ViTSTRPostProcessor(_ViTSTRPostProcessor):
174
174
  ) -> list[tuple[str, float]]:
175
175
  # compute pred with argmax for attention models
176
176
  out_idxs = logits.argmax(-1)
177
- preds_prob = torch.softmax(logits, -1).max(dim=-1)[0]
177
+ preds_prob = torch.softmax(logits, -1).max(dim=-1)[0].detach().cpu().numpy()
178
178
 
179
179
  # Manual decoding
180
180
  word_values = [
181
181
  "".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
182
- for encoded_seq in out_idxs.cpu().numpy()
182
+ for encoded_seq in out_idxs.detach().cpu().numpy()
183
183
  ]
184
184
  # compute probabilties for each word up to the EOS token
185
185
  probs = [
186
- preds_prob[i, : len(word)].clip(0, 1).mean().item() if word else 0.0 for i, word in enumerate(word_values)
186
+ float(preds_prob[i, : len(word)].clip(0, 1).mean()) if word else 0.0 for i, word in enumerate(word_values)
187
187
  ]
188
188
 
189
189
  return list(zip(word_values, probs))
@@ -239,7 +239,7 @@ def vitstr_small(pretrained: bool = False, **kwargs: Any) -> ViTSTR:
239
239
  >>> out = model(input_tensor)
240
240
 
241
241
  Args:
242
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
242
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
243
243
  kwargs: keyword arguments of the ViTSTR architecture
244
244
 
245
245
  Returns:
@@ -268,7 +268,7 @@ def vitstr_base(pretrained: bool = False, **kwargs: Any) -> ViTSTR:
268
268
  >>> out = model(input_tensor)
269
269
 
270
270
  Args:
271
- pretrained (bool): If True, returns a model pre-trained on our text recognition dataset
271
+ pretrained: If True, returns a model pre-trained on our text recognition dataset
272
272
  kwargs: keyword arguments of the ViTSTR architecture
273
273
 
274
274
  Returns:
@@ -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.
@@ -71,12 +71,11 @@ def recognition_predictor(
71
71
  ) -> RecognitionPredictor:
72
72
  """Text recognition architecture.
73
73
 
74
- Example::
75
- >>> import numpy as np
76
- >>> from doctr.models import recognition_predictor
77
- >>> model = recognition_predictor(pretrained=True)
78
- >>> input_page = (255 * np.random.rand(32, 128, 3)).astype(np.uint8)
79
- >>> out = model([input_page])
74
+ >>> import numpy as np
75
+ >>> from doctr.models import recognition_predictor
76
+ >>> model = recognition_predictor(pretrained=True)
77
+ >>> input_page = (255 * np.random.rand(32, 128, 3)).astype(np.uint8)
78
+ >>> out = model([input_page])
80
79
 
81
80
  Args:
82
81
  arch: name of the architecture or model itself to use (e.g. 'crnn_vgg16_bn')
@@ -0,0 +1,2 @@
1
+ from .zoo import *
2
+ from .tablecenternet import *
@@ -0,0 +1 @@
1
+ from .pytorch import *
@@ -0,0 +1,80 @@
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
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import torch
10
+ from torch import nn
11
+
12
+ from doctr.models.detection._utils import _remove_padding
13
+ from doctr.models.preprocessor import PreProcessor
14
+ from doctr.models.utils import set_device_and_dtype
15
+
16
+ __all__ = ["TablePredictor"]
17
+
18
+
19
+ class TablePredictor(nn.Module):
20
+ """Implements an object able to recognize the cell structure of tables in a document.
21
+
22
+ Args:
23
+ pre_processor: transform inputs for easier batched model inference
24
+ model: core table-structure-recognition architecture
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ pre_processor: PreProcessor,
30
+ model: nn.Module,
31
+ ) -> None:
32
+ super().__init__()
33
+ self.pre_processor = pre_processor
34
+ self.model = model.eval()
35
+
36
+ @torch.inference_mode()
37
+ def forward(self, pages: list[np.ndarray], **kwargs: Any) -> list[dict[str, Any]]:
38
+ # Extract parameters from the preprocessor
39
+ preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
40
+ symmetric_pad = self.pre_processor.resize.symmetric_pad
41
+ assume_straight_pages = self.model.assume_straight_pages
42
+ # Dimension check
43
+ if any(page.ndim != 3 for page in pages):
44
+ raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
45
+
46
+ processed_batches = self.pre_processor(pages)
47
+ _params = next(self.model.parameters())
48
+ self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
49
+ self.model, processed_batches, _params.device, _params.dtype
50
+ )
51
+ predicted_batches = [self.model(batch, return_preds=True, **kwargs) for batch in processed_batches]
52
+ preds = [pred for batch in predicted_batches for pred in batch["preds"]]
53
+
54
+ rectified = _remove_padding(
55
+ pages,
56
+ [{"polygons": pred["polygons"]} for pred in preds],
57
+ preserve_aspect_ratio=preserve_aspect_ratio,
58
+ symmetric_pad=symmetric_pad,
59
+ assume_straight_pages=assume_straight_pages, # type: ignore[arg-type]
60
+ )
61
+
62
+ results: list[dict[str, Any]] = []
63
+ for pred, rect in zip(preds, rectified):
64
+ polygons = rect["polygons"] # * np.array([w, h], dtype=np.float32) # relative -> absolute pixels
65
+ scores, logical = pred["scores"], pred["logical"]
66
+ cells, max_row, max_col = [], -1, -1
67
+ for poly, score, lc in zip(polygons, scores, logical):
68
+ start_col, end_col, start_row, end_row = (int(v) for v in lc)
69
+ max_row, max_col = max(max_row, end_row), max(max_col, end_col)
70
+ cells.append({
71
+ "geometry": poly.tolist(), # 4 points (TL, TR, BR, BL) in relative coordinates
72
+ "score": float(score),
73
+ "row_start": start_row,
74
+ "row_end": end_row,
75
+ "col_start": start_col,
76
+ "col_end": end_col,
77
+ })
78
+ # logical coordinates are 0-indexed, so the table size is the largest index + 1 (0 if no cells)
79
+ results.append({"cells": cells, "num_rows": max_row + 1, "num_cols": max_col + 1})
80
+ return results
@@ -0,0 +1,2 @@
1
+ from .base import *
2
+ from .pytorch import *