AI Wiki中文/EN

OCR: reading the characters and preserving the document

光学字符识别

Build a complete tiny CNN/BiRNN with CTC gradients, test repeated characters and beam decoding, and distinguish text recognition from document parsing.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Reading the letters is not the same as reading the page

Imagine an invoice with two columns. Every word is recognized correctly, but the amount in the right column is attached to the wrong item on the left. Character accuracy is perfect; the extracted document is still wrong.

Optical character recognition, or OCR, converts visible text into machine-readable symbols. A practical document pipeline may also locate text regions, estimate their orientation, recover reading order, group table cells and extract fields. These stages have different targets and failure modes. A line recognizer does not automatically become a page parser. PaddleOCR’s 2025 report explicitly separates text recognition, structural parsing and key-information extraction into different solutions. Task separation

Before rasterizing a PDF, check whether it already contains usable text. Extracting and verifying its text layer can avoid an unnecessary recognition step, although the layer’s order and encoding still need checking. For scanned pages or photographs, OCR must work from pixels. Preserve the original page and coordinates so a reader can trace an extracted value back to its evidence.

This article builds a small image-to-sequence recognizer. It reads synthetic A/B glyphs, includes the entire forward and backward calculation, and makes its remaining errors visible. Text detection and full-page structure are explained separately; they are not hidden inside the example.

Computed repeat collapse, best-path versus label probability, and synthetic AA transcription that remains incorrect after training.
Original computed diagram: blank preserves repeats, label probabilities sum paths, and a lower loss can still accompany a wrong transcription. Probability and training fixtures are separate.

Locate text, represent a line, then decode a sequence

A detector answers where, not what

A detector may return rectangles, quadrilaterals or polygons around text. A recognizer consumes a crop and predicts symbols. Rotated or curved text complicates the crop; ordering several crops requires yet another rule or model.

DBNet predicts a text probability map P and a learned threshold map T. Its differentiable approximation to binarization uses a positive sharpness k:

B^ij=11+exp⁡[−k(Pij−Tij)].\widehat B_{ij}=\frac{1}{1+\exp[-k(P_{ij}-T_{ij})]}.

The local derivative is:

∂B^∂P=kB^(1−B^),∂B^∂T=−kB^(1−B^).\frac{\partial\widehat B}{\partial P}=k\widehat B(1-\widehat B),\qquad \frac{\partial\widehat B}{\partial T}=-k\widehat B(1-\widehat B).

At P=T the output is 0.5; with the paper’s k=50 the derivative is 12.5. Training can therefore pass a signal through a soft threshold. The paper allows inference from the probability map without retaining the learned-threshold branch. DB method

The fixed PaddleOCR postprocessor we inspected thresholds its probability map with a strict greater-than comparison and then forms polygons or quadrilaterals. It also includes an expansion step based on area and perimeter. This is not the same computation as the differentiable sigmoid. Our program implements only the latter local operator, not a trained text detector or polygon pipeline. Fixed postprocessing

Turn image width into sequence length

CRNN combines convolutional features, a bidirectional recurrent network and transcription. Its feature map is read by columns so a variable-width image becomes a variable-length sequence. The original model uses bidirectional LSTMs; its training target is the text string, without individual character boxes. This does not remove the need to obtain the text crop in a larger system. Original CRNN

Our smaller model uses one convolution, averages over feature-map height, runs two tanh RNNs in opposite directions, concatenates their states and projects to character logits. Averaging replaces the paper’s column concatenation, and tanh units replace its LSTMs. The complete teaching network has 93 parameters. It preserves image width, so a 7×11 synthetic “AA” crop produces 11 output frames, not two presegmented character slots.

The example assumes horizontal left-to-right crops. Vertical, right-to-left and mixed-order text need a declared ordering and normalization policy.

The two recurrent directions can use context from both sides of an ambiguous mark. This is compatible with CTC’s output factorization: frame probabilities are conditioned on the input/network representation. It does not mean the image frames are independent, nor does CTC’s output layer act as an autoregressive language model. CTC assumptions

CTC sums over alignments

Connectionist Temporal Classification adds a blank symbol to the character alphabet. Blank means “emit no label”; a literal space, when supported, needs its own character label. A path π assigns a symbol or blank to every frame. Collapse it by merging consecutive repeats first and removing blanks second. Thus A A blank A becomes AA, while A A A becomes A. The ordering matters. Transcription rule

