File size: 17,604 Bytes
7bb24f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"""The trained OCR architectures, defined once and shared by training and serving.

`services/ocr-lab/train_*.py` builds these; `ocr_model.py` loads the resulting weights
behind the same `recognize()` contract every other backend uses. They live on the
serving side rather than in the lab because the lab never ships and these must — a
checkpoint is useless without the class that describes it, and two copies of a module
drift the moment one of them is edited.

Nothing here is OCR-specific plumbing: no preprocessing, no decoding, no file formats.
Just the modules, so the shapes a checkpoint was saved with are the shapes it loads into.
"""
import math

import torch
import torch.nn as nn

# The layout classes the corpus is generated with. Order is the label order, so it is
# part of the checkpoint's meaning — appending is safe, reordering silently relabels
# every trained weight.
CATEGORIES = ["column", "article_head", "section_head", "header", "photo",
              "caption", "page_number"]
CAT_ID = {c: i for i, c in enumerate(CATEGORIES)}

# Line images are scaled to this height before recognition; the width follows the
# aspect ratio. Baked into the conv stack's geometry, so it is not a free parameter.
REC_HEIGHT = 48


class CRNN(nn.Module):
    """Line image → character sequence. Convolutions collapse the line to a sequence,
    a BiLSTM reads it, CTC aligns it.

    Height reduces to 1 and width to W/4, so a 1000 px line becomes 250 timesteps —
    comfortably more than the ~90 characters such a line holds, which is the condition
    CTC needs in order to be able to emit them all.
    """

    def __init__(self, n_classes, nc=1):
        super().__init__()

        def blk(i, o, pool):
            layers = [nn.Conv2d(i, o, 3, 1, 1), nn.BatchNorm2d(o), nn.ReLU(True)]
            if pool:
                layers.append(nn.MaxPool2d(pool, pool))
            return layers

        self.cnn = nn.Sequential(
            *blk(nc, 64, (2, 2)),        # 48 → 24,  W/2
            *blk(64, 128, (2, 2)),       # 24 → 12,  W/4
            *blk(128, 256, None),
            *blk(256, 256, (2, 1)),      # 12 → 6,   W/4
            *blk(256, 512, None),
            *blk(512, 512, (2, 1)),      # 6  → 3,   W/4
            nn.Conv2d(512, 512, (3, 1)), nn.BatchNorm2d(512), nn.ReLU(True),  # 3 → 1
        )
        self.rnn = nn.LSTM(512, 256, num_layers=2, bidirectional=True,
                           batch_first=True, dropout=0.1)
        self.out = nn.Linear(512, n_classes)

    def forward(self, x):
        f = self.cnn(x)                       # B,512,1,T
        f = f.squeeze(2).permute(0, 2, 1)     # B,T,512
        f, _ = self.rnn(f)
        return self.out(f)                    # B,T,C


class Orderer(nn.Module):
    """Detected blocks → reading order and article grouping.

    Two bilinear heads over a transformer encoder: `precedes(a,b)` and `same_flow(a,b)`.
    Self-attention is permutation-equivariant, which is what the job requires — the
    input is a *set* of boxes from a detector, and the model must not be able to cheat
    by reading the order it was handed.
    """

    def __init__(self, d_in, d=192, layers=4, heads=6):
        super().__init__()
        self.inp = nn.Sequential(nn.Linear(d_in, d), nn.GELU(), nn.Linear(d, d))
        enc = nn.TransformerEncoderLayer(d, heads, d * 4, batch_first=True,
                                         dropout=0.1, norm_first=True)
        self.enc = nn.TransformerEncoder(enc, layers)
        self.prec = nn.Bilinear(d, d, 1)
        self.same = nn.Bilinear(d, d, 1)

    def forward(self, x, mask):
        h = self.enc(self.inp(x), src_key_padding_mask=~mask)
        n = h.shape[1]
        a = h[:, :, None, :].expand(-1, -1, n, -1).reshape(-1, h.shape[-1])
        b = h[:, None, :, :].expand(-1, n, -1, -1).reshape(-1, h.shape[-1])
        prec = self.prec(a, b).view(h.shape[0], n, n)
        same = self.same(a, b).view(h.shape[0], n, n)
        # Precedence is asymmetric by construction; grouping is symmetrised, since
        # "same article" cannot depend on which block you name first.
        return prec, (same + same.transpose(1, 2)) / 2


