torchocr.models#

See Models and pretrained weights for every pretrained weights entry and its benchmark.

Detection#

class torchocr.models.DBNet(backbone=None, weights=None, pretrained_backbone=False, fpn_out_channels=256, head_inner_channels=64)[source]#

Bases: Module

DBNet text detector.

The model produces a probability map and a threshold map at the input resolution. The differentiable-binarization combination of the two maps is a training-time loss helper and lives outside this module.

Parameters:
  • backbone (Literal['resnet18', 'resnet18_vd', 'mobilenet_v3_large_05'] | None) – Which backbone to instantiate. "resnet18" uses torchvision’s ResNet-18 with its 7x7 stem and is what torchocr trains from scratch (no published OCR weights). "resnet18_vd" and "mobilenet_v3_large_05" mirror PaddleOCR’s detectors so converted checkpoints load as-is. Default None: taken from weights when it is an enum member, else "resnet18".

  • weights (WeightsEnum | str | None) – Pretrained OCR weights – a member of DBNet_ResNet18_VD_Weights or DBNet_MobileNetV3_Large_05_Weights, or a member name such as "DEFAULT" resolved against backbone. If the download fails a UserWarning is emitted and the model keeps its random initialization. Pair with weights.transforms() for the matching preprocessing. Default None (random init). pretrained_backbone is ignored for the PaddleOCR-style backbones since no canonical ImageNet weights ship with torchvision for them.

  • pretrained_backbone (bool) – If True and backbone="resnet18", load ImageNet weights for the torchvision ResNet-18 backbone. Default False to keep instantiation offline-safe.

  • fpn_out_channels (int) – Channels per FPN level. Default 256.

  • head_inner_channels (int) – Inner channels of the probability and threshold heads. Used only on the resnet18 path; the resnet18_vd path uses fpn_out_channels // 4 to match PaddleOCR.

Note

The resnet18 backbone is wrapped via create_feature_extractor (FX-traced). Custom backbones with data-dependent control flow may fail to trace. The resnet18_vd path bypasses FX tracing.

forward(images)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Parameters:

images (Tensor)

Return type:

DBNetOutput

class torchocr.models.DBNetOutput(probability, threshold)[source]#

Bases: object

Probability and threshold maps from a DBNet forward pass.

Parameters:
torchocr.models.dbnet_resnet18_vd(*, weights=None, **kwargs)[source]#

DBNet with PaddleOCR’s ResNet-18-VD backbone; see DBNet_ResNet18_VD_Weights.

Parameters:
Return type:

DBNet

torchocr.models.dbnet_resnet18(**kwargs)[source]#

DBNet with torchvision’s ResNet-18 backbone (no published OCR weights).

Parameters:

kwargs (object)

Return type:

DBNet

torchocr.models.dbnet_mobilenet_v3_large_05(*, weights=None, **kwargs)[source]#

PP-OCRv3 detector (MobileNetV3-large x0.5 + RSEFPN); see DBNet_MobileNetV3_Large_05_Weights.

Parameters:
Return type:

DBNet

class torchocr.models.DBNet_ResNet18_VD_Weights(*values)[source]#

Bases: WeightsEnum

