folio-sbb-print-ocr / reader.py
foliokestrel's picture
Release a CPU OCR reader for historical print with a diplomatic transcription, searchable text, PAGE XML input, and a reproducible twelve-work Berlin evaluation.
2e35f95 verified
Raw History Blame Contribute Delete
2.54 kB
"""Image preparation and a small CTC recognizer for a single printed line."""
import numpy as np
from PIL import Image, ImageOps
import torch
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
HEIGHT = 40
MARGIN = 8
STRIDE = 4
def line_width(width, height):
return max(4, min(4096, round(width*HEIGHT/height)))
def pixels(image):
if 'A' in image.getbands() or 'transparency' in image.info:
rgba=image.convert('RGBA')
image=Image.alpha_composite(Image.new('RGBA',image.size,'white'),rgba)
gray=ImageOps.autocontrast(image.convert('L'),cutoff=0.5)
width=line_width(*gray.size)
gray=gray.resize((width,HEIGHT),Image.Resampling.BILINEAR)
x=np.asarray(gray,dtype=np.float32)
ink=(255-x)/255
return torch.from_numpy(np.pad(ink,((0,0),(MARGIN,MARGIN))))[None]
def greedy(logits, lengths, alphabet):
labels=logits.argmax(-1).detach().cpu().tolist()
text=[]
for row,n in zip(labels,lengths):
last=None
chars=[]
for label in row[:int(n)]:
if label and label!=last:
chars.append(alphabet[label-1])
last=label
text.append(''.join(chars))
return text
class LineReader(nn.Module):
def __init__(self, classes):
super().__init__()
blocks=[]
channels=1
for features,pool in [(32,(2,2)),(64,(2,2)),(96,(2,1)),(128,(2,1))]:
blocks.extend([nn.Conv2d(channels,features,3,padding=1,bias=False),
nn.BatchNorm2d(features),nn.ReLU(inplace=True),nn.MaxPool2d(pool)])
channels=features
# Height 40 -> 20 -> 10 -> 5 -> 2, then a learned full-height projection.
blocks.extend([nn.Conv2d(channels,160,(2,1)),nn.ReLU(inplace=True)])
self.features=nn.Sequential(*blocks)
self.sequence=nn.LSTM(160,160,num_layers=2,dropout=.15,batch_first=True,bidirectional=True)
self.classifier=nn.Linear(320,classes)
with torch.no_grad():
self.classifier.bias[0]=-1
def forward(self, image, steps):
# Give the last valid convolutional features the same blank context when
# a line is evaluated alone or alongside a wider neighbor.
x=self.features(nn.functional.pad(image,(0,32))).squeeze(2).transpose(1,2)
packed=pack_padded_sequence(x,steps,batch_first=True,enforce_sorted=False)
encoded,_=self.sequence(packed)
seq,_=pad_packed_sequence(encoded,batch_first=True)
return self.classifier(seq)