def block_features(blocks, width, height):
    """Geometry only — never text. The orderer runs on the detector's output, at which
    point nothing on the page has been read yet."""
    feats = []
    for b in blocks:
        x0, y0, x1, y1 = b["bbox"]
        x0, x1 = x0 / width, x1 / width
        y0, y1 = y0 / height, y1 / height
        onehot = [0.0] * len(CATEGORIES)
        onehot[CAT_ID.get(b.get("type", "column"), 0)] = 1.0
        feats.append([x0, y0, x1, y1, x1 - x0, y1 - y0,
                      (x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0) * (y1 - y0)] + onehot)
    return torch.tensor(feats, dtype=torch.float32)


def ctc_greedy(logits, itos):
    """Greedy CTC decode: argmax, drop repeats, drop blanks (index 0)."""
    out = []
    for seq in logits.argmax(-1):
        chars, prev = [], -1
        for t in seq.tolist():
            if t != prev and t != 0:
                chars.append(itos[t])
            prev = t
        out.append("".join(chars))
    return out


def load_script_masks(crnn_dir, itos):
    """`scripts.json` beside a CRNN (ocr-lab/scripts/script_masks.py) → {alphabet: bool
    tensor over the CTC classes}, or None for a reader that has no such file (rec-real reads
    one alphabet and needs none). The blank, class 0, is allowed in every alphabet."""
    import json
    import os
    p = os.path.join(crnn_dir, "scripts.json")
    if not os.path.isfile(p):
        return None
    sets = json.loads(open(p, encoding="utf-8").read())
    masks = {}
    for name, chars in sets.items():
        allowed = set(chars)
        masks[name] = torch.tensor([i == 0 or c in allowed for i, c in enumerate(itos)])
    return masks


OLD_ALPHABETS = ("georgian", "latin", "oldcyr")
# The vote, in nats of summed log-probability (see `lock_block`): a word is EVIDENCE for an
# old alphabet when that alphabet beats modern on it by `strong_nats`; a block may use an
# old alphabet when at least `min_words` of its words, and `min_frac` of them, are evidence;
# inside such a block a word goes to modern Cyrillic when modern beats the old alphabet on
# it by `word_nats`; a modern line that came out mostly Latin is re-read Cyrillic-only unless
# that costs more than `latin_per_letter` per letter.
LOCK_DEFAULTS = {"strong_nats": 5.0, "min_words": 3.0, "min_frac": 0.15, "word_nats": 2.0,
                 "latin_per_letter": 1.0}


def _mostly_latin(text):
    import unicodedata
    letters = [c for c in text if c.isalpha()]
    return len(letters) >= 4 and sum(
        unicodedata.name(c, "").startswith("LATIN") for c in letters) > len(letters) / 2


