torchocr 0.4.1__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.
- torchocr/__init__.py +26 -0
- torchocr/charsets.py +67 -0
- torchocr/core/__init__.py +1 -0
- torchocr/core/structures.py +72 -0
- torchocr/data/__init__.py +5 -0
- torchocr/data/ppocr_keys_v1.txt +6623 -0
- torchocr/datasets/__init__.py +9 -0
- torchocr/datasets/funsd.py +90 -0
- torchocr/datasets/icdar.py +116 -0
- torchocr/datasets/lmdb_words.py +73 -0
- torchocr/datasets/totaltext.py +118 -0
- torchocr/decoders.py +283 -0
- torchocr/io/__init__.py +21 -0
- torchocr/io/pdf.py +45 -0
- torchocr/losses.py +208 -0
- torchocr/metrics/__init__.py +6 -0
- torchocr/metrics/detection.py +208 -0
- torchocr/metrics/recognition.py +80 -0
- torchocr/models/__init__.py +37 -0
- torchocr/models/backbones/__init__.py +6 -0
- torchocr/models/backbones/mobilenet_v3.py +314 -0
- torchocr/models/backbones/resnet_vd.py +248 -0
- torchocr/models/detection.py +519 -0
- torchocr/models/hub.py +216 -0
- torchocr/models/recognition.py +391 -0
- torchocr/ops/__init__.py +6 -0
- torchocr/ops/crop.py +113 -0
- torchocr/ops/geometry.py +99 -0
- torchocr/pipelines.py +219 -0
- torchocr/postprocess.py +175 -0
- torchocr/transforms/__init__.py +13 -0
- torchocr/transforms/_presets.py +137 -0
- torchocr/transforms/db_targets.py +166 -0
- torchocr/transforms/v2.py +182 -0
- torchocr-0.4.1.dist-info/METADATA +257 -0
- torchocr-0.4.1.dist-info/RECORD +39 -0
- torchocr-0.4.1.dist-info/WHEEL +5 -0
- torchocr-0.4.1.dist-info/licenses/LICENSE +28 -0
- torchocr-0.4.1.dist-info/top_level.txt +1 -0
torchocr/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""torchocr: a PyTorch-native end-to-end OCR library."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.4.1"
|
|
4
|
+
|
|
5
|
+
from .charsets import load_charset, load_ppocr_keys_v1
|
|
6
|
+
from .core.structures import DocumentTensor
|
|
7
|
+
from .decoders import CharNGramLM, CTCBeamDecoder, CTCGreedyDecoder
|
|
8
|
+
from .io import load_image, load_pdf
|
|
9
|
+
from .losses import CRNNLoss, DBLoss
|
|
10
|
+
from .pipelines import OCRPipeline
|
|
11
|
+
from .postprocess import DBPostProcessor
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"CRNNLoss",
|
|
15
|
+
"CTCBeamDecoder",
|
|
16
|
+
"CharNGramLM",
|
|
17
|
+
"CTCGreedyDecoder",
|
|
18
|
+
"DBLoss",
|
|
19
|
+
"DBPostProcessor",
|
|
20
|
+
"DocumentTensor",
|
|
21
|
+
"OCRPipeline",
|
|
22
|
+
"load_image",
|
|
23
|
+
"load_charset",
|
|
24
|
+
"load_pdf",
|
|
25
|
+
"load_ppocr_keys_v1",
|
|
26
|
+
]
|
torchocr/charsets.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Character set loaders for OCR recognizers.
|
|
2
|
+
|
|
3
|
+
Currently exposes the PaddleOCR Chinese full-charset (``ppocr_keys_v1.txt``)
|
|
4
|
+
matched to PaddleOCR's CTC head shape: ``blank`` at index 0, followed by
|
|
5
|
+
6622 characters from the dictionary, a space, and any padding the model's
|
|
6
|
+
``num_classes`` requires (PaddleOCR hardcodes ``out_channels=6625`` even
|
|
7
|
+
though the active chars only fill 6624 slots).
|
|
8
|
+
|
|
9
|
+
The loader is sized against ``num_classes`` so callers can pass it
|
|
10
|
+
straight into :class:`CTCGreedyDecoder` without size mismatches.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from importlib.resources import files
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
_DATA_PACKAGE = "torchocr.data"
|
|
19
|
+
_PPOCR_KEYS_FILENAME = "ppocr_keys_v1.txt"
|
|
20
|
+
|
|
21
|
+
# PaddleOCR's CTC blank lives at index 0 by convention; matches the default
|
|
22
|
+
# ``blank_index`` in :class:`torchocr.CTCGreedyDecoder`.
|
|
23
|
+
BLANK_TOKEN = "<blank>"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def load_ppocr_keys_v1(num_classes: int) -> list[str]:
|
|
27
|
+
"""Return PaddleOCR's Chinese charset sized to match ``num_classes``.
|
|
28
|
+
|
|
29
|
+
Layout is ``[<blank>] + 6622 chars + [" "]`` followed by padding
|
|
30
|
+
``<blank>`` entries up to ``num_classes``. The CTC blank at index 0
|
|
31
|
+
is what the decoder collapses, so any padding entries (also blank)
|
|
32
|
+
are harmless even if the model never emits them.
|
|
33
|
+
|
|
34
|
+
For PaddleOCR's standard ch_ppocr_v2.0_rec checkpoint pass
|
|
35
|
+
``num_classes=6625``.
|
|
36
|
+
"""
|
|
37
|
+
if num_classes < 6624:
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"num_classes={num_classes} is too small for ppocr_keys_v1 "
|
|
40
|
+
"(needs >= 6624 to fit blank + 6622 chars + space)."
|
|
41
|
+
)
|
|
42
|
+
chars = (
|
|
43
|
+
files(_DATA_PACKAGE)
|
|
44
|
+
.joinpath(_PPOCR_KEYS_FILENAME)
|
|
45
|
+
.read_text(encoding="utf-8")
|
|
46
|
+
.splitlines()
|
|
47
|
+
)
|
|
48
|
+
full = [BLANK_TOKEN, *chars, " "]
|
|
49
|
+
while len(full) < num_classes:
|
|
50
|
+
full.append(BLANK_TOKEN)
|
|
51
|
+
return full
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
_LOADERS = {"ppocr_keys_v1": load_ppocr_keys_v1}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def load_charset(name: str, num_classes: int) -> list[str]:
|
|
58
|
+
"""Load a bundled charset by the name stored in ``weights.meta["charset"]``.
|
|
59
|
+
|
|
60
|
+
Example::
|
|
61
|
+
|
|
62
|
+
weights = CRNN_ResNet34_VD_Weights.DEFAULT
|
|
63
|
+
charset = load_charset(weights.meta["charset"], weights.meta["num_classes"])
|
|
64
|
+
"""
|
|
65
|
+
if name not in _LOADERS:
|
|
66
|
+
raise ValueError(f"Unknown charset '{name}'. Available: {sorted(_LOADERS)}.")
|
|
67
|
+
return _LOADERS[name](num_classes)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core data structures used by torchocr."""
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Core tensor structures for OCR pipelines."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
from torch import Tensor
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class TextDetectionTarget:
|
|
11
|
+
"""Ground-truth text regions for one image.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
polygons: ``(N, P, 2)`` float vertices in pixel ``(x, y)`` order.
|
|
15
|
+
ICDAR-2015 regions are quadrilaterals (``P = 4``).
|
|
16
|
+
texts: ``N`` transcriptions, aligned with ``polygons``.
|
|
17
|
+
ignore: ``(N,)`` bool mask of don't-care regions (``###`` in
|
|
18
|
+
ICDAR files). Evaluators exclude them from both recall and
|
|
19
|
+
precision.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
polygons: Tensor
|
|
23
|
+
texts: list[str]
|
|
24
|
+
ignore: Tensor
|
|
25
|
+
|
|
26
|
+
def __post_init__(self) -> None:
|
|
27
|
+
if self.polygons.ndim != 3 or self.polygons.shape[2] != 2:
|
|
28
|
+
raise ValueError(f"Expected (N, P, 2) polygons; got {tuple(self.polygons.shape)}.")
|
|
29
|
+
n = self.polygons.shape[0]
|
|
30
|
+
if len(self.texts) != n or tuple(self.ignore.shape) != (n,):
|
|
31
|
+
raise ValueError(
|
|
32
|
+
f"polygons ({n}), texts ({len(self.texts)}) and ignore "
|
|
33
|
+
f"{tuple(self.ignore.shape)} must describe the same N regions."
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# A pytree node: torchvision.transforms.v2 then moves ``polygons`` (once wrapped as
|
|
38
|
+
# ``tv_tensors.KeyPoints``) and leaves ``texts`` and ``ignore`` aligned. See torchocr.transforms.v2.
|
|
39
|
+
torch.export.register_dataclass(TextDetectionTarget)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class DocumentTensor:
|
|
44
|
+
"""Container for OCR-ready document data.
|
|
45
|
+
|
|
46
|
+
Attributes:
|
|
47
|
+
pixels: The input image, unmodified.
|
|
48
|
+
text: ``K`` recognized strings, one per region.
|
|
49
|
+
bounding_boxes: ``(K, 4)`` axis-aligned ``(x1, y1, x2, y2)`` boxes.
|
|
50
|
+
polygons: ``(K, 4, 2)`` rotated text quads in reading order
|
|
51
|
+
(top-left, top-right, bottom-right, bottom-left), when the
|
|
52
|
+
post-processor provides them.
|
|
53
|
+
scores: ``(K,)`` recognition confidence in ``[0, 1]``: the mean
|
|
54
|
+
probability of the characters read (0 if none).
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
pixels: Tensor
|
|
58
|
+
text: list[str] = field(default_factory=list)
|
|
59
|
+
bounding_boxes: Tensor | None = None
|
|
60
|
+
polygons: Tensor | None = None
|
|
61
|
+
scores: Tensor | None = None
|
|
62
|
+
|
|
63
|
+
def to(self, *args: object, **kwargs: object) -> "DocumentTensor":
|
|
64
|
+
"""Return a copy moved to the requested device/dtype."""
|
|
65
|
+
move = lambda t: t.to(*args, **kwargs) if t is not None else None # noqa: E731
|
|
66
|
+
return DocumentTensor(
|
|
67
|
+
pixels=self.pixels.to(*args, **kwargs),
|
|
68
|
+
text=list(self.text),
|
|
69
|
+
bounding_boxes=move(self.bounding_boxes),
|
|
70
|
+
polygons=move(self.polygons),
|
|
71
|
+
scores=move(self.scores),
|
|
72
|
+
)
|