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 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
+ )
@@ -0,0 +1,5 @@
1
+ """Vendored read-only data files (charsets, etc.) for torchocr.
2
+
3
+ This subpackage exists purely so :mod:`importlib.resources` can locate
4
+ the bundled text files. Loaders live in :mod:`torchocr.charsets`.
5
+ """