def lock_block(logits_list, itos, masks, forced="auto", params=None):
    """One BLOCK's lines (logits [T, C] each) → (alphabet, [(text, confidence, alphabet)],
    vote) — each word read in one alphabet, and old alphabets only where the block shows them.

    A reader that knows four alphabets, left free, put a Georgian letter or a whole 1928
    Latin line into 25 of 26.6k modern lines (5 Nov 2026, «напх- rana agvna»), which the
    modern-only reader never did. A block-wide lock fixed that but broke real old pages:
    1930s dictionaries and primers mix alphabets INSIDE a line («ახჷ რხუარა — Кланяться»),
    the Russian glosses outvoted the Abkhaz headwords, and the headwords came out as junk.
    So the unit of choice is the WORD (frames between the free reading's spaces), and the
    unit of PERMISSION is the block:

    1. Per word and alphabet, the summed log-probability of the best path under that
       alphabet's mask, scored with the FULL softmax — the alphabet a word is printed in
       loses almost nothing; the others lose several nats per letter.
    2. A word is evidence for an old alphabet when it beats modern by `strong_nats`. The
       block may use the old alphabet with the most evidence only if that is `min_words`
       words and `min_frac` of the block's words. A modern block with one misread line has
       a word or two in ~400; a Georgian-headword dictionary block has a third.
    3. Not permitted → every line is read with the modern mask (nothing today's reader
       could not have said), plus the mostly-Latin check. Permitted → each word is read in
       the block's old alphabet unless modern beats it there by `word_nats`.

    `forced` = an alphabet name skips the vote (a page the user labelled); "auto" votes."""
    p = {**LOCK_DEFAULTS, **(params or {})}
    import unicodedata
    seps = {i for i, c in enumerate(itos) if i and not c.isalpha()
            and unicodedata.category(c) != "Mn" and not 0xE000 <= ord(c) <= 0xF8FF}
    neg = float("-inf")
    olds = [k for k in OLD_ALPHABETS if k in masks]

    def collapse(idx, val):
        txt, confs, prev = [], [], -1
        for t, i in enumerate(idx):
            if i != prev and i != 0:
                txt.append(itos[i])
                confs.append(math.exp(val[t]))
            prev = i
        return "".join(txt), (sum(confs) / len(confs)) if confs else 0.0

    per, evidence, nwords = [], {k: 0 for k in olds}, 0
    for lg in logits_list:
        logp = torch.log_softmax(lg.float(), -1)
        best = {k: logp.masked_fill(~m, neg).max(-1) for k, m in masks.items()}
        best = {k: (v.indices.tolist(), v.values.tolist()) for k, v in best.items()}
        free = logp.argmax(-1).tolist()
        # Words = runs between the free reading's separators — spaces AND punctuation, since
        # a dictionary joins headword and gloss with a bare dash («დთახჾეიტ—Погиб»).
        cuts, s0 = [], 0
        for t, i in enumerate(free):
            if i in seps:
                cuts += [(s0, t), (t, t + 1)]
                s0 = t + 1
        cuts.append((s0, len(free)))
        cuts = [(s, e) for s, e in cuts if e > s]
        words = []
        for s, e in cuts:
            sc = {k: sum(best[k][1][s:e]) for k in best}
            letters = sum(itos[i].isalpha() for i in free[s:e] if i)
            if letters >= 2:
                nwords += 1
                for k in olds:
                    if sc[k] - sc["modern"] > p["strong_nats"]:
                        evidence[k] += 1
            words.append((s, e, sc))
        per.append((best, words))

    A = max(olds, key=evidence.get) if olds else None
    if forced in olds:
        A, permitted = forced, True
    elif forced == "modern" or A is None:
        permitted = False
    else:
        permitted = evidence[A] >= p["min_words"] and evidence[A] >= p["min_frac"] * nwords

    lines = []
    for best, words in per:
        if not permitted:
            t, c = collapse(*best["modern"])
            if "modern_cyr" in best and _mostly_latin(t):
                letters = sum(ch.isalpha() for ch in t)
                if sum(best["modern"][1]) - sum(best["modern_cyr"][1]) <= \
                        p["latin_per_letter"] * letters:
                    t, c = collapse(*best["modern_cyr"])
            lines.append((t, c, "modern"))
            continue
        # The way back is Cyrillic-only: what an old block holds besides its own alphabet is
        # Russian or modern Abkhaz. With Latin allowed, a 1928 word re-read "modern" came
        # back half Cyrillic (agent keys, 5 Nov: а, о, і, е inside Latin words).
        alt = "modern_cyr" if "modern_cyr" in best else "modern"
        idx, val, used = [], [], False
        for s, e, sc in words:
            k = alt if sc[alt] - sc[A] > p["word_nats"] else A
            used |= k == A
            idx += best[k][0][s:e]
            val += best[k][1][s:e]
        t, c = collapse(idx, val)
        lines.append((t, c, A if used else "modern"))
    vote = {"evidence": evidence, "words": nwords, "permitted": permitted}
    return (A if permitted else "modern"), lines, vote