For target string y and per-frame probabilities pt, CTC adds the probability of every path that collapses to y:

P(y∣x)=∑π:B(π)=y∏t=0T−1pt(πt).P(y\mid x)=\sum_{\pi:\mathcal B(\pi)=y}\prod_{t=0}^{T-1}p_t(\pi_t).

A character can occupy several frames, and the model need not be told exactly where each character begins. This is supervised sequence learning, not learning without text labels. Direct enumeration grows exponentially with frame count. Dynamic programming reuses shared partial alignments. CTC construction

Insert blanks around and between target symbols, yielding an extended sequence z of length S=2U+1. Let αt(s) sum paths that finish in state s at frame t, including that frame’s emission. Define δs as 1 only when s≥2, zs is not blank and zs differs from zs−2. Then:

αt(s)=pt(zs)[αt−1(s)+αt−1(s−1)+δsαt−1(s−2)].\alpha_t(s)=p_t(z_s)\left[\alpha_{t-1}(s)+\alpha_{t-1}(s-1)+\delta_s\alpha_{t-1}(s-2)\right].

Out-of-range states contribute zero. At the first frame only the initial blank and, for a nonempty target, its first character are allowed. Staying repeats a state; advancing by one crosses a blank/label boundary; the guarded two-state jump skips a blank between different labels. It cannot skip the blank between two identical target characters.

For a nonempty target, accept the final character or final blank:

P(y∣x)=αT−1(S−2)+αT−1(S−1),L=−log⁡P(y∣x).P(y\mid x)=\alpha_{T-1}(S-2)+\alpha_{T-1}(S-1),\qquad L=-\log P(y\mid x).

The implementation computes these sums in log space, using log-sum-exp rather than multiplying many small probabilities. Empty targets have only the blank state. An empty input with an empty target has loss zero; an empty input with a nonempty target is impossible.

Our backward variable βt(s) describes the remaining emissions after frame t, excluding the current one. That convention differs from the original paper’s inclusive β; either works if used consistently. The posterior probability of symbol k at frame t and the logit gradient are:

γt(k)=∑s:zs=kαt(s)βt(s)P(y∣x),∂L∂at(k)=pt(k)−γt(k).\gamma_t(k)=\frac{\sum_{s:z_s=k}\alpha_t(s)\beta_t(s)}{P(y\mid x)},\qquad \frac{\partial L}{\partial a_t(k)}=p_t(k)-\gamma_t(k).

Here at(k) is the pre-softmax logit. Subtracting posterior occupancy gives the error signal for the projection, both RNNs and the CNN. The tests independently enumerate tiny paths, compare their occupancy with the dynamic program, and check all model gradients by finite differences.

Repeated labels impose a minimum frame count. If R counts adjacent equal target pairs:

Tmin⁡=U+R.T_{\min}=U+R.

“AA” therefore requires at least three frames, for example A blank A. If downsampling leaves only two, no training update can produce a valid alignment. Our function returns infinite loss and no gradient for an infeasible target, rather than silently treating it as a zero-loss example. Declare the length policy when padding batches; the inspected PaddleOCR wrapper passes the common prediction length to each sample. Loss wrapper

Best path and best string can disagree

Suppose both frames have probabilities blank=0.4, A=0.35 and B=0.25. Greedy decoding selects two blanks and returns an empty string with probability 0.16. The label “A” has three paths: A A, A blank, and blank A. Their probabilities add to 0.4025, so “A” is more probable than the greedy result.

Our prefix beam stores separate probability masses for prefixes ending in blank and nonblank. This distinction preserves a repeated letter separated by blank while merging an uninterrupted repeat. A finite beam prunes possibilities and need not find the global optimum; in the example, beam size one still returns the empty string. No lexicon or language model is used. Decoding distinction

A lexicon or language model can help resolve ambiguity, but can also turn an unfamiliar name or identifier into a familiar wrong word. Evaluate the raw recognizer and the constrained decoder separately. CRNN explicitly distinguishes lexicon-free and lexicon-based evaluation. Lexicon conditions

Do not confuse a reported “confidence” with the probability of a whole transcription. The fixed PaddleOCR greedy decoder averages retained token maxima, using zero for an empty retained sequence. That statistic is not CTC’s sum over complete alignment paths. Decoder and score calculation

Measure transcription and structure separately

With substitutions S, deletions D, insertions I and N reference characters, micro-averaged character error rate is:

CER⁡=S+D+IN.\operatorname{CER}=\frac{S+D+I}{N}.

Add edit counts across the corpus before dividing. book→bok needs one deletion; A→ABC needs two insertions. Together CER is 3/5=0.6. Averaging their separate rates would give a different result. Insertions can make CER exceed one. An empty reference denominator is undefined even if erroneous output was produced; report the insertion count separately. Edit-distance evaluation is part of the original CTC framing. Sequence error measurement

Word error rate uses word tokens instead of characters. The example defines characters as Python Unicode code points and words as whitespace-separated tokens. Optional NFC normalization is explicit; case, punctuation and spaces are not silently removed. This is not grapheme segmentation, and whitespace tokenization is not a general Chinese word segmenter. Report the policy alongside the score.

Correct strings in the wrong order, a shifted table cell or a missed text region require additional end-to-end checks. Preserve detection recall, crop-level recognition, exact field matches and reading-order/table tests separately. Otherwise an accurate recognizer can hide a broken document pipeline.

Run pixels through a complete CTC update

Use Python 3.12 and NumPy 1.26.4. Save the code as ocr_sequence.py and run python ocr_sequence.py. It generates two original bitmap glyphs, constructs a synthetic line, computes CNN/BiRNN logits, sums CTC paths, backpropagates through every parameter and updates once. No downloaded data or pretrained weights are required.

The DB sigmoid, edit metrics and decoding counterexample are independent fixtures. The code does not claim a complete CRNN reproduction, page detector, document parser or OCR service. Its tanh recurrent units and height averaging are intentional simplifications, not the original paper’s architecture.

"""Original tiny image-to-sequence CNN/BiRNN with complete CTC gradients.

Synthetic A/B glyphs only. Tanh recurrent units replace the original CRNN's
LSTMs. No text detector, layout parser, language model or pretrained OCR engine.
"""
import json
import unicodedata
import numpy as np


def finite(value, rank):
    x=np.asarray(value,float)
    if x.ndim!=rank or not np.isfinite(x).all():raise ValueError('finite array of specified rank required')
    return x


def logsum(values):
    values=np.asarray(values,float)
    if values.size==0:return -np.inf
    maximum=values.max()
    if maximum==-np.inf:return -np.inf
    return float(maximum+np.log(np.exp(values-maximum).sum()))


def log_softmax(logits):
    z=finite(logits,2)
    if z.shape[1]<2:raise ValueError('at least blank and one label required')
    shifted=z-z.max(axis=1,keepdims=True)
    return shifted-np.log(np.exp(shifted).sum(axis=1,keepdims=True))


def validate_blank(blank,classes):
    if type(blank) is not int or not 0<=blank<classes:raise ValueError('valid integer blank index required')


def collapse(path,blank=0):
    """Merge consecutive repeats BEFORE removing blanks."""
    labels=np.asarray(path)
    if labels.ndim!=1 or (len(labels) and (labels.dtype.kind not in 'iu' or np.any(labels<0))):
        raise ValueError('nonnegative integer path required')
    if type(blank) is not int or blank<0:raise ValueError('nonnegative blank index required')
    out=[];previous=None
    for symbol in labels:
        if symbol!=previous and symbol!=blank:out.append(int(symbol))
        previous=symbol
    return tuple(out)