PPOCR_SERVER_V2 = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/dbnet_resnet18_vd_ppocr_server_v2-59d99b11.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.DetectionPreset'>, max_side=960, channel_order='bgr'), meta={'task': 'detection', 'backbone': 'resnet18_vd', 'num_params': 12364386, 'source': 'PaddleOCR ch_ppocr_server_v2.0_det_train, via scripts/convert_paddle_dbnet.py', 'license': 'Apache-2.0', 'languages': ['ch', 'en'], 'postprocess': {'threshold': 0.3, 'box_thresh': 0.6, 'unclip_ratio': 1.5}, '_metrics': {'ICDAR2015-test': {'precision': 0.5814, 'recall': 0.3216, 'hmean': 0.4141}}, '_docs': "Trained by PaddleOCR on line-level annotations of mostly Chinese/English document and scene text, then converted to PyTorch. ICDAR-2015 scores *word* boxes in low-resolution street scenes, so adjacent words merged into one line count as misses; use this number to compare checkpoints, not as the accuracy you will see on documents. ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; transforms() preset, DBPostProcessor(**meta['postprocess']). Reproduce with references/detection/evaluate.py --weights <this enum>."})#
ICDAR2015 = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/dbnet_resnet18_vd_ic15-d803cec9.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.DetectionPreset'>, max_side=1280, channel_order='bgr'), meta={'task': 'detection', 'backbone': 'resnet18_vd', 'num_params': 12364386, 'source': 'torchocr: PPOCR_SERVER_V2 fine-tuned 300 epochs on the 1000 ICDAR-2015 training images with references/detection/train.py', 'license': 'Apache-2.0 (base weights); fine-tuned on ICDAR 2015, released for research use', 'languages': ['en'], 'postprocess': {'threshold': 0.3, 'box_thresh': 0.5, 'unclip_ratio': 1.5}, '_metrics': {'ICDAR2015-test': {'precision': 0.8485, 'recall': 0.7737, 'hmean': 0.8094}}, '_docs': "Word-level detector for incidental scene text (street-level photos, Latin script). box_thresh=0.5 maximizes hmean on the *training* split (references/detection/calibrate.py) and was applied once to the test split; with PaddleOCR's box_thresh=0.6 this checkpoint scores 0.794. Weights are the last epoch -- no checkpoint was selected on the test set. Expect lower recall on dense documents and on non-Latin scripts. ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; transforms() preset, DBPostProcessor(**meta['postprocess']). Reproduce with references/detection/evaluate.py --weights <this enum>."})#
DEFAULT = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/dbnet_resnet18_vd_ppocr_server_v2-59d99b11.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.DetectionPreset'>, max_side=960, channel_order='bgr'), meta={'task': 'detection', 'backbone': 'resnet18_vd', 'num_params': 12364386, 'source': 'PaddleOCR ch_ppocr_server_v2.0_det_train, via scripts/convert_paddle_dbnet.py', 'license': 'Apache-2.0', 'languages': ['ch', 'en'], 'postprocess': {'threshold': 0.3, 'box_thresh': 0.6, 'unclip_ratio': 1.5}, '_metrics': {'ICDAR2015-test': {'precision': 0.5814, 'recall': 0.3216, 'hmean': 0.4141}}, '_docs': "Trained by PaddleOCR on line-level annotations of mostly Chinese/English document and scene text, then converted to PyTorch. ICDAR-2015 scores *word* boxes in low-resolution street scenes, so adjacent words merged into one line count as misses; use this number to compare checkpoints, not as the accuracy you will see on documents. ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; transforms() preset, DBPostProcessor(**meta['postprocess']). Reproduce with references/detection/evaluate.py --weights <this enum>."})#
class torchocr.models.DBNet_MobileNetV3_Large_05_Weights(*values)[source]#

Bases: WeightsEnum

