Overview
Recognizers consumed by media toolkit components.
This module provides recognizers that transcribe content, such as cropped text lines, found in images and decoded video frames.
Exported Classes
BaseTextRecognizer-- Abstract base for text-line recognizers.PPOCRTextRecognizer-- Lazy PP-OCRv6 ONNX text recognizer.
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 |
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. |