def ctc(logits,target,blank=0):
    """Log-space single-sequence CTC; beta EXCLUDES the current emission.

    Returns loss, logit gradient, diagnostics. Infeasible targets have infinite
    loss and gradient=None, never a silent zero gradient. Empty/empty is valid.
    """
    lp=log_softmax(logits);time,classes=lp.shape;validate_blank(blank,classes)
    target=np.asarray(target)
    if target.ndim!=1 or (len(target) and (target.dtype.kind not in 'iu' or np.any(target<0) or np.any(target>=classes) or np.any(target==blank))):
        raise ValueError('target labels must be valid nonblank integers')
    target=target.astype(int);length=len(target)
    minimum=length+int((target[1:]==target[:-1]).sum())
    if time<minimum:
        return float('inf'),None,{'feasible':False,'minimumFrames':minimum,'logProbability':-float('inf')}
    if time==0:
        return 0.,np.empty_like(lp),{'feasible':True,'minimumFrames':0,'logProbability':0.,'posterior':np.empty_like(lp)}
    states=np.full(2*length+1,blank,int);states[1::2]=target;size=len(states)
    incoming=[]
    for s in range(size):
        prior=[s]
        if s>=1:prior.append(s-1)
        if s>=2 and states[s]!=blank and states[s]!=states[s-2]:prior.append(s-2)
        incoming.append(prior)
    outgoing=[[] for _ in range(size)]
    for s,prior in enumerate(incoming):
        for previous in prior:outgoing[previous].append(s)
    alpha=np.full((time,size),-np.inf);alpha[0,0]=lp[0,blank]
    if length:alpha[0,1]=lp[0,target[0]]
    for t in range(1,time):
        for s in range(size):alpha[t,s]=lp[t,states[s]]+logsum(alpha[t-1,incoming[s]])
    ends=[size-1] if length==0 else [size-2,size-1]
    log_probability=logsum(alpha[-1,ends])
    beta=np.full_like(alpha,-np.inf);beta[-1,ends]=0
    for t in range(time-2,-1,-1):
        for s in range(size):
            following=outgoing[s]
            beta[t,s]=logsum(lp[t+1,states[following]]+beta[t+1,following])
    posterior=np.zeros_like(lp)
    state_posterior=np.exp(alpha+beta-log_probability)
    for s,symbol in enumerate(states):posterior[:,symbol]+=state_posterior[:,s]
    gradient=np.exp(lp)-posterior
    return -log_probability,gradient,{'feasible':True,'minimumFrames':minimum,
            'logProbability':log_probability,'posterior':posterior}


def greedy_decode(logits,blank=0):
    lp=log_softmax(logits);validate_blank(blank,lp.shape[1])
    return collapse(lp.argmax(axis=1),blank)


def prefix_beam(logits,beam_size=32,blank=0):
    """Pruned prefix beam with separate blank/nonblank ending masses; no LM.

    Returned scores retain only paths surviving pruning; finite beams do not
    guarantee the global most probable transcription. Ties sort lexicographically.
    """
    lp=log_softmax(logits);validate_blank(blank,lp.shape[1])
    if type(beam_size) is not int or not 1<=beam_size<=1024:raise ValueError('beam size1..1024 required')
    beam={():[0.,-np.inf]}
    for row in lp:
        updated={}
        def add(prefix,kind,value):
            masses=updated.setdefault(prefix,[-np.inf,-np.inf]);masses[kind]=np.logaddexp(masses[kind],value)
        for prefix,(pb,pn) in beam.items():
            total=np.logaddexp(pb,pn);add(prefix,0,total+row[blank])
            for symbol in range(len(row)):
                if symbol==blank:continue
                if prefix and prefix[-1]==symbol:
                    add(prefix,1,pn+row[symbol])
                    add(prefix+(symbol,),1,pb+row[symbol])
                else:add(prefix+(symbol,),1,total+row[symbol])
        ranked=sorted(updated.items(),key=lambda item:(-np.logaddexp(*item[1]),item[0]))
        beam=dict(ranked[:beam_size])
    return [(prefix,float(np.logaddexp(*mass))) for prefix,mass in sorted(beam.items(),key=lambda item:(-np.logaddexp(*item[1]),item[0]))]


def edit_counts(reference,hypothesis):
    """Token edit DP. Equal-cost paths prefer diagonal, then deletion, insertion."""
    a,b=list(reference),list(hypothesis);n,m=len(a),len(b)
    cost=np.zeros((n+1,m+1),int);trace=np.zeros_like(cost)
    cost[:,0]=np.arange(n+1);cost[0,:]=np.arange(m+1);trace[1:,0]=1;trace[0,1:]=2
    for i in range(1,n+1):
        for j in range(1,m+1):
            candidates=[cost[i-1,j-1]+(a[i-1]!=b[j-1]),cost[i-1,j]+1,cost[i,j-1]+1]
            trace[i,j]=int(np.argmin(candidates));cost[i,j]=candidates[trace[i,j]]
    substitutions=deletions=insertions=0;i,j=n,m
    while i or j:
        if trace[i,j]==0:
            substitutions+=int(a[i-1]!=b[j-1]);i-=1;j-=1
        elif trace[i,j]==1:deletions+=1;i-=1
        else:insertions+=1;j-=1
    return {'substitutions':substitutions,'deletions':deletions,'insertions':insertions,
            'distance':int(cost[n,m]),'referenceLength':n}


