holocron.utils¶
holocron.utils provides some utilities for general usage.
Synthetic text rendering¶
Load fonts once, then render tight grayscale masks for characters or complete sequences. Font discovery and corpus preparation happen before the sampling loop; resizing and stochastic effects remain regular TorchVision transforms.
The library performs no network access. To prepare the pinned starter manifest from the repository, run:
Use find_fonts(text) instead when only installed system fonts are needed.
from itertools import cycle
from pathlib import Path
import matplotlib.pyplot as plt
from PIL import ImageFont
from torchvision.transforms import v2
from holocron.utils import render_text
font_paths = tuple(str(path) for path in sorted(Path("/tmp/holocron-fonts").glob("*.ttf")))[:3]
fonts = [ImageFont.truetype(path, 48) for path in font_paths]
augment = v2.Compose([
v2.Pad(4, fill=0),
v2.Resize(48),
v2.RandomAffine(degrees=8, translate=(0.05, 0.05), scale=(0.9, 1.1), fill=0),
v2.GaussianBlur(kernel_size=3, sigma=(0.1, 1.0)),
v2.RandomInvert(p=0.2),
])
fig, axes = plt.subplots(2, 3, constrained_layout=True)
for ax, text, font in zip(axes.flat, ["A", "OCR-42"] * 3, cycle(fonts)):
ax.imshow(augment(render_text(text, font)), cmap="gray", vmin=0, vmax=255)
ax.axis("off")
plt.show()
The downloadable fonts come from the Google Fonts repository under the SIL Open Font License.
render_text
¶
render_text(text: str, font: FreeTypeFont, *, padding: int = 0, background_color: int = 0, text_color: int = 255) -> Image
Render text as a tight grayscale image.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
non-empty Unicode text to render
TYPE:
|
font
|
preloaded font used for rasterization
TYPE:
|
padding
|
number of background pixels added on every side
TYPE:
|
background_color
|
grayscale background value
TYPE:
|
text_color
|
grayscale text value
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Image
|
rendered grayscale image |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
if |
ValueError
|
if the arguments cannot produce a visible image |
Source code in holocron/utils/fonts.py
find_fonts
cached
¶
Find loadable system fonts that cover the requested text.
Matplotlib-bundled fonts are included so discovery does not depend on the host having user-installed fonts.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
optional text whose non-whitespace code points must be supported
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, ...]
|
sorted, deduplicated font paths |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
if |
Source code in holocron/utils/fonts.py
CTC decoding¶
Encode target characters and decode line-model predictions using an explicit alphabet. See the recognition models for the image and sequence-length contract.
recognition
¶
Alphabet encoding and lexicon-free CTC transcript decoding.
CTCCodec
¶
CTCCodec(alphabet: str)
Map an ordered alphabet to CTC labels, reserving index zero for blank.
| PARAMETER | DESCRIPTION |
|---|---|
alphabet
|
unique printable Unicode characters; ordinary space is allowed
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the alphabet is empty, duplicated, or contains unsupported whitespace |
Source code in holocron/utils/recognition.py
encode
¶
Encode text without inserting CTC blanks.
| PARAMETER | DESCRIPTION |
|---|---|
text
|
characters drawn from this codec's alphabet
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
one-dimensional CPU int64 tensor of target labels |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if a character is absent from the alphabet |
Source code in holocron/utils/recognition.py
decode
¶
Collapse a greedy CTC alignment, preserving repeats separated by blanks.
| PARAMETER | DESCRIPTION |
|---|---|
indices
|
consecutive frame labels, truncated to the true sequence length |
| RETURNS | DESCRIPTION |
|---|---|
str
|
decoded transcript, including predicted spaces and punctuation |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if an index is outside the blank/alphabet label range |
Source code in holocron/utils/recognition.py
prefix_beam_decode
¶
prefix_beam_decode(log_probabilities: ndarray, codec: CTCCodec, beam_width: int = 5, token_topk: int = 8) -> str
Approximate the most probable transcript, respecting blanks and repeated letters.
| PARAMETER | DESCRIPTION |
|---|---|
log_probabilities
|
frame log probabilities of shape (T, alphabet size + 1)
TYPE:
|
codec
|
alphabet whose blank index is zero
TYPE:
|
beam_width
|
number of transcript prefixes retained per frame
TYPE:
|
token_topk
|
maximum nonblank frame labels considered; blank is always included
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
the best prefix after summing blank/nonblank alignment probabilities |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if beam width, token count, or probability shape is invalid |
Source code in holocron/utils/recognition.py
Miscellaneous¶
parallel
¶
parallel(func: Callable[[Inp], Out], arr: Sequence[Inp], num_threads: int | None = None, progress: bool = False, **kwargs: Any) -> Iterable[Out]
Performs parallel tasks by leveraging multi-threading.
| PARAMETER | DESCRIPTION |
|---|---|
func
|
function to be executed on multiple workers
TYPE:
|
arr
|
function argument's values
TYPE:
|
num_threads
|
number of workers to be used for multiprocessing
TYPE:
|
progress
|
whether the progress bar should be displayed
TYPE:
|
kwargs
|
keyword arguments of [
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Iterable[Out]
|
list of function's results |
Source code in holocron/utils/misc.py
find_image_size
¶
Computes the best image size target for a given set of images
| PARAMETER | DESCRIPTION |
|---|---|
dataset
|
an iterator yielding a |
**kwargs
|
keyword args of
TYPE:
|