PPOCR_V3_CH = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/dbnet_mobilenet_v3_large_05_ppocr_v3_ch-fc000d1e.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.DetectionPreset'>, max_side=960, channel_order='bgr'), meta={'task': 'detection', 'backbone': 'mobilenet_v3_large_05', 'num_params': 603418, 'source': 'PaddleOCR ch_PP-OCRv3_det_distill_train (Student), via scripts/convert_paddle_dbnet_v3.py', 'license': 'Apache-2.0', 'languages': ['ch', 'en'], 'postprocess': {'threshold': 0.3, 'box_thresh': 0.6, 'unclip_ratio': 1.5}, '_metrics': {'ICDAR2015-test': {'precision': 0.5641, 'recall': 0.337, 'hmean': 0.4219}}, '_docs': "Trained by PaddleOCR on line-level annotations of mostly Chinese/English document and scene text, then converted to PyTorch. ICDAR-2015 scores *word* boxes in low-resolution street scenes, so adjacent words merged into one line count as misses; use this number to compare checkpoints, not as the accuracy you will see on documents. ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; transforms() preset, DBPostProcessor(**meta['postprocess']). Reproduce with references/detection/evaluate.py --weights <this enum>."})#
PPOCR_V3_EN = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/dbnet_mobilenet_v3_large_05_ppocr_v3_en-9bfd3b59.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.DetectionPreset'>, max_side=960, channel_order='bgr'), meta={'task': 'detection', 'backbone': 'mobilenet_v3_large_05', 'num_params': 603418, 'source': 'PaddleOCR en_PP-OCRv3_det_distill_train (Student), via scripts/convert_paddle_dbnet_v3.py', 'license': 'Apache-2.0', 'languages': ['en'], 'postprocess': {'threshold': 0.3, 'box_thresh': 0.6, 'unclip_ratio': 1.5}, '_metrics': {'ICDAR2015-test': {'precision': 0.5342, 'recall': 0.3755, 'hmean': 0.4411}}, '_docs': "Trained by PaddleOCR on line-level annotations of mostly Chinese/English document and scene text, then converted to PyTorch. ICDAR-2015 scores *word* boxes in low-resolution street scenes, so adjacent words merged into one line count as misses; use this number to compare checkpoints, not as the accuracy you will see on documents. ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; transforms() preset, DBPostProcessor(**meta['postprocess']). Reproduce with references/detection/evaluate.py --weights <this enum>."})#
ICDAR2015 = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/dbnet_mobilenet_v3_large_05_ic15-d9d17ae7.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.DetectionPreset'>, max_side=1280, channel_order='bgr'), meta={'task': 'detection', 'backbone': 'mobilenet_v3_large_05', 'num_params': 603418, 'source': 'torchocr: PPOCR_V3_EN fine-tuned 300 epochs on the 1000 ICDAR-2015 training images with references/detection/train.py', 'license': 'Apache-2.0 (base weights); fine-tuned on ICDAR 2015, released for research use', 'languages': ['en'], 'postprocess': {'threshold': 0.3, 'box_thresh': 0.45, 'unclip_ratio': 1.5}, '_metrics': {'ICDAR2015-test': {'precision': 0.7845, 'recall': 0.689, 'hmean': 0.7337}}, '_docs': "Word-level detector for incidental scene text (street-level photos, Latin script). box_thresh=0.45 maximizes hmean on the *training* split (references/detection/calibrate.py) and was applied once to the test split; with PaddleOCR's box_thresh=0.6 this checkpoint scores 0.688. Weights are the last epoch -- no checkpoint was selected on the test set. Expect lower recall on dense documents and on non-Latin scripts. ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; transforms() preset, DBPostProcessor(**meta['postprocess']). Reproduce with references/detection/evaluate.py --weights <this enum>."})#
DEFAULT = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/dbnet_mobilenet_v3_large_05_ppocr_v3_ch-fc000d1e.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.DetectionPreset'>, max_side=960, channel_order='bgr'), meta={'task': 'detection', 'backbone': 'mobilenet_v3_large_05', 'num_params': 603418, 'source': 'PaddleOCR ch_PP-OCRv3_det_distill_train (Student), via scripts/convert_paddle_dbnet_v3.py', 'license': 'Apache-2.0', 'languages': ['ch', 'en'], 'postprocess': {'threshold': 0.3, 'box_thresh': 0.6, 'unclip_ratio': 1.5}, '_metrics': {'ICDAR2015-test': {'precision': 0.5641, 'recall': 0.337, 'hmean': 0.4219}}, '_docs': "Trained by PaddleOCR on line-level annotations of mostly Chinese/English document and scene text, then converted to PyTorch. ICDAR-2015 scores *word* boxes in low-resolution street scenes, so adjacent words merged into one line count as misses; use this number to compare checkpoints, not as the accuracy you will see on documents. ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; transforms() preset, DBPostProcessor(**meta['postprocess']). Reproduce with references/detection/evaluate.py --weights <this enum>."})#

Recognition#

class torchocr.models.CRNN(num_classes=None, backbone=None, weights=None, input_channels=3, rnn_hidden=256)[source]#