def error_rate(references,hypotheses,unit='character',normalization=None):
    """Micro edit rate: Python Unicode code points or whitespace-delimited words.

    Optional NFC only. No punctuation/case/space removal, grapheme segmentation,
    Chinese word segmentation, or silently defined rate for an empty denominator.
    """
    if len(references)!=len(hypotheses) or unit not in ['character','word'] or normalization not in [None,'NFC']:
        raise ValueError('paired strings, declared unit and optional NFC required')
    total={'substitutions':0,'deletions':0,'insertions':0,'distance':0,'referenceLength':0}
    exact=0
    for reference,hypothesis in zip(references,hypotheses):
        if not isinstance(reference,str) or not isinstance(hypothesis,str):raise ValueError('string samples required')
        if normalization:
            reference=unicodedata.normalize(normalization,reference);hypothesis=unicodedata.normalize(normalization,hypothesis)
        a,b=(list(reference),list(hypothesis)) if unit=='character' else (reference.split(),hypothesis.split())
        counts=edit_counts(a,b)
        for key in total:total[key]+=counts[key]
        exact+=int(a==b)
    total['rate']=total['distance']/total['referenceLength'] if total['referenceLength'] else None
    total['exactMatch']=exact/len(references) if len(references) else None
    return total


def differentiable_binary(probability,threshold,k=50.):
    """Local DB sigmoid operator, not a text detector or polygon postprocessor."""
    p,t=finite(probability,2),finite(threshold,2)
    if p.shape!=t.shape or min(p.shape)<1 or np.any((p<0)|(p>1)|(t<0)|(t>1)) or not np.isfinite(k) or k<=0:
        raise ValueError('matching probability/threshold maps in[0,1] and positive k required')
    z=k*(p-t);out=np.exp(-np.logaddexp(0,-z));derivative=k*out*(1-out)
    return out,derivative,-derivative


def conv(image,k,b):
    h,w,_=image.shape;size=k.shape[0];pad=size//2
    padded=np.pad(image,((pad,pad),(pad,pad),(0,0)));out=np.broadcast_to(b,(h,w,len(b))).copy()
    for y in range(size):
        for x in range(size):out+=padded[y:y+h,x:x+w] @ k[y,x]
    return out


def conv_backward(image,k,gradient):
    h,w,_=image.shape;size=k.shape[0];pad=size//2
    padded=np.pad(image,((pad,pad),(pad,pad),(0,0)));dx=np.zeros_like(padded);dk=np.zeros_like(k)
    for y in range(size):
        for x in range(size):
            dk[y,x]=np.einsum('hwc,hwf->cf',padded[y:y+h,x:x+w],gradient)
            dx[y:y+h,x:x+w]+=gradient @ k[y,x].T
    return dx[pad:pad+h,pad:pad+w],dk,gradient.sum(axis=(0,1))


def rnn(sequence,parameters):
    wx,wh,b=parameters;hidden=np.zeros((len(sequence),len(b)));previous=np.zeros(len(b))
    for t,x in enumerate(sequence):hidden[t]=np.tanh(x @ wx+previous @ wh+b);previous=hidden[t]
    return hidden


def rnn_backward(sequence,hidden,parameters,gradient):
    wx,wh,b=parameters;dx=np.zeros_like(sequence);dwx=np.zeros_like(wx);dwh=np.zeros_like(wh);db=np.zeros_like(b);carry=np.zeros_like(b)
    for t in range(len(sequence)-1,-1,-1):
        dz=(gradient[t]+carry)*(1-hidden[t]**2);previous=hidden[t-1] if t else np.zeros_like(b)
        dwx+=np.outer(sequence[t],dz);dwh+=np.outer(previous,dz);db+=dz
        dx[t]=dz @ wx.T;carry=dz @ wh.T
    return dx,[dwx,dwh,db]


def parameters(seed=17):
    rng=np.random.default_rng(seed)
    return [rng.normal(0,.2,(3,3,1,3)),np.full(3,.1),
            rng.normal(0,.2,(3,3)),rng.normal(0,.2,(3,3)),np.zeros(3),
            rng.normal(0,.2,(3,3)),rng.normal(0,.2,(3,3)),np.zeros(3),
            rng.normal(0,.2,(6,3)),np.zeros(3)]


def forward(image,p):
    image=finite(image,3)
    if min(image.shape)<1 or image.shape[2]!=1:raise ValueError('nonempty H,W,1 image required')
    feature=np.tanh(conv(image,p[0],p[1]));sequence=feature.mean(axis=0)
    left=rnn(sequence,p[2:5]);right_reversed=rnn(sequence[::-1],p[5:8])
    joined=np.concatenate([left,right_reversed[::-1]],axis=1)
    return joined @ p[8]+p[9],(image,feature,sequence,left,right_reversed,joined)