def ctc_nbest(logits, itos, width=8, topk=5, prune=-9.0):
    """Prefix beam search over ONE line's logits → [(text, log-probability), …].

    No language model here on purpose: this is the acoustic half, and it is the half that
    must stay cheap. Its job is to offer the alternatives argmax discards — argmax commits
    to one letter per frame and can never report that frame 41 was nearly `ԥ` — so that a
    language model can choose between whole readings afterwards (`ocr_lm.rescore`).

    Pruned two ways, because the inner loop is python: only the `topk` classes at each
    frame, and only those within `prune` nats of the frame's best. On a well-trained CTC
    output most frames are a confident blank, so the beam collapses to one prefix and the
    step costs almost nothing.
    """
    logp = torch.log_softmax(logits.float(), dim=-1)
    T = logp.shape[0]
    top = logp.topk(min(topk, logp.shape[1]), dim=-1)
    values, indices = top.values.tolist(), top.indices.tolist()
    neg = float("-inf")
    beams = {"": (0.0, neg)}                       # prefix -> (log p_blank, log p_symbol)

    def lse(a, b):
        if a == neg:
            return b
        if b == neg:
            return a
        m = a if a > b else b
        return m + math.log(math.exp(a - m) + math.exp(b - m))

    for t in range(T):
        cand = {}
        cut = values[t][0] + prune
        for prefix, (pb, pnb) in beams.items():
            ptot = lse(pb, pnb)
            for p, c in zip(values[t], indices[t]):
                if p < cut:
                    break
                if c == 0:                          # blank keeps the prefix as it is
                    e = cand.get(prefix) or (neg, neg)
                    cand[prefix] = (lse(e[0], ptot + p), e[1])
                    continue
                ch = itos[c]
                if prefix and prefix[-1] == ch:
                    # A repeat only starts a new letter across a blank; otherwise it is
                    # the same letter held for another frame. This distinction is the
                    # whole reason CTC needs two probabilities per prefix.
                    e = cand.get(prefix) or (neg, neg)
                    cand[prefix] = (e[0], lse(e[1], pnb + p))
                    base = pb
                else:
                    base = ptot
                grown = prefix + ch
                e = cand.get(grown) or (neg, neg)
                cand[grown] = (e[0], lse(e[1], base + p))
        beams = dict(sorted(cand.items(), key=lambda kv: -lse(*kv[1]))[:width])

    out = {k: lse(*v) for k, v in beams.items()}

    # The greedy string is always a candidate, with the log-probability of its own best
    # alignment. Measured, and the reason this is here: ranking the beam by label
    # likelihood alone scored WORSE than argmax on both a clean page (1.46 % → 2.39 %)
    # and the newspaper (7.89 % → 8.04 %). A CTC model this confident puts nearly all the
    # mass on one alignment, so summing alignments mostly adds noise from near-duplicate
    # labellings. Keeping argmax in the list means the language model chooses between it
    # and the alternatives instead of never seeing it.
    best = logp.argmax(-1).tolist()
    chars, prev, score = [], -1, 0.0
    for t, c in enumerate(best):
        if c != prev and c != 0:
            chars.append(itos[c])
        prev = c
        score += float(logp[t, c])
    greedy = "".join(chars)
    if greedy not in out or out[greedy] < score:
        out[greedy] = score

    return sorted(out.items(), key=lambda kv: -kv[1])


class _LMBlock(nn.Module):
    def __init__(self, dim, heads):
        super().__init__()
        self.ln1, self.ln2 = nn.LayerNorm(dim), nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, heads, batch_first=True)
        self.mlp = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(),
                                 nn.Linear(4 * dim, dim))

    def forward(self, x, mask):
        h = self.ln1(x)
        a, _ = self.attn(h, h, h, attn_mask=mask, need_weights=False)
        x = x + a
        return x + self.mlp(self.ln2(x))


class CharLM(nn.Module):
    """Character-level causal LM over Abkhaz, used to score whether a JOIN reads.

    Not a decoder and not a recognizer — it never sees an image. It exists because the
    one step that actually settled the Аԥсны broadsheet was reading the text and checking
    that the split sentence continued, and no vision model performs that step: asked to
    derive the page's layout, the closed teacher answers "the reading order is standard
    left-to-right, top-to-bottom" and folds the column-major sidebar into its neighbour.

    Character-level because its input at serving time is OCR output with real errors in
    it. A subword tokenizer meeting a mangled token loses the whole token; a character
    model degrades gracefully, which is the entire requirement here.
    """

    def __init__(self, vocab, dim=384, layers=6, heads=6, ctx=256):
        super().__init__()
        self.tok = nn.Embedding(vocab, dim)
        self.pos = nn.Embedding(ctx, dim)
        self.blocks = nn.ModuleList([_LMBlock(dim, heads) for _ in range(layers)])
        self.ln = nn.LayerNorm(dim)
        self.head = nn.Linear(dim, vocab, bias=False)
        self.ctx = ctx

    def forward(self, idx):
        T = idx.shape[1]
        x = self.tok(idx) + self.pos(torch.arange(T, device=idx.device))
        mask = torch.triu(torch.full((T, T), float("-inf"), device=idx.device), 1)
        for b in self.blocks:
            x = b(x, mask)
        return self.head(self.ln(x))