Bases: Module

CRNN recognizer.

Two backbone variants share a single forward contract:

  • backbone="vgg" (default): the original Shi et al. 2015 VGG-style CNN with one deviation – the final conv7 uses kernel_size=(2, 1) so the output width matches W // 4 exactly. This is what torchocr trains from scratch.

  • backbone="resnet34_vd": the PaddleOCR-compatible recognizer stack – ResNet-34-VD backbone (with recognizer-style (2, 1) strides so width is preserved), 2-layer BiLSTM, single Linear head. Parameter shapes and naming align with PaddleOCR weights so scripts/convert_paddle_crnn.py produces drop-in checkpoints.

Parameters:
  • num_classes (int | None) – Number of output classes including the CTC blank. Required without weights – the caller must commit to a charset. With weights it defaults to weights.meta["num_classes"] and must equal it if given.

  • backbone (Literal['vgg', 'resnet34_vd'] | None) – "vgg" or "resnet34_vd". Default None: taken from weights when it is an enum member, else "vgg".

  • weights (WeightsEnum | str | None) – Pretrained weights – a CRNN_ResNet34_VD_Weights member or a member name such as "DEFAULT". If the download fails a UserWarning is emitted and the model keeps its random initialization. Default None.

  • input_channels (int) – Channels in the input crops. Default 3.

  • rnn_hidden (int) – Hidden size of each BiLSTM direction. Default 256.

Forward:

Inputs are crops of shape (B, input_channels, 32, W) with W >= 16. Output is (T, B, num_classes) logits where T = W // 4. log_softmax is not applied – pass logits directly to nn.CTCLoss(zero_infinity=True) after a log_softmax(dim=-1) at training time.

Graph capture:

FX-traceable and torch.export-able with a dynamic batch size. The crop width must be static under torch.export (it specializes nn.LSTM’s sequence length) – which matches inference, where torchocr.ops.crop_quads() pads every crop to max_width. torch.compile works but graph-breaks at the LSTM (a Dynamo limitation), so fullgraph=True is not supported.

forward(images)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Parameters:

images (Tensor)

Return type:

Tensor

torchocr.models.crnn_resnet34_vd(*, weights=None, num_classes=None, **kwargs)[source]#

PaddleOCR-compatible CRNN (ResNet-34-VD + BiLSTM + CTC); see CRNN_ResNet34_VD_Weights.

Parameters:
Return type:

CRNN

torchocr.models.crnn_vgg(*, num_classes, **kwargs)[source]#

CRNN with the original VGG-style CNN (no published weights).

Parameters:
Return type:

CRNN

class torchocr.models.CRNN_ResNet34_VD_Weights(*values)[source]#

Bases: WeightsEnum