def backward(p,cache,gradient):
    image,feature,sequence,left,right_reversed,joined=cache;gradient=finite(gradient,2)
    if gradient.shape!=(image.shape[1],3):raise ValueError('matching time,class gradient required')
    dw=joined.T @ gradient;db=gradient.sum(axis=0);dh=gradient @ p[8].T
    dx_left,dp_left=rnn_backward(sequence,left,p[2:5],dh[:,:3])
    dx_reverse,dp_right=rnn_backward(sequence[::-1],right_reversed,p[5:8],dh[:,3:][::-1])
    ds=dx_left+dx_reverse[::-1]
    df=np.broadcast_to(ds[None]/image.shape[0],feature.shape)*(1-feature**2)
    dx,dk,dc=conv_backward(image,p[0],df)
    return [dk,dc]+dp_left+dp_right+[dw,db],dx


def glyph_line(text):
    glyphs={'A':['01110','10001','10001','11111','10001','10001','10001'],
            'B':['11110','10001','10001','11110','10001','10001','11110']}
    if not isinstance(text,str) or not text or any(c not in glyphs for c in text):raise ValueError('nonempty synthetic A/B string required')
    pieces=[]
    for i,c in enumerate(text):
        if i:pieces.append(np.zeros((7,1)))
        pieces.append(np.array([[float(v) for v in row] for row in glyphs[c]]))
    return np.concatenate(pieces,axis=1)[...,None]


def demo():
    image=glyph_line('AA');p=parameters();logits,cache=forward(image,p)
    before,gradient,diagnostic=ctc(logits,[1,1]);dp,dx=backward(p,cache,gradient)
    for value,derivative in zip(p,dp):value-=.05*derivative
    after_logits,_=forward(image,p);after=ctc(after_logits,[1,1])[0];assert after<before
    ambiguous=np.log([[.4,.35,.25],[.4,.35,.25]])
    beams=prefix_beam(ambiguous,32)
    db,dprob,dthreshold=differentiable_binary([[.4,.5,.6]],[[.5,.5,.5]])
    return {'parameters':sum(v.size for v in p),'inputShape':list(image.shape),'frames':len(logits),
            'target':[1,1],'minimumFrames':diagnostic['minimumFrames'],'lossBefore':before,'lossAfterOneStep':after,
            'inputGradientNorm':float(np.linalg.norm(dx)),'networkGreedyAfter':list(greedy_decode(after_logits)),
            'blankSeparatedRepeat':list(collapse([1,1,0,1])),'greedyCounterexample':list(greedy_decode(ambiguous)),
            'bestPrefixCounterexample':list(beams[0][0]),'bestLabelProbability':float(np.exp(beams[0][1])),
            'emptyLabelProbability':float(np.exp(-ctc(ambiguous,[])[0])),
            'cerExample':error_rate(['book','A'],['bok','ABC']),
            'dbValues':db.tolist(),'dbProbabilityGradient':dprob.tolist(),
            'scope':'one synthetic AA update; separate decoding/metric/DB fixtures; not a pretrained or page-level OCR result'}


if __name__=='__main__':print(json.dumps(demo(),indent=2))

Output from the checked environment; final floating-point digits may vary:

{
  "parameters": 93,
  "inputShape": [
    7,
    11,
    1
  ],
  "frames": 11,
  "target": [
    1,
    1
  ],
  "minimumFrames": 3,
  "lossBefore": 5.859007152446334,
  "lossAfterOneStep": 4.692159498168067,
  "inputGradientNorm": 0.024114785000749216,
  "networkGreedyAfter": [
    1,
    1,
    1,
    1
  ],
  "blankSeparatedRepeat": [
    1,
    1
  ],
  "greedyCounterexample": [],
  "bestPrefixCounterexample": [
    1
  ],
  "bestLabelProbability": 0.4024999999999999,
  "emptyLabelProbability": 0.15999999999999998,
  "cerExample": {
    "substitutions": 0,
    "deletions": 1,
    "insertions": 2,
    "distance": 3,
    "referenceLength": 5,
    "rate": 0.6,
    "exactMatch": 0.0
  },
  "dbValues": [
    [
      0.006692850924284861,
      0.5,
      0.9933071490757152
    ]
  ],
  "dbProbabilityGradient": [
    [
      0.332402833539508,
      12.5,
      0.33240283353950717
    ]
  ],
  "scope": "one synthetic AA update; separate decoding/metric/DB fixtures; not a pretrained or page-level OCR result"
}

