Skip to content

Base Text Recognizer

Abstract base for text recognizers in the media toolkit.

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:

  • process accepts a text-crop image attachment and returns a text/plain attachment holding its UTF-8 text. The output keeps the input's metadata, such as a text detector's index and bbox, and adds the recognition confidence; process_batch recognizes several crops in one recognize call.
  • recognize runs on decoded BGR uint8 crops 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 uint8 crops of any size.

required

Returns:

Type Description
list[TextRecognition]

list[TextRecognition]: One (text, confidence) pair per crop, in input order. ("", 0.0) when nothing is recognized in a crop.