torchocr 0.4.1__tar.gz
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-0.4.1/LICENSE +28 -0
- torchocr-0.4.1/PKG-INFO +257 -0
- torchocr-0.4.1/README.md +223 -0
- torchocr-0.4.1/pyproject.toml +59 -0
- torchocr-0.4.1/setup.cfg +4 -0
- torchocr-0.4.1/src/torchocr/__init__.py +26 -0
- torchocr-0.4.1/src/torchocr/charsets.py +67 -0
- torchocr-0.4.1/src/torchocr/core/__init__.py +1 -0
- torchocr-0.4.1/src/torchocr/core/structures.py +72 -0
- torchocr-0.4.1/src/torchocr/data/__init__.py +5 -0
- torchocr-0.4.1/src/torchocr/data/ppocr_keys_v1.txt +6623 -0
- torchocr-0.4.1/src/torchocr/datasets/__init__.py +9 -0
- torchocr-0.4.1/src/torchocr/datasets/funsd.py +90 -0
- torchocr-0.4.1/src/torchocr/datasets/icdar.py +116 -0
- torchocr-0.4.1/src/torchocr/datasets/lmdb_words.py +73 -0
- torchocr-0.4.1/src/torchocr/datasets/totaltext.py +118 -0
- torchocr-0.4.1/src/torchocr/decoders.py +283 -0
- torchocr-0.4.1/src/torchocr/io/__init__.py +21 -0
- torchocr-0.4.1/src/torchocr/io/pdf.py +45 -0
- torchocr-0.4.1/src/torchocr/losses.py +208 -0
- torchocr-0.4.1/src/torchocr/metrics/__init__.py +6 -0
- torchocr-0.4.1/src/torchocr/metrics/detection.py +208 -0
- torchocr-0.4.1/src/torchocr/metrics/recognition.py +80 -0
- torchocr-0.4.1/src/torchocr/models/__init__.py +37 -0
- torchocr-0.4.1/src/torchocr/models/backbones/__init__.py +6 -0
- torchocr-0.4.1/src/torchocr/models/backbones/mobilenet_v3.py +314 -0
- torchocr-0.4.1/src/torchocr/models/backbones/resnet_vd.py +248 -0
- torchocr-0.4.1/src/torchocr/models/detection.py +519 -0
- torchocr-0.4.1/src/torchocr/models/hub.py +216 -0
- torchocr-0.4.1/src/torchocr/models/recognition.py +391 -0
- torchocr-0.4.1/src/torchocr/ops/__init__.py +6 -0
- torchocr-0.4.1/src/torchocr/ops/crop.py +113 -0
- torchocr-0.4.1/src/torchocr/ops/geometry.py +99 -0
- torchocr-0.4.1/src/torchocr/pipelines.py +219 -0
- torchocr-0.4.1/src/torchocr/postprocess.py +175 -0
- torchocr-0.4.1/src/torchocr/transforms/__init__.py +13 -0
- torchocr-0.4.1/src/torchocr/transforms/_presets.py +137 -0
- torchocr-0.4.1/src/torchocr/transforms/db_targets.py +166 -0
- torchocr-0.4.1/src/torchocr/transforms/v2.py +182 -0
- torchocr-0.4.1/src/torchocr.egg-info/PKG-INFO +257 -0
- torchocr-0.4.1/src/torchocr.egg-info/SOURCES.txt +70 -0
- torchocr-0.4.1/src/torchocr.egg-info/dependency_links.txt +1 -0
- torchocr-0.4.1/src/torchocr.egg-info/requires.txt +24 -0
- torchocr-0.4.1/src/torchocr.egg-info/top_level.txt +1 -0
- torchocr-0.4.1/tests/test_backbones.py +96 -0
- torchocr-0.4.1/tests/test_beam_decoder.py +133 -0
- torchocr-0.4.1/tests/test_charsets.py +45 -0
- torchocr-0.4.1/tests/test_compile_export.py +101 -0
- torchocr-0.4.1/tests/test_converter.py +127 -0
- torchocr-0.4.1/tests/test_crnn_converter.py +104 -0
- torchocr-0.4.1/tests/test_datasets.py +104 -0
- torchocr-0.4.1/tests/test_db_targets.py +68 -0
- torchocr-0.4.1/tests/test_decoders.py +62 -0
- torchocr-0.4.1/tests/test_detection_presets.py +76 -0
- torchocr-0.4.1/tests/test_funsd.py +48 -0
- torchocr-0.4.1/tests/test_io.py +61 -0
- torchocr-0.4.1/tests/test_lmdb_words.py +56 -0
- torchocr-0.4.1/tests/test_losses.py +78 -0
- torchocr-0.4.1/tests/test_metrics.py +188 -0
- torchocr-0.4.1/tests/test_mobilenet_v3.py +77 -0
- torchocr-0.4.1/tests/test_models.py +162 -0
- torchocr-0.4.1/tests/test_ops.py +170 -0
- torchocr-0.4.1/tests/test_parquet_to_lmdb.py +66 -0
- torchocr-0.4.1/tests/test_pipeline.py +232 -0
- torchocr-0.4.1/tests/test_postprocess.py +164 -0
- torchocr-0.4.1/tests/test_recognition_metrics.py +51 -0
- torchocr-0.4.1/tests/test_recognition_sampling.py +30 -0
- torchocr-0.4.1/tests/test_totaltext.py +78 -0
- torchocr-0.4.1/tests/test_transforms.py +64 -0
- torchocr-0.4.1/tests/test_transforms_v2.py +97 -0
- torchocr-0.4.1/tests/test_v3_converter.py +124 -0
- torchocr-0.4.1/tests/test_weights.py +235 -0
torchocr-0.4.1/LICENSE
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, Bryan Chen
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
torchocr-0.4.1/PKG-INFO
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: torchocr
|
|
3
|
+
Version: 0.4.1
|
|
4
|
+
Summary: PyTorch-native end-to-end OCR pipeline.
|
|
5
|
+
License-Expression: BSD-3-Clause
|
|
6
|
+
Project-URL: Documentation, https://bryanbradfo.github.io/torchOCR/
|
|
7
|
+
Project-URL: Source, https://github.com/BryanBradfo/torchOCR
|
|
8
|
+
Project-URL: Changelog, https://github.com/BryanBradfo/torchOCR/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Weights, https://huggingface.co/BryanBradfo/torchocr-weights
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: torch
|
|
14
|
+
Requires-Dist: torchvision>=0.23
|
|
15
|
+
Requires-Dist: pymupdf
|
|
16
|
+
Requires-Dist: scipy
|
|
17
|
+
Requires-Dist: opencv-python-headless
|
|
18
|
+
Requires-Dist: pyclipper
|
|
19
|
+
Requires-Dist: shapely>=2.0
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: pytest>=7.0; extra == "test"
|
|
22
|
+
Requires-Dist: lmdb; extra == "test"
|
|
23
|
+
Requires-Dist: pyarrow; extra == "test"
|
|
24
|
+
Provides-Extra: lmdb
|
|
25
|
+
Requires-Dist: lmdb; extra == "lmdb"
|
|
26
|
+
Provides-Extra: docs
|
|
27
|
+
Requires-Dist: sphinx>=8; extra == "docs"
|
|
28
|
+
Requires-Dist: sphinx-gallery>=0.17; extra == "docs"
|
|
29
|
+
Requires-Dist: pydata-sphinx-theme>=0.16; extra == "docs"
|
|
30
|
+
Requires-Dist: matplotlib; extra == "docs"
|
|
31
|
+
Provides-Extra: convert
|
|
32
|
+
Requires-Dist: paddlepaddle>=2.5; extra == "convert"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# torchOCR
|
|
36
|
+
|
|
37
|
+
**A PyTorch-native, end-to-end OCR library — batchable, GPU-first, and free of clunky C++ runtimes.**
|
|
38
|
+
|
|
39
|
+
[](https://github.com/BryanBradfo/torchOCR/actions/workflows/ci.yml) · [](https://pypi.org/project/torchocr/) · [ python · 3.10+ ] · [ pytorch · 2.0+ ] · [docs](https://bryanbradfo.github.io/torchOCR/) · [ license · BSD-3-Clause ]
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Why torchOCR
|
|
44
|
+
|
|
45
|
+
Every modern deep learning stack lives in PyTorch — except OCR. The dominant tools (Tesseract, PaddleOCR, EasyOCR) wrap C++ binaries, ship custom runtimes, or stitch together TensorFlow and ONNX detours that fight against PyTorch's batching, autograd, and `torch.compile`. The result is an ecosystem where reading text from an image is the only thing you can't do natively.
|
|
46
|
+
|
|
47
|
+
**torchOCR** is a clean-slate, pure-PyTorch OCR pipeline modeled after `torchvision`. Detection, recognition, and document-level data structures are first-class `nn.Module`s and dataclasses. Tensors stay on-device, batches stay batches, and the public API is small enough to read in an afternoon.
|
|
48
|
+
|
|
49
|
+
## Philosophy
|
|
50
|
+
|
|
51
|
+
- **Pure PyTorch.** No Tesseract, no Leptonica, no ONNX intermediaries. Every layer is `nn.Module` you can subclass, fine-tune, or `state_dict`-load.
|
|
52
|
+
- **PyTorch 2.0 first.** Every model FX-traces, `torch.export`s with dynamic sizes and `torch.compile`s — checked in CI, shape contracts included (see *Graph capture* below).
|
|
53
|
+
- **Explicit shape contracts.** Outputs are typed dataclasses (`DBNetOutput`), not `Dict[str, Tensor]`. Every model documents its tensor shapes — and asserts them at runtime.
|
|
54
|
+
- **Modular, torchvision-style API.** `from torchocr.models import DBNet, CRNN`. Models compose, swap, and re-export the way you'd expect from `torchvision.models`.
|
|
55
|
+
- **Zero magic at import time.** No global state, no monkey-patching, no network calls unless you ask for them.
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install torchocr
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
From source:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
git clone https://github.com/BryanBradfo/torchOCR.git
|
|
67
|
+
cd torchOCR
|
|
68
|
+
pip install -e .
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Requires Python 3.10+, PyTorch 2.0+, and torchvision 0.23+.
|
|
72
|
+
|
|
73
|
+
## Quickstart
|
|
74
|
+
|
|
75
|
+
### Image to text in three lines
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from torchocr import OCRPipeline, load_image
|
|
79
|
+
|
|
80
|
+
pipeline = OCRPipeline.from_pretrained(
|
|
81
|
+
detector_weights="DBNet_ResNet18_VD_Weights.ICDAR2015", # scene text, English
|
|
82
|
+
recognizer_weights="CRNN_ResNet34_VD_Weights.MJSYNTH_ICDAR2015_TOTALTEXT_MLT19", # Latin scene text
|
|
83
|
+
device="cuda", # or "cpu" (~4 s/page)
|
|
84
|
+
min_text_score=0.8, # drop unreadable regions
|
|
85
|
+
)
|
|
86
|
+
doc = pipeline(load_image("photo.jpg"))
|
|
87
|
+
doc.text # list[str], one per region, in reading order
|
|
88
|
+
doc.polygons # (K, 4, 2) rotated quads, reading order, in input pixels
|
|
89
|
+
doc.scores # (K,) recognition confidence
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Each stage brings its own preprocessing (`weights.transforms()`), post-processing
|
|
93
|
+
(`weights.meta["postprocess"]`), charset (`weights.meta["charset"]`) and decoder
|
|
94
|
+
(`weights.meta["decoder"]`: here CTC beam search with a character language model, downloaded on first
|
|
95
|
+
use); words are rectified out of the original-resolution image with `torchocr.ops.crop_quads`. The defaults
|
|
96
|
+
(`from_pretrained()` with no arguments) pair the multilingual PP-OCRv3 detector with the
|
|
97
|
+
Chinese + English recognizer, suited to documents.
|
|
98
|
+
|
|
99
|
+
### Building blocks
|
|
100
|
+
|
|
101
|
+
Every stage is an ordinary module or callable you can use, replace or fine-tune on its own:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
import torch
|
|
105
|
+
from torchocr import DBPostProcessor, load_charset
|
|
106
|
+
from torchocr.decoders import build_decoder
|
|
107
|
+
from torchocr.io import load_image
|
|
108
|
+
from torchocr.models import CRNN, DBNet, CRNN_ResNet34_VD_Weights, DBNet_ResNet18_VD_Weights
|
|
109
|
+
from torchocr.ops import crop_quads
|
|
110
|
+
|
|
111
|
+
image = load_image("photo.jpg") # (3, H, W) uint8 RGB
|
|
112
|
+
|
|
113
|
+
det_weights = DBNet_ResNet18_VD_Weights.ICDAR2015
|
|
114
|
+
detector = DBNet(weights=det_weights).eval()
|
|
115
|
+
batch = det_weights.transforms()(image)[None] # (1, 3, H', W'), multiples of 32
|
|
116
|
+
with torch.no_grad():
|
|
117
|
+
detection = detector(batch) # DBNetOutput(probability, threshold)
|
|
118
|
+
quads = DBPostProcessor(**det_weights.meta["postprocess"]).quadrilaterals(detection)[0] # (K, 4, 2)
|
|
119
|
+
quads = quads * torch.tensor([image.shape[2] / batch.shape[3], image.shape[1] / batch.shape[2]])
|
|
120
|
+
|
|
121
|
+
rec_weights = CRNN_ResNet34_VD_Weights.MJSYNTH_ICDAR2015_TOTALTEXT_MLT19
|
|
122
|
+
recognizer = CRNN(weights=rec_weights).eval()
|
|
123
|
+
page = rec_weights.transforms().normalize(image)[None].float()
|
|
124
|
+
crops, _ = crop_quads(page, quads, torch.zeros(len(quads), dtype=torch.long), height=32, max_width=320)
|
|
125
|
+
with torch.no_grad():
|
|
126
|
+
logits = recognizer(crops) # (T, K, num_classes), CTC-ready
|
|
127
|
+
charset = load_charset(rec_weights.meta["charset"], rec_weights.meta["num_classes"])
|
|
128
|
+
texts = build_decoder(rec_weights, charset)(logits) # beam search + character LM
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Augmenting text polygons with `torchvision.transforms.v2`
|
|
132
|
+
|
|
133
|
+
Text regions travel through torchvision's own v2 transforms as `tv_tensors.KeyPoints`; torchocr adds
|
|
134
|
+
the two OCR-specific pieces, a crop that never cuts a word and a sanitizer that keeps `texts` and
|
|
135
|
+
`ignore` aligned with the polygons that survive.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from torchvision.transforms import v2
|
|
139
|
+
from torchocr.datasets import TotalText
|
|
140
|
+
from torchocr.transforms import MakeDBTargets
|
|
141
|
+
from torchocr.transforms.v2 import RandomTextCrop, SanitizeTextPolygons, wrap_sample
|
|
142
|
+
|
|
143
|
+
augment = v2.Compose([
|
|
144
|
+
v2.RandomRotation(10), v2.RandomAffine(0, scale=(0.5, 3.0)),
|
|
145
|
+
RandomTextCrop(), v2.Resize(size=None, max_size=640),
|
|
146
|
+
SanitizeTextPolygons(), # off-canvas words dropped, clipped ones marked don't-care
|
|
147
|
+
])
|
|
148
|
+
image, target = augment(*wrap_sample(*TotalText("~/data/totaltext", split="train")[0]))
|
|
149
|
+
db_targets = MakeDBTargets()(target.polygons, target.ignore, image.shape[-2:])
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Graph capture: `torch.compile`, `torch.export`, FX
|
|
153
|
+
|
|
154
|
+
Every model is tested (`tests/test_compile_export.py`) to FX-trace, `torch.export` and `torch.compile`,
|
|
155
|
+
with its runtime shape contract intact:
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from torch.export import Dim, export
|
|
159
|
+
|
|
160
|
+
# Detector: one fused graph, ~1.2x faster on GPU (ResNet18-VD at 736x1280: 25.0 -> 20.3 ms).
|
|
161
|
+
detector = torch.compile(DBNet(weights="DBNet_ResNet18_VD_Weights.ICDAR2015").eval(), fullgraph=True)
|
|
162
|
+
|
|
163
|
+
# Ahead-of-time export with any image size that is a multiple of 32.
|
|
164
|
+
side = lambda name: 32 * Dim(name, min=1, max=128)
|
|
165
|
+
program = export(DBNet(backbone="resnet18_vd").eval(), (torch.randn(1, 3, 736, 1280),),
|
|
166
|
+
dynamic_shapes=({2: side("h"), 3: side("w")},))
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`CRNN` exports with a dynamic batch but a static crop width, because `torch.export` specializes
|
|
170
|
+
`nn.LSTM`'s sequence length; inference already pads every crop to `max_width`. Under
|
|
171
|
+
`torch.compile` it graph-breaks at the LSTM (a Dynamo limitation), so `fullgraph=True` applies to
|
|
172
|
+
the detector only. Compiled outputs match eager to ~1e-3 (Inductor reorders floating-point
|
|
173
|
+
operations); published metrics are measured in eager mode.
|
|
174
|
+
|
|
175
|
+
## Architecture
|
|
176
|
+
|
|
177
|
+
| Component | Module | What it is |
|
|
178
|
+
| --- | --- | --- |
|
|
179
|
+
| `DBNet` | `torchocr.models` | Differentiable Binarization detector: ResNet-18-VD + FPN or MobileNetV3-large ×0.5 + RSEFPN backbone, probability and threshold heads. Returns a typed `DBNetOutput`. |
|
|
180
|
+
| `CRNN` | `torchocr.models` | Convolutional recurrent recognizer: ResNet-34-VD (or VGG-style) CNN, two bidirectional LSTMs, linear classifier. Returns CTC logits `(T, B, num_classes)`. |
|
|
181
|
+
| `DBPostProcessor` | `torchocr` | Probability map → rotated word quads in reading order. |
|
|
182
|
+
| `CTCGreedyDecoder`, `CTCBeamDecoder`, `CharNGramLM` | `torchocr.decoders` | CTC decoding, optionally fused with a character language model. |
|
|
183
|
+
| `OCRPipeline`, `DocumentTensor` | `torchocr` | Composition of the stages; a dataclass holding the input image, texts, quads, boxes and confidences. |
|
|
184
|
+
|
|
185
|
+
Both models enforce their input contracts at runtime (`DBNet`: `(B, 3, H, W)` with `H, W ≡ 0 (mod 32)`;
|
|
186
|
+
`CRNN`: `(B, 3, 32, W)`) and raise `ValueError` with the offending shape.
|
|
187
|
+
|
|
188
|
+
## Status
|
|
189
|
+
|
|
190
|
+
| Capability | State |
|
|
191
|
+
| --- | --- |
|
|
192
|
+
| `DBNet` / `CRNN` architectures + shape contracts | ✅ Implemented |
|
|
193
|
+
| Pretrained weights (`*_Weights` enums, hash-checked, on [Hugging Face](https://huggingface.co/BryanBradfo/torchocr-weights)) | ✅ 4 PaddleOCR conversions + 5 torchocr-trained checkpoints |
|
|
194
|
+
| DB post-processing (contours → rotated quads) | ✅ Implemented |
|
|
195
|
+
| `torchocr.ops.crop_quads` (batched perspective rectification) | ✅ Implemented |
|
|
196
|
+
| `torchocr.metrics` (ICDAR hmean, word accuracy / CER) and `torchocr.datasets.ICDAR2015` | ✅ Implemented |
|
|
197
|
+
| DB training (`references/detection/train.py`) | ✅ Implemented |
|
|
198
|
+
| CTC greedy and beam-search decoding (character n-gram LM) | ✅ Implemented |
|
|
199
|
+
| Datasets: ICDAR-2015, Total-Text, FUNSD, LMDB word crops | ✅ Implemented |
|
|
200
|
+
| End-to-end `OCRPipeline.from_pretrained` (image → text, reading order) | ✅ Implemented |
|
|
201
|
+
| Polygon-aware augmentation on `torchvision.transforms.v2` (`torchocr.transforms.v2`) | ✅ Implemented |
|
|
202
|
+
| Synthetic pre-training data (MJSynth via Parquet → LMDB) | ✅ Implemented |
|
|
203
|
+
| Sphinx documentation site with example gallery (`docs/`, `gallery/`) | ✅ Implemented |
|
|
204
|
+
|
|
205
|
+
Benchmarks (official IoU protocol, reproducible with `references/`; fine-tuned weights are the last epoch,
|
|
206
|
+
thresholds chosen on training splits only):
|
|
207
|
+
|
|
208
|
+
| Detection (test hmean) | ICDAR-2015 | Total-Text | FUNSD |
|
|
209
|
+
| --- | --- | --- | --- |
|
|
210
|
+
| `DBNet_ResNet18_VD_Weights.ICDAR2015` (trained by torchocr, 12.4 M params) | **0.809** | 0.696 | **0.826** |
|
|
211
|
+
| `DBNet_MobileNetV3_Large_05_Weights.ICDAR2015` (trained by torchocr, 0.6 M params) | 0.734 | | |
|
|
212
|
+
| `DBNet_MobileNetV3_Large_05_Weights.PPOCR_V3_EN` (converted, line-level) | 0.441 | | 0.180 |
|
|
213
|
+
|
|
214
|
+
| Recognition (word accuracy on ground-truth words) | ICDAR-2015 | Total-Text |
|
|
215
|
+
| --- | --- | --- |
|
|
216
|
+
| `CRNN_ResNet34_VD_Weights.MJSYNTH_ICDAR2015_TOTALTEXT_MLT19` + beam search & char LM | **0.799** | **0.819** |
|
|
217
|
+
| `CRNN_ResNet34_VD_Weights.ICDAR2015_TOTALTEXT_MLT19` + beam search & char LM | 0.791 | 0.802 |
|
|
218
|
+
| `CRNN_ResNet34_VD_Weights.ICDAR2015` (greedy) | 0.738 | |
|
|
219
|
+
| `CRNN_ResNet34_VD_Weights.PPOCR_SERVER_V2` (converted, greedy) | 0.665 | 0.701 |
|
|
220
|
+
|
|
221
|
+
End to end (`OCRPipeline`, image → text; a word counts when detected *and* read correctly,
|
|
222
|
+
case-insensitive, generic vocabulary; `references/end2end/evaluate.py`), with the two bold models and
|
|
223
|
+
`min_text_score=0.8`: **0.665** on ICDAR-2015 (0.219 with the converted PaddleOCR weights), **0.585** on
|
|
224
|
+
Total-Text and **0.722** on FUNSD scanned forms; ~60 ms per street image on a laptop GPU.
|
|
225
|
+
|
|
226
|
+
`weights.meta` documents each checkpoint's provenance, license, preprocessing and known limits.
|
|
227
|
+
|
|
228
|
+
## Roadmap
|
|
229
|
+
|
|
230
|
+
- **Distribution**: PyPI release (`pip install torchocr`) and a hosted documentation site.
|
|
231
|
+
- **Detection**: detectors pre-trained on SynthText and fine-tuned on curved text (Total-Text is the weakest benchmark).
|
|
232
|
+
- **Recognition**: an ASCII-only recognizer head and a multilingual variant; an attention/transformer recognizer.
|
|
233
|
+
- **Deployment**: `torch.ao` quantization and ONNX / `torch.export` packaging of both models.
|
|
234
|
+
|
|
235
|
+
## Documentation
|
|
236
|
+
|
|
237
|
+
Online at **https://bryanbradfo.github.io/torchOCR/** (API reference, pretrained weights, benchmarks, example gallery). To build it locally:
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
pip install -e ".[docs]"
|
|
241
|
+
sphinx-build -b html docs docs/_build/html # TORCHOCR_DOCS_GALLERY=0 skips running the examples
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Running the tests
|
|
245
|
+
|
|
246
|
+
```bash
|
|
247
|
+
pip install -e ".[test]"
|
|
248
|
+
pytest
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Contributing
|
|
252
|
+
|
|
253
|
+
Issues and PRs welcome. Each model in `src/torchocr/models/` documents its shape contract in the docstring; please match the existing style (`from torch import Tensor, nn`, Google-style docstrings, `Tensor | None` unions). See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the full coding standards and PR process.
|
|
254
|
+
|
|
255
|
+
## License
|
|
256
|
+
|
|
257
|
+
BSD 3-Clause, like torchvision — see `LICENSE`.
|
torchocr-0.4.1/README.md
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# torchOCR
|
|
2
|
+
|
|
3
|
+
**A PyTorch-native, end-to-end OCR library — batchable, GPU-first, and free of clunky C++ runtimes.**
|
|
4
|
+
|
|
5
|
+
[](https://github.com/BryanBradfo/torchOCR/actions/workflows/ci.yml) · [](https://pypi.org/project/torchocr/) · [ python · 3.10+ ] · [ pytorch · 2.0+ ] · [docs](https://bryanbradfo.github.io/torchOCR/) · [ license · BSD-3-Clause ]
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Why torchOCR
|
|
10
|
+
|
|
11
|
+
Every modern deep learning stack lives in PyTorch — except OCR. The dominant tools (Tesseract, PaddleOCR, EasyOCR) wrap C++ binaries, ship custom runtimes, or stitch together TensorFlow and ONNX detours that fight against PyTorch's batching, autograd, and `torch.compile`. The result is an ecosystem where reading text from an image is the only thing you can't do natively.
|
|
12
|
+
|
|
13
|
+
**torchOCR** is a clean-slate, pure-PyTorch OCR pipeline modeled after `torchvision`. Detection, recognition, and document-level data structures are first-class `nn.Module`s and dataclasses. Tensors stay on-device, batches stay batches, and the public API is small enough to read in an afternoon.
|
|
14
|
+
|
|
15
|
+
## Philosophy
|
|
16
|
+
|
|
17
|
+
- **Pure PyTorch.** No Tesseract, no Leptonica, no ONNX intermediaries. Every layer is `nn.Module` you can subclass, fine-tune, or `state_dict`-load.
|
|
18
|
+
- **PyTorch 2.0 first.** Every model FX-traces, `torch.export`s with dynamic sizes and `torch.compile`s — checked in CI, shape contracts included (see *Graph capture* below).
|
|
19
|
+
- **Explicit shape contracts.** Outputs are typed dataclasses (`DBNetOutput`), not `Dict[str, Tensor]`. Every model documents its tensor shapes — and asserts them at runtime.
|
|
20
|
+
- **Modular, torchvision-style API.** `from torchocr.models import DBNet, CRNN`. Models compose, swap, and re-export the way you'd expect from `torchvision.models`.
|
|
21
|
+
- **Zero magic at import time.** No global state, no monkey-patching, no network calls unless you ask for them.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install torchocr
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
From source:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
git clone https://github.com/BryanBradfo/torchOCR.git
|
|
33
|
+
cd torchOCR
|
|
34
|
+
pip install -e .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Requires Python 3.10+, PyTorch 2.0+, and torchvision 0.23+.
|
|
38
|
+
|
|
39
|
+
## Quickstart
|
|
40
|
+
|
|
41
|
+
### Image to text in three lines
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from torchocr import OCRPipeline, load_image
|
|
45
|
+
|
|
46
|
+
pipeline = OCRPipeline.from_pretrained(
|
|
47
|
+
detector_weights="DBNet_ResNet18_VD_Weights.ICDAR2015", # scene text, English
|
|
48
|
+
recognizer_weights="CRNN_ResNet34_VD_Weights.MJSYNTH_ICDAR2015_TOTALTEXT_MLT19", # Latin scene text
|
|
49
|
+
device="cuda", # or "cpu" (~4 s/page)
|
|
50
|
+
min_text_score=0.8, # drop unreadable regions
|
|
51
|
+
)
|
|
52
|
+
doc = pipeline(load_image("photo.jpg"))
|
|
53
|
+
doc.text # list[str], one per region, in reading order
|
|
54
|
+
doc.polygons # (K, 4, 2) rotated quads, reading order, in input pixels
|
|
55
|
+
doc.scores # (K,) recognition confidence
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Each stage brings its own preprocessing (`weights.transforms()`), post-processing
|
|
59
|
+
(`weights.meta["postprocess"]`), charset (`weights.meta["charset"]`) and decoder
|
|
60
|
+
(`weights.meta["decoder"]`: here CTC beam search with a character language model, downloaded on first
|
|
61
|
+
use); words are rectified out of the original-resolution image with `torchocr.ops.crop_quads`. The defaults
|
|
62
|
+
(`from_pretrained()` with no arguments) pair the multilingual PP-OCRv3 detector with the
|
|
63
|
+
Chinese + English recognizer, suited to documents.
|
|
64
|
+
|
|
65
|
+
### Building blocks
|
|
66
|
+
|
|
67
|
+
Every stage is an ordinary module or callable you can use, replace or fine-tune on its own:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import torch
|
|
71
|
+
from torchocr import DBPostProcessor, load_charset
|
|
72
|
+
from torchocr.decoders import build_decoder
|
|
73
|
+
from torchocr.io import load_image
|
|
74
|
+
from torchocr.models import CRNN, DBNet, CRNN_ResNet34_VD_Weights, DBNet_ResNet18_VD_Weights
|
|
75
|
+
from torchocr.ops import crop_quads
|
|
76
|
+
|
|
77
|
+
image = load_image("photo.jpg") # (3, H, W) uint8 RGB
|
|
78
|
+
|
|
79
|
+
det_weights = DBNet_ResNet18_VD_Weights.ICDAR2015
|
|
80
|
+
detector = DBNet(weights=det_weights).eval()
|
|
81
|
+
batch = det_weights.transforms()(image)[None] # (1, 3, H', W'), multiples of 32
|
|
82
|
+
with torch.no_grad():
|
|
83
|
+
detection = detector(batch) # DBNetOutput(probability, threshold)
|
|
84
|
+
quads = DBPostProcessor(**det_weights.meta["postprocess"]).quadrilaterals(detection)[0] # (K, 4, 2)
|
|
85
|
+
quads = quads * torch.tensor([image.shape[2] / batch.shape[3], image.shape[1] / batch.shape[2]])
|
|
86
|
+
|
|
87
|
+
rec_weights = CRNN_ResNet34_VD_Weights.MJSYNTH_ICDAR2015_TOTALTEXT_MLT19
|
|
88
|
+
recognizer = CRNN(weights=rec_weights).eval()
|
|
89
|
+
page = rec_weights.transforms().normalize(image)[None].float()
|
|
90
|
+
crops, _ = crop_quads(page, quads, torch.zeros(len(quads), dtype=torch.long), height=32, max_width=320)
|
|
91
|
+
with torch.no_grad():
|
|
92
|
+
logits = recognizer(crops) # (T, K, num_classes), CTC-ready
|
|
93
|
+
charset = load_charset(rec_weights.meta["charset"], rec_weights.meta["num_classes"])
|
|
94
|
+
texts = build_decoder(rec_weights, charset)(logits) # beam search + character LM
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Augmenting text polygons with `torchvision.transforms.v2`
|
|
98
|
+
|
|
99
|
+
Text regions travel through torchvision's own v2 transforms as `tv_tensors.KeyPoints`; torchocr adds
|
|
100
|
+
the two OCR-specific pieces, a crop that never cuts a word and a sanitizer that keeps `texts` and
|
|
101
|
+
`ignore` aligned with the polygons that survive.
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from torchvision.transforms import v2
|
|
105
|
+
from torchocr.datasets import TotalText
|
|
106
|
+
from torchocr.transforms import MakeDBTargets
|
|
107
|
+
from torchocr.transforms.v2 import RandomTextCrop, SanitizeTextPolygons, wrap_sample
|
|
108
|
+
|
|
109
|
+
augment = v2.Compose([
|
|
110
|
+
v2.RandomRotation(10), v2.RandomAffine(0, scale=(0.5, 3.0)),
|
|
111
|
+
RandomTextCrop(), v2.Resize(size=None, max_size=640),
|
|
112
|
+
SanitizeTextPolygons(), # off-canvas words dropped, clipped ones marked don't-care
|
|
113
|
+
])
|
|
114
|
+
image, target = augment(*wrap_sample(*TotalText("~/data/totaltext", split="train")[0]))
|
|
115
|
+
db_targets = MakeDBTargets()(target.polygons, target.ignore, image.shape[-2:])
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Graph capture: `torch.compile`, `torch.export`, FX
|
|
119
|
+
|
|
120
|
+
Every model is tested (`tests/test_compile_export.py`) to FX-trace, `torch.export` and `torch.compile`,
|
|
121
|
+
with its runtime shape contract intact:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from torch.export import Dim, export
|
|
125
|
+
|
|
126
|
+
# Detector: one fused graph, ~1.2x faster on GPU (ResNet18-VD at 736x1280: 25.0 -> 20.3 ms).
|
|
127
|
+
detector = torch.compile(DBNet(weights="DBNet_ResNet18_VD_Weights.ICDAR2015").eval(), fullgraph=True)
|
|
128
|
+
|
|
129
|
+
# Ahead-of-time export with any image size that is a multiple of 32.
|
|
130
|
+
side = lambda name: 32 * Dim(name, min=1, max=128)
|
|
131
|
+
program = export(DBNet(backbone="resnet18_vd").eval(), (torch.randn(1, 3, 736, 1280),),
|
|
132
|
+
dynamic_shapes=({2: side("h"), 3: side("w")},))
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`CRNN` exports with a dynamic batch but a static crop width, because `torch.export` specializes
|
|
136
|
+
`nn.LSTM`'s sequence length; inference already pads every crop to `max_width`. Under
|
|
137
|
+
`torch.compile` it graph-breaks at the LSTM (a Dynamo limitation), so `fullgraph=True` applies to
|
|
138
|
+
the detector only. Compiled outputs match eager to ~1e-3 (Inductor reorders floating-point
|
|
139
|
+
operations); published metrics are measured in eager mode.
|
|
140
|
+
|
|
141
|
+
## Architecture
|
|
142
|
+
|
|
143
|
+
| Component | Module | What it is |
|
|
144
|
+
| --- | --- | --- |
|
|
145
|
+
| `DBNet` | `torchocr.models` | Differentiable Binarization detector: ResNet-18-VD + FPN or MobileNetV3-large ×0.5 + RSEFPN backbone, probability and threshold heads. Returns a typed `DBNetOutput`. |
|
|
146
|
+
| `CRNN` | `torchocr.models` | Convolutional recurrent recognizer: ResNet-34-VD (or VGG-style) CNN, two bidirectional LSTMs, linear classifier. Returns CTC logits `(T, B, num_classes)`. |
|
|
147
|
+
| `DBPostProcessor` | `torchocr` | Probability map → rotated word quads in reading order. |
|
|
148
|
+
| `CTCGreedyDecoder`, `CTCBeamDecoder`, `CharNGramLM` | `torchocr.decoders` | CTC decoding, optionally fused with a character language model. |
|
|
149
|
+
| `OCRPipeline`, `DocumentTensor` | `torchocr` | Composition of the stages; a dataclass holding the input image, texts, quads, boxes and confidences. |
|
|
150
|
+
|
|
151
|
+
Both models enforce their input contracts at runtime (`DBNet`: `(B, 3, H, W)` with `H, W ≡ 0 (mod 32)`;
|
|
152
|
+
`CRNN`: `(B, 3, 32, W)`) and raise `ValueError` with the offending shape.
|
|
153
|
+
|
|
154
|
+
## Status
|
|
155
|
+
|
|
156
|
+
| Capability | State |
|
|
157
|
+
| --- | --- |
|
|
158
|
+
| `DBNet` / `CRNN` architectures + shape contracts | ✅ Implemented |
|
|
159
|
+
| Pretrained weights (`*_Weights` enums, hash-checked, on [Hugging Face](https://huggingface.co/BryanBradfo/torchocr-weights)) | ✅ 4 PaddleOCR conversions + 5 torchocr-trained checkpoints |
|
|
160
|
+
| DB post-processing (contours → rotated quads) | ✅ Implemented |
|
|
161
|
+
| `torchocr.ops.crop_quads` (batched perspective rectification) | ✅ Implemented |
|
|
162
|
+
| `torchocr.metrics` (ICDAR hmean, word accuracy / CER) and `torchocr.datasets.ICDAR2015` | ✅ Implemented |
|
|
163
|
+
| DB training (`references/detection/train.py`) | ✅ Implemented |
|
|
164
|
+
| CTC greedy and beam-search decoding (character n-gram LM) | ✅ Implemented |
|
|
165
|
+
| Datasets: ICDAR-2015, Total-Text, FUNSD, LMDB word crops | ✅ Implemented |
|
|
166
|
+
| End-to-end `OCRPipeline.from_pretrained` (image → text, reading order) | ✅ Implemented |
|
|
167
|
+
| Polygon-aware augmentation on `torchvision.transforms.v2` (`torchocr.transforms.v2`) | ✅ Implemented |
|
|
168
|
+
| Synthetic pre-training data (MJSynth via Parquet → LMDB) | ✅ Implemented |
|
|
169
|
+
| Sphinx documentation site with example gallery (`docs/`, `gallery/`) | ✅ Implemented |
|
|
170
|
+
|
|
171
|
+
Benchmarks (official IoU protocol, reproducible with `references/`; fine-tuned weights are the last epoch,
|
|
172
|
+
thresholds chosen on training splits only):
|
|
173
|
+
|
|
174
|
+
| Detection (test hmean) | ICDAR-2015 | Total-Text | FUNSD |
|
|
175
|
+
| --- | --- | --- | --- |
|
|
176
|
+
| `DBNet_ResNet18_VD_Weights.ICDAR2015` (trained by torchocr, 12.4 M params) | **0.809** | 0.696 | **0.826** |
|
|
177
|
+
| `DBNet_MobileNetV3_Large_05_Weights.ICDAR2015` (trained by torchocr, 0.6 M params) | 0.734 | | |
|
|
178
|
+
| `DBNet_MobileNetV3_Large_05_Weights.PPOCR_V3_EN` (converted, line-level) | 0.441 | | 0.180 |
|
|
179
|
+
|
|
180
|
+
| Recognition (word accuracy on ground-truth words) | ICDAR-2015 | Total-Text |
|
|
181
|
+
| --- | --- | --- |
|
|
182
|
+
| `CRNN_ResNet34_VD_Weights.MJSYNTH_ICDAR2015_TOTALTEXT_MLT19` + beam search & char LM | **0.799** | **0.819** |
|
|
183
|
+
| `CRNN_ResNet34_VD_Weights.ICDAR2015_TOTALTEXT_MLT19` + beam search & char LM | 0.791 | 0.802 |
|
|
184
|
+
| `CRNN_ResNet34_VD_Weights.ICDAR2015` (greedy) | 0.738 | |
|
|
185
|
+
| `CRNN_ResNet34_VD_Weights.PPOCR_SERVER_V2` (converted, greedy) | 0.665 | 0.701 |
|
|
186
|
+
|
|
187
|
+
End to end (`OCRPipeline`, image → text; a word counts when detected *and* read correctly,
|
|
188
|
+
case-insensitive, generic vocabulary; `references/end2end/evaluate.py`), with the two bold models and
|
|
189
|
+
`min_text_score=0.8`: **0.665** on ICDAR-2015 (0.219 with the converted PaddleOCR weights), **0.585** on
|
|
190
|
+
Total-Text and **0.722** on FUNSD scanned forms; ~60 ms per street image on a laptop GPU.
|
|
191
|
+
|
|
192
|
+
`weights.meta` documents each checkpoint's provenance, license, preprocessing and known limits.
|
|
193
|
+
|
|
194
|
+
## Roadmap
|
|
195
|
+
|
|
196
|
+
- **Distribution**: PyPI release (`pip install torchocr`) and a hosted documentation site.
|
|
197
|
+
- **Detection**: detectors pre-trained on SynthText and fine-tuned on curved text (Total-Text is the weakest benchmark).
|
|
198
|
+
- **Recognition**: an ASCII-only recognizer head and a multilingual variant; an attention/transformer recognizer.
|
|
199
|
+
- **Deployment**: `torch.ao` quantization and ONNX / `torch.export` packaging of both models.
|
|
200
|
+
|
|
201
|
+
## Documentation
|
|
202
|
+
|
|
203
|
+
Online at **https://bryanbradfo.github.io/torchOCR/** (API reference, pretrained weights, benchmarks, example gallery). To build it locally:
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
pip install -e ".[docs]"
|
|
207
|
+
sphinx-build -b html docs docs/_build/html # TORCHOCR_DOCS_GALLERY=0 skips running the examples
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Running the tests
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
pip install -e ".[test]"
|
|
214
|
+
pytest
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Contributing
|
|
218
|
+
|
|
219
|
+
Issues and PRs welcome. Each model in `src/torchocr/models/` documents its shape contract in the docstring; please match the existing style (`from torch import Tensor, nn`, Google-style docstrings, `Tensor | None` unions). See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the full coding standards and PR process.
|
|
220
|
+
|
|
221
|
+
## License
|
|
222
|
+
|
|
223
|
+
BSD 3-Clause, like torchvision — see `LICENSE`.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"] # SPDX `license` expression
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "torchocr"
|
|
7
|
+
version = "0.4.1"
|
|
8
|
+
description = "PyTorch-native end-to-end OCR pipeline."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "BSD-3-Clause"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"torch",
|
|
15
|
+
"torchvision>=0.23", # tv_tensors.KeyPoints (torchocr.transforms.v2)
|
|
16
|
+
"pymupdf",
|
|
17
|
+
"scipy",
|
|
18
|
+
"opencv-python-headless",
|
|
19
|
+
"pyclipper",
|
|
20
|
+
"shapely>=2.0",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Documentation = "https://bryanbradfo.github.io/torchOCR/"
|
|
25
|
+
Source = "https://github.com/BryanBradfo/torchOCR"
|
|
26
|
+
Changelog = "https://github.com/BryanBradfo/torchOCR/blob/main/CHANGELOG.md"
|
|
27
|
+
Weights = "https://huggingface.co/BryanBradfo/torchocr-weights"
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
test = [
|
|
31
|
+
"pytest>=7.0",
|
|
32
|
+
"lmdb",
|
|
33
|
+
"pyarrow",
|
|
34
|
+
]
|
|
35
|
+
lmdb = [
|
|
36
|
+
"lmdb",
|
|
37
|
+
]
|
|
38
|
+
docs = [
|
|
39
|
+
"sphinx>=8",
|
|
40
|
+
"sphinx-gallery>=0.17",
|
|
41
|
+
"pydata-sphinx-theme>=0.16",
|
|
42
|
+
"matplotlib",
|
|
43
|
+
]
|
|
44
|
+
convert = [
|
|
45
|
+
"paddlepaddle>=2.5",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[tool.setuptools]
|
|
49
|
+
package-dir = {"" = "src"}
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.packages.find]
|
|
52
|
+
where = ["src"]
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.package-data]
|
|
55
|
+
torchocr = ["data/*.txt"]
|
|
56
|
+
|
|
57
|
+
[tool.pytest.ini_options]
|
|
58
|
+
pythonpath = ["src"]
|
|
59
|
+
testpaths = ["tests"]
|
torchocr-0.4.1/setup.cfg
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
|
+
]
|
|
@@ -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."""
|