Loss decreases from 5.85901 to 4.69216. Yet networkGreedyAfter contains four A labels while the target has two. The program exposes this error rather than substituting the ground truth into a demo output. A lower training objective does not guarantee a correct greedy transcription after one step.

A convolution costs O(HWk²CinCout). A tanh recurrent direction with feature width D and hidden width H costs O(T(DH+H²)); the bidirectional model runs two directions. Our CTC calculation costs O(TC+TU) for C classes and target length U, storing O(T(C+U)) arrays for logits/posteriors and alignment states. A forward-only probability calculation can reduce the alignment-state memory, but this example retains it for gradients.

For a beam of width B, prefix expansion considers O(TBC) symbol extensions before ranking. Python tuple copying and sorting add overhead; the code is a transparent small decoder, not a production speed claim. Edit alignment uses O(NM) time and memory for sequences of lengths N and M because it retains a backtrace, not just the final distance.

A fluent reconstruction may still change the evidence

Lost pixels cannot be restored by a good language prior. Blur, skew, compression and low contrast can remove distinctions such as a decimal point. A language model may produce a plausible reconstruction, but plausibility is not a faithful transcription. Keep raw output, alternatives or rejection status, and the source crop when the value matters.

Recognition systems and parsers differ. The 2007 Tesseract overview describes a historical binary-image/blob/line pipeline with two-pass adaptive recognition. The fixed modern README says Tesseract 4 added an LSTM line engine while retaining a legacy mode. Do not present the old classifier description as the only current engine. Historical engine, modern project

Small and large models have configuration boundaries. The PP-OCRv5 CVPR 2026 paper’s “5M” refers to its mobile detection-plus-recognition configuration, not every v5 model. Its described recognizer uses attention-guided CTC training; guidance during training does not make our plain CTC example a reproduction. We have not rerun the paper’s comparative benchmarks. Configuration and method

By the edition cutoff, the fixed PaddleOCR README also records PP-OCRv6, PaddleOCR-VL-1.6 and HPD-Parsing. Its text-recognition and document-parsing families should not be collapsed into one model name or one accuracy number. The 2025 report’s three-solution overview remains useful context, but is not a claim that v5 is the latest available model. Dated project overview, 2025 report

Deployment adds its own questions. Measure peak memory, latency at the actual page size, supported character inventory, confidence/rejection policy and corrections required per document. Split data by document or source collection where appropriate to avoid near-duplicate leakage. Check data and model rights separately from repository code licensing; the inspected PaddleOCR code license heading is Apache 2.0, not blanket evidence about every dataset. Code license heading

Four checks for a trustworthy transcription

1. Keep the repeated letter

Collapse A A blank A. Why does deleting blanks before merging repeats give the wrong result? How many frames are required for target “AA”?

Answer: Merge consecutive repeats first to obtain A blank A, then remove blank to obtain AA. Deleting blank first would incorrectly turn all A symbols into one run. Two target symbols plus one adjacent repeat require three frames. CTC blank is not a printed space.

2. Sum labels instead of guessing from peaks

Both frames have probabilities [blank:0.4, A:0.35, B:0.25]. Compute the empty-string probability and the probability of label “A”.

Answer: Only blank-blank collapses to empty, giving 0.4²=0.16. “A” receives A-A, A-blank and blank-A: 0.35²+0.35×0.4+0.4×0.35=0.4025. Greedy’s most probable path therefore does not supply the most probable label.

3. Audit an error-rate denominator

The references are book and A; outputs are bok and ABC. Calculate corpus CER. Then consider an empty reference with output X.

Answer: One deletion plus two insertions gives three edits over five reference code points: CER=0.6. The empty reference contributes an insertion but no reference character. If it is the only sample, the rate is undefined, not zero; if part of a corpus, its insertion still enters the numerator.

4. Diagnose a successful loss and a failed document

The tiny network’s loss falls while its greedy result is AAAA for target AA. Separately, a parser recognizes every word but assigns an amount to the wrong table row. What should each evaluation report?