PPOCR_SERVER_V2 = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/crnn_resnet34_vd_ppocr_server_v2-803ba4c9.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.RecognitionPreset'>, height=32, max_width=320, channel_order='bgr'), meta={'task': 'recognition', 'backbone': 'resnet34_vd', 'num_params': 27860673, 'num_classes': 6625, 'charset': 'ppocr_keys_v1', 'source': 'PaddleOCR ch_ppocr_server_v2.0_rec_train, via scripts/convert_paddle_crnn.py', 'license': 'Apache-2.0', 'languages': ['ch', 'en'], '_metrics': {'ICDAR2015-test-gt-quads': {'word_accuracy': 0.6649, 'char_error_rate': 0.1333}}, '_docs': 'Chinese + English line recognizer (CTC, 6623 characters + blank) trained by PaddleOCR mostly on document and street-sign text lines. Benchmark: the 2077 alphanumeric care words of ICDAR-2015 test, cropped from the full images with torchocr.ops.crop_quads on their ground-truth quads, scored case-insensitively over letters and digits (not the official Task 4.3 crops). Axis-aligned crops of the same words score 0.5787 -- rotated scene text needs quad rectification. Reproduce with references/recognition/evaluate.py.'})#
ICDAR2015 = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/crnn_resnet34_vd_ic15-da0782b5.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.RecognitionPreset'>, height=32, max_width=320, channel_order='bgr'), meta={'task': 'recognition', 'backbone': 'resnet34_vd', 'num_params': 27860673, 'num_classes': 6625, 'charset': 'ppocr_keys_v1', 'source': 'torchocr: PPOCR_SERVER_V2 fine-tuned 30 epochs on the 4467 legible ICDAR-2015 training words (crop_quads on jittered ground-truth quads) with references/recognition/train.py', 'license': 'Apache-2.0 (base weights); fine-tuned on ICDAR 2015, released for research use', 'languages': ['en'], '_metrics': {'ICDAR2015-test-gt-quads': {'word_accuracy': 0.7376, 'char_error_rate': 0.101}}, '_docs': "Scene-text word recognizer (CTC). Same benchmark protocol as PPOCR_SERVER_V2: the 2077 alphanumeric care words of ICDAR-2015 test cropped with crop_quads on their ground-truth quads, case-insensitive. Last epoch, no checkpoint selected on the test set. The charset is still PaddleOCR's Chinese + Latin one, but fine-tuning used Latin scene text only, so Chinese accuracy is not guaranteed. Reproduce with references/recognition/evaluate.py."})#
ICDAR2015_TOTALTEXT_MLT19 = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/crnn_resnet34_vd_scene-38393899.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.RecognitionPreset'>, height=32, max_width=320, channel_order='bgr'), meta={'task': 'recognition', 'backbone': 'resnet34_vd', 'num_params': 27860673, 'num_classes': 6625, 'charset': 'ppocr_keys_v1', 'decoder': {'type': 'ctc_beam', 'beam_width': 10, 'lm_weight': 0.2, 'lm_url': 'https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/charlm6_scene-883dd7cd.json'}, 'source': 'torchocr: PPOCR_SERVER_V2 fine-tuned 10 epochs (bf16) on 66k Latin scene words: ICDAR-2015 train (x2), Total-Text train and MLT-2019 Latin crops, with references/recognition/train.py', 'license': 'Apache-2.0 (base weights); fine-tuned on ICDAR 2015, Total-Text and MLT 2019, released for research use', 'languages': ['en', 'fr', 'de', 'it', 'es', 'pt'], '_metrics': {'ICDAR2015-test-gt-quads': {'word_accuracy': 0.7906, 'char_error_rate': 0.0812}, 'TotalText-test-gt-quads': {'word_accuracy': 0.8018, 'char_error_rate': 0.0951}}, '_docs': 'Latin scene-text word recognizer. Decoded with CTC beam search (width 10) and a case-insensitive 6-gram character language model built from the training transcriptions only; beam width and LM weight were chosen on Total-Text *training* words. Same benchmark protocol as PPOCR_SERVER_V2 (ground-truth quads cropped with crop_quads, case-insensitive). Last epoch, no checkpoint selected on any test set. Chinese is no longer supported in practice. Reproduce with references/recognition/evaluate.py.'})#
MJSYNTH_ICDAR2015_TOTALTEXT_MLT19 = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/crnn_resnet34_vd_synth-513c0334.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.RecognitionPreset'>, height=32, max_width=320, channel_order='bgr'), meta={'task': 'recognition', 'backbone': 'resnet34_vd', 'num_params': 27860673, 'num_classes': 6625, 'charset': 'ppocr_keys_v1', 'decoder': {'type': 'ctc_beam', 'beam_width': 10, 'lm_weight': 0.2, 'lm_url': 'https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/charlm6_scene-883dd7cd.json'}, 'source': 'torchocr: ICDAR2015_TOTALTEXT_MLT19 fine-tuned 6 more epochs (bf16), each drawing 370k words at random: the 66k real Latin scene words (ICDAR-2015 train x2, Total-Text train, MLT-2019 Latin crops) once on average, plus 300k of the 7.2M MJSynth synthetic words, with references/recognition/train.py', 'license': 'Apache-2.0 (base weights); fine-tuned on ICDAR 2015, Total-Text, MLT 2019 and MJSynth, released for research use', 'languages': ['en', 'fr', 'de', 'it', 'es', 'pt'], '_metrics': {'ICDAR2015-test-gt-quads': {'word_accuracy': 0.7987, 'char_error_rate': 0.0789}, 'TotalText-test-gt-quads': {'word_accuracy': 0.819, 'char_error_rate': 0.0924}}, '_docs': 'Latin scene-text word recognizer, ICDAR2015_TOTALTEXT_MLT19 further trained with MJSynth synthetic words mixed into every epoch. Decoded like its parent, with the same CTC beam search (width 10) and 6-gram character language model (built from real training transcriptions only; beam width and LM weight were chosen on Total-Text *training* words). Same benchmark protocol as PPOCR_SERVER_V2 (ground-truth quads cropped with crop_quads, case-insensitive). Last epoch, no checkpoint selected on any test set. Chinese is no longer supported in practice. Reproduce with references/recognition/evaluate.py.'})#
DEFAULT = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/crnn_resnet34_vd_ppocr_server_v2-803ba4c9.pth', transforms=functools.partial(<class 'torchocr.transforms._presets.RecognitionPreset'>, height=32, max_width=320, channel_order='bgr'), meta={'task': 'recognition', 'backbone': 'resnet34_vd', 'num_params': 27860673, 'num_classes': 6625, 'charset': 'ppocr_keys_v1', 'source': 'PaddleOCR ch_ppocr_server_v2.0_rec_train, via scripts/convert_paddle_crnn.py', 'license': 'Apache-2.0', 'languages': ['ch', 'en'], '_metrics': {'ICDAR2015-test-gt-quads': {'word_accuracy': 0.6649, 'char_error_rate': 0.1333}}, '_docs': 'Chinese + English line recognizer (CTC, 6623 characters + blank) trained by PaddleOCR mostly on document and street-sign text lines. Benchmark: the 2077 alphanumeric care words of ICDAR-2015 test, cropped from the full images with torchocr.ops.crop_quads on their ground-truth quads, scored case-insensitively over letters and digits (not the official Task 4.3 crops). Axis-aligned crops of the same words score 0.5787 -- rotated scene text needs quad rectification. Reproduce with references/recognition/evaluate.py.'})#

