Overview
Text recognizer implementations for media analysis.
Text recognizers transcribe upright, single-line text crops, such as the crops text detectors return, into text.
Exported Classes
BaseTextRecognizer-- Abstract base for text recognizers.PPOCRTextRecognizer-- Backend-selectable PP-OCRv6 text recognizer family.OnnxPPOCRTextRecognizer-- Lazy ONNX Runtime PP-OCRv6 text recognizer, the family default.
BaseTextRecognizer()
Bases: MediaToolkit[Attachment, Attachment], ABC
Define the text recognizer role for media toolkit components.
Recognizers transcribe single-line, upright text crops, such as the crops a text detector returns. They expose two public entry points:
processaccepts a text-crop image attachment and returns atext/plainattachment holding its UTF-8 text. The output keeps the input's metadata, such as a text detector'sindexandbbox, and adds the recognitionconfidence;process_batchrecognizes several crops in onerecognizecall.recognizeruns on decoded BGRuint8crops and returns one(text, confidence)pair per crop. Consumers that already hold decoded crops, such as OCR converters, call it directly.
Subclasses implement only recognize. Construction must be synchronous and free of I/O so
recognizers can be built from declarative specs. Any slow preparation, such as downloading
model weights, belongs in
ensure_ready,
which consumers await before calling recognize. Recognizers holding native resources
release them in
close.
Usage Example
Detect then recognize (process):
from gllm_inference.schema import Attachment
from gllm_multimodal.media_toolkit.media_toolkit import MediaToolkit
detector = MediaToolkit.build("PPOCRTextDetector")
recognizer = MediaToolkit.build("PPOCRTextRecognizer")
crops = await detector.process(Attachment.from_path("/path/to/slide.png"))
lines = await recognizer.process_batch(crops)
for line in lines:
print(line.data.decode(), line.metadata["bbox"], line.metadata["confidence"])
Decoded crops (recognize):
import numpy as np
from PIL import Image
from gllm_multimodal.media_toolkit.media_toolkit import MediaToolkit
recognizer = MediaToolkit.build("PPOCRTextRecognizer")
await recognizer.ensure_ready()
crop = np.asarray(Image.open("/path/to/line.png").convert("RGB"))[:, :, ::-1] # RGB -> BGR
[(text, confidence)] = recognizer.recognize([crop])
close()
Release resources held by the recognizer.
The default implementation is a no-op for recognizers that hold no native resources. Implementations must be idempotent.
ensure_ready()
async
Prepare the recognizer for inference.
The default implementation is a no-op for recognizers that need no preparation. Implementations must be idempotent.
recognize(crops)
abstractmethod
Recognize the text in upright, single-line BGR crops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crops
|
list[ndarray]
|
Three-channel BGR |
required |
Returns:
| Type | Description |
|---|---|
list[TextRecognition]
|
list[TextRecognition]: One |
OnnxPPOCRTextRecognizer(source=DEFAULT_MODEL_SOURCE, dictionary=None, cache_dir=None, batch_size=DEFAULT_BATCH_SIZE, num_threads=None, providers=None)
Bases: PPOCRTextRecognizer
Run a pinned or locally supplied PP-OCRv6 recognition model with ONNX Runtime.
Construction only validates options. Built-in weights and the character dictionary are
downloaded by
ensure_ready,
and the ONNX Runtime session is created lazily, under a lock, on the first
recognize
call. Both are released by
close.
Requires the ocr, video-ffmpeg, or video-gst extra, which installs ONNX Runtime.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
str | Path
|
Built-in recognizer name ( |
cache_dir |
str | Path | None
|
Persistent weight cache root for built-in models. |
batch_size |
int
|
Maximum number of crops recognized in one ONNX Runtime call. |
num_threads |
int | None
|
Optional CPU intra-op thread count. |
providers |
tuple[ExecutionProvider, ...]
|
ONNX Runtime execution providers in priority order. |
Validate the model source and options without I/O.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
Exact built-in recognizer name, one of
|
DEFAULT_MODEL_SOURCE
|
dictionary
|
str | Path | Sequence[str] | None
|
CTC dictionary
characters (excluding the blank class and trailing space), a path to a
UTF-8 text file with one character per line, or |
None
|
cache_dir
|
str | Path | None
|
Persistent cache root for built-in
weights. When |
None
|
batch_size
|
int
|
Maximum number of crops recognized in one ONNX Runtime call. Must be at least 1. Defaults to 8. |
DEFAULT_BATCH_SIZE
|
num_threads
|
int | None
|
ONNX Runtime CPU intra-op thread count.
|
None
|
providers
|
Sequence[ExecutionProvider] | None
|
ONNX Runtime execution
providers in priority order, each a provider name such as
|
None
|
Raises:
| Type | Description |
|---|---|
ComponentConfigError
|
If the source is unsupported, no dictionary is available for a
local source, |
ComponentModelError
|
If a local path source is not a readable file. |
num_threads
property
Return the ONNX Runtime CPU intra-op thread count.
Returns:
| Type | Description |
|---|---|
int | None
|
int | None: Thread count, or |
providers
property
Return the ONNX Runtime execution providers.
Returns:
| Type | Description |
|---|---|
tuple[ExecutionProvider, ...]
|
tuple[ExecutionProvider, ...]: Execution providers in priority order. |
close()
Idempotently release the ONNX session and memory-backed model bytes.
This method is safe to call multiple times and from multiple threads.
ensure_ready()
async
Resolve built-in weights and dictionary once so recognize can run.
Local path sources need no weight download, but still need a dictionary given at construction. Concurrent callers share one download of each artifact. The steps are: 1. Check that the recognizer is open, and return early when nothing is left to resolve. 2. Load the built-in character dictionary from its inference config, once. 3. Resolve the built-in weights through the shared ONNX session, once.
Raises:
| Type | Description |
|---|---|
MediaOperationFailedError
|
If the recognizer has been closed. |
ComponentModelError
|
If downloading, verifying, or caching a built-in artifact fails. |
ValueError
|
If the downloaded configuration has no valid character dictionary. |
CancelledError
|
If the caller cancels resolution. |
PPOCRTextRecognizer(batch_size=DEFAULT_BATCH_SIZE, dictionary=None)
Bases: FamilyBuildMixin, BackendSelectableProcessor[Attachment, Attachment], BaseTextRecognizer, ABC
Family base for PP-OCRv6 text recognizers with pluggable model runtimes.
The family is built by name, so backend selects the runtime and the remaining keyword
arguments go to that backend's constructor. Calling the family base directly, such as
PPOCRTextRecognizer("ppocrv6_tiny_rec"), builds the same default backend as
PPOCRTextRecognizer.build. The default backend is ONNX Runtime,
OnnxPPOCRTextRecognizer.
Construction only validates options and loads a caller-supplied dictionary. Backends prepare
their model in
ensure_ready
and release it in
close.
Preprocessing follows PaddleOCR's recognition pipeline:
1. Crops stay in BGR order and are resized to height 48, with the width rounded up from the
crop's aspect ratio.
2. Pixels are scaled to [-1, 1].
3. Each batch is right-padded with zeros to its widest crop, and is never narrower than 320 pixels.
Attributes:
| Name | Type | Description |
|---|---|---|
batch_size |
int
|
Maximum number of crops recognized in one model call. |
Validate the batch size and load the caller-supplied dictionary without I/O.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Maximum number of crops recognized in one model call. Must be at least 1. Defaults to 8. |
DEFAULT_BATCH_SIZE
|
dictionary
|
str | Path | Sequence[str] | None
|
CTC dictionary characters
(excluding the blank class and trailing space), or a path to a UTF-8 text file
with one character per line. |
None
|
Raises:
| Type | Description |
|---|---|
ComponentConfigError
|
If |
close()
abstractmethod
Idempotently release the backend model and its native resources.
ensure_ready()
abstractmethod
async
Prepare the backend model and dictionary once so recognize can run.
Implementations must be idempotent and safe to await concurrently.
Raises:
| Type | Description |
|---|---|
MediaOperationFailedError
|
If the recognizer has been closed. |
ComponentModelError
|
If the built-in weights or dictionary cannot be downloaded, cached, or verified. |
recognize(crops)
Recognize upright BGR uint8 crops and greedily decode each one's CTC output.
Crops are batched in order of aspect ratio, so crops of similar resized width share a batch and limit each other's padding; results are returned in input order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
crops
|
list[ndarray]
|
Non-empty three-channel BGR |
required |
Returns:
| Type | Description |
|---|---|
list[TextRecognition]
|
list[TextRecognition]: One |
Raises:
| Type | Description |
|---|---|
MediaOperationFailedError
|
If the recognizer is closed. |
MediaOperationConfigError
|
If |
MediaInputInvalidError
|
If |
MediaResultOperationError
|
If the model output does not match the batch size. |
ComponentConfigError
|
If the model output does not match the dictionary. |