Answer: Report the network’s lower CTC objective together with its wrong transcription; compute edit errors using the actual output. The page parser needs reading-order/cell-assignment or field-level evaluation even if character error is zero. Neither a low loss nor perfect crop-level character recognition proves a correct document.

Follow the task changes, not just engine names

Tesseract’s sources agree that HP released it as open source in 2005. They differ on when development began: the 2007 paper says 1984, while the fixed README says 1985. Both place its origin in HP’s 1980s work; we retain the discrepancy rather than inventing one authoritative start date. Historical account, repository history

CTC was published at ICML 2006 for unsegmented sequence labeling, with a speech experiment; it was not originally an entire page-OCR system. CRNN’s first preprint appeared on 21 July 2015. DBNet’s first preprint was submitted on 20 November 2019, distinct from its AAAI 2020 venue. CTC paper, CRNN history, DBNet history

PaddleOCR 3.0’s technical report was submitted on 8 July 2025. The fixed project README later records PaddleOCR 3.7.0 and PP-OCRv6 on 11 June 2026; a report date, software release and paper publication are different events. Report history, fixed release notes

For a useful reproduction, preserve the image preprocessing, detector/crop policy, character dictionary, blank index, frame lengths, training loss reduction, decoder and evaluation normalization. These details decide which output is possible and what an error count means. This article makes a small version inspectable; full OCR accuracy and document parsing remain separate empirical tasks.

Make a prediction, then check

What does the CTC path A A blank A collapse to?

Choose one answer

Learning objectives

  • Separate detection, line recognition, reading order and document structure.
  • Trace CTC paths, blank/repeat rules and complete neural gradients.
  • Compare greedy decoding with prefix probability accumulation and finite-beam limits.
  • Report edit counts, normalization policies and pipeline-level failures honestly.

Prerequisites & connections

Explore related knowledge →

References

  1. Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Networks
    Alex Graves; Santiago Fernández; Faustino Gomez; Jürgen Schmidhuber · 2006
  2. An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition
    Baoguang Shi; Xiang Bai; Cong Yao · 2015
  3. Real-time Scene Text Detection with Differentiable Binarization
    Minghui Liao; Zhaoyi Wan; Cong Yao; Kai Chen; Xiang Bai · 2019
  4. An Overview of the Tesseract OCR Engine
    Ray Smith · 2007
  5. PaddleOCR 3.0 Technical Report
    Cheng Cui et al. · 2025
  6. PP-OCRv5: A Specialized 5M-Parameter Model Rivaling Billion-Parameter Vision-Language Models on OCR Tasks
    Cheng Cui; Yubo Zhang et al. · 2026
  7. PaddleOCR fixed family overview and releases
    PaddlePaddle contributors · 2026
  8. PaddleOCR fixed Apache2.0 license heading
    PaddlePaddle contributors · 2026
  9. PaddleOCR fixed CTC decoding and score calculation
    PaddlePaddle contributors · 2026
  10. PaddleOCR fixed CTC loss wrapper
    PaddlePaddle contributors · 2026
  11. PaddleOCR fixed DB postprocessing
    PaddlePaddle contributors · 2026
  12. Tesseract fixed neural and legacy engine overview
    Tesseract contributors · 2026
  13. An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition — submission history
    Baoguang Shi; Xiang Bai; Cong Yao · 2015
  14. Real-time Scene Text Detection with Differentiable Binarization — submission history
    Minghui Liao; Zhaoyi Wan; Cong Yao; Kai Chen; Xiang Bai · 2019
  15. PaddleOCR 3.0 Technical Report — submission history
    Cheng Cui et al. · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: scoped original OCR/CTC papers and fixed PaddleOCR/Tesseract sources; exhaustive CTC paths/posteriors, full93-parameter model gradients, independent decoding/edit/DB tests, bilingual comparison and computed diagram binding. Not human peer review or OCR benchmark reproduction.

  • Twenty numerical tests plus four bilingual/output/metadata/diagram checks; all93 CNN/BiRNN parameters and20 inputs central differences through CTC, exhaustive paths/occupancy, empty/repeated/impossible targets, prefix-beam versus exact search, edit-count normalization and DB derivatives.
  • Compared complete bilingual arguments, eight display equations, full code/output, four explained exercises and15 scoped sources. Preserved wrong AAAA prediction despite lower loss, future-only beta convention, text versus page scope, old/new engine boundaries and Tesseract date discrepancy. Reused existing CTC event instead of duplicating it.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.