Page orientation#

class torchocr.models.PPLCNet(num_classes=None, dropout=0.2, weights=None, progress=True)[source]#

Bases: Module

PP-LCNet x1.0 image classifier (Cui et al., 2021), as used by PaddleOCR for page orientation.

A 1.7M-parameter CPU-oriented network: depthwise-separable blocks with HardSwish, squeeze-excitation only in the last two blocks, then global pooling and a 1280-wide 1x1 convolution before the classifier. Submodule names mirror PaddleClas so checkpoints port with a short remap (scripts/convert_paddle_pplcnet.py).

Parameters:
  • num_classes (int | None) – Number of output logits. Default: from weights, else 4.

  • dropout (float) – Dropout probability before the classifier.

  • weights (PPLCNet_x1_0_Weights | str | None) – Pretrained PPLCNet_x1_0_Weights (member or name).

  • progress (bool) – Show a download progress bar.

Forward:

(B, 3, H, W) normalized images -> (B, num_classes) logits.

forward(images)[source]#

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

Parameters:

images (Tensor)

Return type:

Tensor

torchocr.models.pp_lcnet_x1_0(*, weights=None, **kwargs)[source]#

PP-LCNet x1.0 classifier; see PPLCNet_x1_0_Weights.

Parameters:
Return type:

PPLCNet

class torchocr.models.PPLCNet_x1_0_Weights(*values)[source]#

Bases: WeightsEnum

PPOCR_DOC_ORIENTATION = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/pplcnet_x1_0_doc_ori-ba9045e4.pth', transforms=<class 'torchocr.transforms._presets.ClassificationPreset'>, meta={'task': 'page-orientation', 'backbone': 'pp_lcnet_x1_0', 'num_params': 1676644, 'categories': ['0', '90', '180', '270'], 'source': 'PaddleOCR PP-LCNet_x1_0_doc_ori, via scripts/convert_paddle_pplcnet.py', 'license': 'Apache-2.0', 'min_confidence': 0.7, '_metrics': {'DocLayNet-test': {'accuracy': 0.9848, 'upright_wrongly_turned': 0.0024, 'turned_set_upright': 0.9753}}, '_docs': "Trained by PaddleOCR on document pages (mostly Chinese and English), converted to PyTorch. Scored on the 4999 DocLayNet test pages (financial reports, manuals, laws, patents, scientific articles, tenders), each fed upright and turned 90, 180 and 270 degrees: accuracy is the argmax; the other two numbers are PageOrientation's decisions at min_confidence=0.7, chosen on DocLayNet validation and applied once to test. Weakest on manuals (0.973) and laws (0.979), where most errors send upright pages to 180 degrees. Not meant for scene photos: on a street photo it is unsure (p < 0.8) and can still turn it. Reproduce with references/orientation/evaluate.py."})#
DEFAULT = Weights(url='https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main/pplcnet_x1_0_doc_ori-ba9045e4.pth', transforms=<class 'torchocr.transforms._presets.ClassificationPreset'>, meta={'task': 'page-orientation', 'backbone': 'pp_lcnet_x1_0', 'num_params': 1676644, 'categories': ['0', '90', '180', '270'], 'source': 'PaddleOCR PP-LCNet_x1_0_doc_ori, via scripts/convert_paddle_pplcnet.py', 'license': 'Apache-2.0', 'min_confidence': 0.7, '_metrics': {'DocLayNet-test': {'accuracy': 0.9848, 'upright_wrongly_turned': 0.0024, 'turned_set_upright': 0.9753}}, '_docs': "Trained by PaddleOCR on document pages (mostly Chinese and English), converted to PyTorch. Scored on the 4999 DocLayNet test pages (financial reports, manuals, laws, patents, scientific articles, tenders), each fed upright and turned 90, 180 and 270 degrees: accuracy is the argmax; the other two numbers are PageOrientation's decisions at min_confidence=0.7, chosen on DocLayNet validation and applied once to test. Weakest on manuals (0.973) and laws (0.979), where most errors send upright pages to 180 degrees. Not meant for scene photos: on a street photo it is unsure (p < 0.8) and can still turn it. Reproduce with references/orientation/evaluate.py."})#

Weights API#

class torchocr.models.Weights(url, transforms, meta)[source]#

Bases: object

One published checkpoint.

Parameters:
url#

Download URL; the file name carries a SHA-256 prefix.

Type:

str

transforms#

Zero-argument factory for the inference preset the checkpoint expects (call it: weights.transforms()).

Type:

collections.abc.Callable[[…], torch.nn.modules.module.Module]

meta#

Free-form metadata. Keys shared by every torchocr checkpoint: task, backbone, num_params, source, license, _metrics (benchmark -> scores) and _docs.

Type:

dict[str, Any]

class torchocr.models.WeightsEnum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: Enum

Base class for the per-architecture weights enums.

A DEFAULT member aliases the recommended checkpoint.

classmethod verify(obj)[source]#

Resolve obj (member, member name, or "Cls.NAME") to a member of cls.

Parameters:

obj (WeightsEnum | str | None)

Return type:

WeightsEnum | None

torchocr.models.list_models()[source]#

Sorted names of every registered model builder.

Return type:

list[str]

torchocr.models.get_model(name, **config)[source]#

Build a registered model, e.g. get_model("dbnet_resnet18_vd", weights="DEFAULT").

Parameters:
Return type:

Module

torchocr.models.get_model_weights(name)[source]#

The weights enum of a registered model, or None if it has no published weights.

Parameters:

name (str)

Return type:

type[WeightsEnum] | None

torchocr.models.get_weight(name)[source]#

Resolve a fully-qualified "Cls.NAME" string, e.g. "DBNet_ResNet18_VD_Weights.DEFAULT".

Parameters:

name (str)

Return type:

WeightsEnum