codetomato commited on
Commit
e9a85fb
·
verified ·
1 Parent(s): dd77f47

Coptic OCR: segmenter, recognizers (E17s1, E10a), char LM, inference code

Browse files
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ language:
4
+ - cop
5
+ pipeline_tag: image-to-text
6
+ tags:
7
+ - ocr
8
+ - htr
9
+ - coptic
10
+ - sahidic
11
+ - manuscripts
12
+ - ctc
13
+ datasets:
14
+ - blowing-up-groundhogs/scam
15
+ ---
16
+
17
+ # Coptic OCR (Sahidic manuscripts and print)
18
+
19
+ This model reads Coptic text from photos or scans of whole pages. It was trained mainly on Sahidic manuscripts from the White Monastery (Vatican, Borg. copt. 109). It also handles printed Sahidic reasonably well.
20
+
21
+ The pipeline has three parts:
22
+
23
+ 1. **Line finder:** Kraken BLLA baseline segmentation, fine-tuned on SCAM pages, plus column-aware reading order.
24
+ 2. **Recognizer:** reads each line. It's a CTC model: an ImageNet ResNet-50, cut after layer3, followed by a 2-layer BiLSTM with 512 units.
25
+ 3. **Language model:** a 5-gram character model trained on Coptic Scriptorium text, used during CTC beam search (shallow fusion, α=0.35, β=0.5, beam 12).
26
+
27
+ ## Files
28
+
29
+ | File | What it is |
30
+ |---|---|
31
+ | `models/recognizer.safetensors` + `.json` | The default line recognizer (run E17s1): ResNet-50, trained on gold plus self-labelled lines, with simulated show-through. Best overall. |
32
+ | `models/recognizer_manuscript.safetensors` + `.json` | A ResNet-34 recognizer fine-tuned on gold lines only (run E10a). Slightly better on full test pages, much worse on print. |
33
+ | `models/segmenter.safetensors` | Kraken BLLA line segmenter, fine-tuned on SCAM pages |
34
+ | `models/coptic_char5.pkl` | 5-gram character language model, stored as a pickle of plain Python dicts |
35
+ | `scripts/` | Inference code: `transcribe.py` is the entry point. Training code is in `train_crnn.py`. |
36
+
37
+ ## Usage
38
+
39
+ ```bash
40
+ pip install -r requirements.txt # torch, torchvision, kraken 7.2, pillow, numpy, safetensors
41
+ python scripts/transcribe.py page.jpg # one line of text per detected line, in reading order
42
+ python scripts/transcribe.py page.jpg --overlay boxes.jpg
43
+ python scripts/transcribe.py line1.png line2.png --lines # inputs are already single-line crops
44
+ python scripts/transcribe.py page.jpg --rec models/recognizer_manuscript.safetensors
45
+ python scripts/transcribe.py page.jpg --no-lm # greedy decoding without the language model
46
+ ```
47
+
48
+ It runs on CPU or CUDA. A page takes about 2 s on a laptop GPU.
49
+
50
+ ## Results
51
+
52
+ **CER** is the character error rate, counting a letter and its marks as one character (as the SCAM paper does), so lower is better. The **ignoring spaces** column matters because the manuscripts have no word spaces, which makes word division a matter of convention.
53
+
54
+ | Benchmark | E17s1 (default) | E10a (manuscript) |
55
+ |---|---|---|
56
+ | SCAM-A test lines, official CER | **11.52** | 11.99 |
57
+ | SCAM-A test lines, ignoring spaces | **8.01** | 8.50 |
58
+ | SCAM-A test, full pages (automatic segmentation) | 7.04 | **6.69** |
59
+ | 35 held-out leaves by unseen scribes, letter CER vs. the Sahidic Bible* | 10.99 | 10.98 |
60
+ | Printed: Horner's Sahidic Luke, letter CER vs. the edition* | **18.11** | 30.62 |
61
+
62
+ \* These pages have no gold transcription. Each page's letters are compared with the matching passage of a printed edition, ignoring diacritics, punctuation and spaces. Lectionary pages that switch passage are scored one passage at a time. Real spelling differences between the scribe and the edition count as errors, so these numbers overstate the true error rate. Use them to compare models, not as absolute accuracy.
63
+
64
+ Published results on the same SCAM-A test lines: VAN 7.50, CRNN 13.91, TrOCR-L 14.99 ([SCAM paper](https://arxiv.org/abs/2606.15987)). This model beats the paper's line-level baselines. It does not match VAN, which reads whole paragraphs at once.
65
+
66
+ ## Training data
67
+
68
+ - **[SCAM](https://huggingface.co/datasets/blowing-up-groundhogs/scam)** (CC-BY 4.0): gold line transcriptions of a Sahidic manuscript. Only the training split was used; val selected the model and test was scored once.
69
+ - **About 22k self-labelled lines** from other Borg. copt. 109 leaves (Vatican Library digitizations). The model's own transcriptions were kept where a strict agreement filter passed. Held-out fascicles used for evaluation were excluded.
70
+ - **Synthetic lines** rendered in Coptic fonts from [Coptic Scriptorium](https://github.com/CopticScriptorium/corpora) text (CC-BY 4.0), which also trained the language model.
71
+ - **Horner's printed Sahidic New Testament** (public domain), with lines aligned to the edition text.
72
+
73
+ Training images are not included in this repo. Manuscript images are © Biblioteca Apostolica Vaticana.
74
+
75
+ ## Limitations
76
+
77
+ - **Sahidic only.** It was trained on Sahidic, mostly one scriptorium's style. Bohairic, other dialects and very different hands will be worse.
78
+ - **Damage hurts.** Errors cluster on damaged lines (bleed-through, tears, marginal notes).
79
+ - **Simple page layouts.** It expects one or two text columns. Ornaments, marginalia and complex layouts may be split into lines or ordered wrongly.
80
+ - **Output conventions follow the SCAM transcription:** lowercase letters with combining marks (superlinear stroke, dots, trema), and spaces as word division.
models/coptic_char5.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6979989fc990f76b833fc2c5654e002fb1580c01a460a4ae807bca8d37bcf1e3
3
+ size 3765801
models/recognizer.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "codec": [
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
+ "args": {
48
+ "name": "E17s1_E14_showthrough_seed1",
49
+ "train": "data/mix/E13.lst",
50
+ "val": "/home/computah/.t3/projects/coptic-transcription/data/scam_a/val.lst",
51
+ "synth": [
52
+ "data/synth/v1"
53
+ ],
54
+ "synth_ratio": 0.3,
55
+ "init": null,
56
+ "backbone": "resnet50",
57
+ "no_pretrained": false,
58
+ "height": 64,
59
+ "max_width": 1200,
60
+ "hidden": 512,
61
+ "dropout": 0.2,
62
+ "batch": 24,
63
+ "steps": 20000,
64
+ "lr": 0.0005,
65
+ "wd": 0.01,
66
+ "warmup": 300,
67
+ "augment": 1.0,
68
+ "showthrough": 0.3,
69
+ "eval_every": 1000,
70
+ "workers": 14,
71
+ "seed": 1
72
+ },
73
+ "step": 20000,
74
+ "val": {
75
+ "cer": 7.2311046511627906,
76
+ "cer_codepoint": 6.970418225093505,
77
+ "ser": 42.56198347107438,
78
+ "cer_nospace": 7.090909090909091,
79
+ "lines": 242
80
+ }
81
+ }
models/recognizer.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06189b57b7845019e050b943153e2ca9231fa51f588ff7f46b62bdf182489b7a
3
+ size 84897912
models/recognizer_manuscript.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "codec": [
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
+ "args": {
48
+ "name": "E10a_E09_ft_gold",
49
+ "train": "/home/computah/.t3/projects/coptic-transcription/data/scam_a/train.lst",
50
+ "val": "/home/computah/.t3/projects/coptic-transcription/data/scam_a/val.lst",
51
+ "synth": [],
52
+ "synth_ratio": 0.0,
53
+ "init": "runs/E09_gold10x_pseudo3_pool12_synth30/best.pt",
54
+ "backbone": "resnet34",
55
+ "no_pretrained": false,
56
+ "height": 64,
57
+ "max_width": 1200,
58
+ "hidden": 256,
59
+ "dropout": 0.2,
60
+ "batch": 24,
61
+ "steps": 2000,
62
+ "lr": 0.0001,
63
+ "wd": 0.01,
64
+ "warmup": 100,
65
+ "augment": 1.0,
66
+ "eval_every": 200,
67
+ "workers": 5,
68
+ "seed": 0
69
+ },
70
+ "step": 2000,
71
+ "val": {
72
+ "cer": 7.8125,
73
+ "cer_codepoint": 7.616456987419245,
74
+ "ser": 45.04132231404959,
75
+ "lines": 242
76
+ }
77
+ }
models/recognizer_manuscript.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c5f2a9c15682f10b5f7892cc59900fd445c2e8241a6211f7edc0caaf01f5292
3
+ size 43346656
models/segmenter.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d851b7d157ce6d98f9d5fbd4a1b18e47bb074a500626b8715c3e9df92654025a
3
+ size 5054432
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch==2.14.0
2
+ torchvision==0.29.2
3
+ kraken==7.2
4
+ numpy==2.4.6
5
+ pillow==13.0.0
6
+ safetensors==0.7.0
scripts/charlm.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Character n-gram language model (interpolated Witten-Bell) + CTC prefix beam search.
2
+
3
+ The LM is trained on Coptic Scriptorium manuscript lines converted to SCAM
4
+ conventions (see scam_convention.py). We checked that SCAM-A val/test text is
5
+ not contained in Coptic Scriptorium (see EXPERIMENTS.md, "leakage check").
6
+
7
+ python scripts/charlm.py train data/text/cs_lines.tsv data/lm/cs_order7.pkl --order 7
8
+ """
9
+ import math
10
+ import pickle
11
+ import sys
12
+ from collections import defaultdict
13
+ from pathlib import Path
14
+
15
+ sys.path.insert(0, str(Path(__file__).parent))
16
+
17
+ BOS = "\x02"
18
+ EOS = "\x03"
19
+ # Marks the LM cannot predict from text: visual gaps (space) and the SCAM
20
+ # "illegible letter" dot. They get a fixed log-prob and are skipped in history.
21
+ TRANSPARENT = {" ", "."}
22
+ TRANSPARENT_LOGP = math.log(0.02)
23
+
24
+
25
+ def strip_transparent(s):
26
+ return "".join(c for c in s if c not in TRANSPARENT)
27
+
28
+
29
+ class CharLM:
30
+ def __init__(self, order=7):
31
+ self.order = order
32
+ self.counts = [defaultdict(lambda: defaultdict(int)) for _ in range(order)]
33
+ self.vocab = set()
34
+ self._cache = {}
35
+
36
+ def fit(self, lines):
37
+ for line in lines:
38
+ s = BOS * (self.order - 1) + line + EOS
39
+ self.vocab.update(line)
40
+ for i in range(self.order - 1, len(s)):
41
+ c = s[i]
42
+ for n in range(self.order):
43
+ h = s[i - n:i]
44
+ self.counts[n][h][c] += 1
45
+ self.vocab.add(EOS)
46
+ # freeze to plain dicts with totals
47
+ self.tables = []
48
+ for n in range(self.order):
49
+ t = {}
50
+ for h, d in self.counts[n].items():
51
+ t[h] = (dict(d), sum(d.values()), len(d))
52
+ self.tables.append(t)
53
+ del self.counts
54
+ return self
55
+
56
+ def prob(self, hist, c):
57
+ hist = (BOS * (self.order - 1) + hist)[-(self.order - 1):] if self.order > 1 else ""
58
+ key = (hist, c)
59
+ p = self._cache.get(key)
60
+ if p is not None:
61
+ return p
62
+ p = 1.0 / (len(self.vocab) + 1)
63
+ for n in range(self.order):
64
+ h = hist[len(hist) - n:] if n else ""
65
+ entry = self.tables[n].get(h)
66
+ if entry is None:
67
+ break
68
+ d, tot, types = entry
69
+ p = (d.get(c, 0) + types * p) / (tot + types)
70
+ self._cache[key] = p
71
+ return p
72
+
73
+ def logp(self, hist, c):
74
+ if c in TRANSPARENT:
75
+ return TRANSPARENT_LOGP
76
+ return math.log(self.prob(strip_transparent(hist), c))
77
+
78
+ def perplexity(self, lines, eos=True):
79
+ lp, n = 0.0, 0
80
+ for line in lines:
81
+ line = strip_transparent(line)
82
+ for i, c in enumerate(line + (EOS if eos else "")):
83
+ lp += self.logp(line[:i], c)
84
+ n += 1
85
+ return math.exp(-lp / n)
86
+
87
+ def __getstate__(self):
88
+ d = self.__dict__.copy()
89
+ d["_cache"] = {}
90
+ return d
91
+
92
+
93
+ def load(path):
94
+ lm = CharLM.__new__(CharLM)
95
+ with open(path, "rb") as f:
96
+ lm.__dict__.update(pickle.load(f))
97
+ lm._cache = {}
98
+ return lm
99
+
100
+
101
+ def ctc_beam_search(probs, labels, lm=None, alpha=0.5, beta=0.0, beam=16, prune=1e-3, blank=0, eos=False):
102
+ """probs: (C, T) numpy array of per-frame label probabilities (softmaxed).
103
+ labels: dict label_index -> string. Returns best string."""
104
+ C, T = probs.shape
105
+ logp = [[math.log(max(float(v), 1e-30)) for v in probs[:, t]] for t in range(T)]
106
+ NEG = -1e30
107
+
108
+ def lse(a, b):
109
+ if a < b:
110
+ a, b = b, a
111
+ return a if b <= NEG else a + math.log1p(math.exp(b - a))
112
+
113
+ # beam entries: prefix -> (p_blank, p_nonblank, lm_score)
114
+ beams = {"": (0.0, NEG, 0.0)}
115
+ for t in range(T):
116
+ lp_t = logp[t]
117
+ cands = [k for k in range(C) if k != blank and probs[k, t] > prune]
118
+ nxt = defaultdict(lambda: [NEG, NEG, 0.0])
119
+ for prefix, (pb, pnb, lms) in beams.items():
120
+ total = lse(pb, pnb)
121
+ # extend with blank
122
+ e = nxt[prefix]
123
+ e[0] = lse(e[0], total + lp_t[blank]); e[2] = lms
124
+ last = prefix[-1] if prefix else None
125
+ for k in cands:
126
+ ch = labels.get(k, "")
127
+ if not ch:
128
+ continue
129
+ newp = prefix + ch
130
+ lm_inc = alpha * lm.logp(prefix, ch) + beta if lm is not None else 0.0
131
+ if ch == last or (last is not None and prefix.endswith(ch)):
132
+ # repeated label: only from blank-ending path creates a new char
133
+ e2 = nxt[newp]
134
+ e2[1] = lse(e2[1], pb + lp_t[k]); e2[2] = lms + lm_inc
135
+ e = nxt[prefix]
136
+ e[1] = lse(e[1], pnb + lp_t[k])
137
+ else:
138
+ e2 = nxt[newp]
139
+ e2[1] = lse(e2[1], total + lp_t[k]); e2[2] = lms + lm_inc
140
+ beams = dict(sorted(nxt.items(), key=lambda kv: lse(kv[1][0], kv[1][1]) + kv[1][2], reverse=True)[:beam])
141
+ # add end-of-sentence LM score
142
+ def final(kv):
143
+ pfx, (pb, pnb, lms) = kv
144
+ s = lse(pb, pnb) + lms
145
+ if lm is not None and eos:
146
+ s += alpha * lm.logp(pfx, EOS)
147
+ return s
148
+ return max(beams.items(), key=final)[0]
149
+
150
+
151
+ def main():
152
+ cmd = sys.argv[1]
153
+ if cmd == "train":
154
+ from scam_convention import is_allowed, to_scam
155
+ src, out = sys.argv[2], sys.argv[3]
156
+ order = int(sys.argv[sys.argv.index("--order") + 1]) if "--order" in sys.argv else 7
157
+ lines = []
158
+ for row in open(src, encoding="utf-8"):
159
+ t = to_scam(row.rstrip("\n").split("\t")[-1])
160
+ if is_allowed(t):
161
+ lines.append(t)
162
+ # hold out 2% for a perplexity check
163
+ dev = lines[::50]
164
+ train = [l for i, l in enumerate(lines) if i % 50]
165
+ lm = CharLM(order).fit(train)
166
+ print(f"order {order}: {len(train)} train lines, dev perplexity {lm.perplexity(dev):.2f}")
167
+ lm = CharLM(order).fit(lines)
168
+ Path(out).parent.mkdir(parents=True, exist_ok=True)
169
+ with open(out, "wb") as f:
170
+ pickle.dump(lm.__getstate__(), f)
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
scripts/metrics.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CER / SER as defined in the SCAM paper (arXiv 2606.15987, Sec. 4).
2
+
3
+ CER: total edit distance / total ground-truth length, summed over the whole set.
4
+ Primary unit is the *grapheme cluster* (a letter plus its combining marks,
5
+ e.g. "ⲙ̇" counts as one), matching the paper. Code-point CER is also given.
6
+ cer_nospace: CER with all spaces removed from both sides (secondary; see EXPERIMENTS.md).
7
+ SER: total line-level mismatches / number of lines (scriptio continua, so a
8
+ "word" error rate is not meaningful).
9
+ """
10
+ import unicodedata
11
+
12
+ from textnorm import normalize
13
+
14
+
15
+ def graphemes(s: str) -> list[str]:
16
+ out: list[str] = []
17
+ for ch in s:
18
+ if out and unicodedata.combining(ch):
19
+ out[-1] += ch
20
+ else:
21
+ out.append(ch)
22
+ return out
23
+
24
+
25
+ def edit_distance(a, b) -> int:
26
+ if len(a) < len(b):
27
+ a, b = b, a
28
+ prev = list(range(len(b) + 1))
29
+ for i, ca in enumerate(a, 1):
30
+ cur = [i]
31
+ for j, cb in enumerate(b, 1):
32
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
33
+ prev = cur
34
+ return prev[-1]
35
+
36
+
37
+ def score(pairs):
38
+ """pairs: iterable of (prediction, ground_truth). Returns dict of percentages."""
39
+ g_err = g_len = c_err = c_len = s_err = n = ns_err = ns_len = 0
40
+ for pred, gt in pairs:
41
+ pred, gt = normalize(pred), normalize(gt)
42
+ pg, gg = graphemes(pred), graphemes(gt)
43
+ g_err += edit_distance(pg, gg)
44
+ g_len += len(gg)
45
+ c_err += edit_distance(pred, gt)
46
+ c_len += len(gt)
47
+ s_err += pred != gt
48
+ n += 1
49
+ pn, gn = graphemes(pred.replace(" ", "")), graphemes(gt.replace(" ", ""))
50
+ ns_err += edit_distance(pn, gn)
51
+ ns_len += len(gn)
52
+ return {
53
+ "cer": 100 * g_err / max(g_len, 1),
54
+ "cer_codepoint": 100 * c_err / max(c_len, 1),
55
+ "ser": 100 * s_err / max(n, 1),
56
+ # secondary: spaces removed on both sides (SCAM marks visual gaps / some pages word spaces inconsistently)
57
+ "cer_nospace": 100 * ns_err / max(ns_len, 1),
58
+ "lines": n,
59
+ }
scripts/recognize.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference helpers for CRNN checkpoints (train_crnn.py) with optional char-LM decoding."""
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import torch
8
+ from PIL import Image
9
+
10
+ sys.path.insert(0, str(Path(__file__).parent))
11
+ import charlm # noqa: E402
12
+ from train_crnn import CRNN, Codec # noqa: E402
13
+
14
+ DEFAULT_LM = dict(alpha=0.35, beta=0.5, beam=12) # tuned on SCAM val for E09-family models
15
+
16
+
17
+ class Recognizer:
18
+ """ckpt may be a comma-separated list: the models' CTC probabilities are averaged
19
+ (all must share codec and input height)."""
20
+
21
+ def __init__(self, ckpt, device=None, lm_path=None, alpha=None, beta=None, beam=None):
22
+ ckpts = [c for c in str(ckpt).split(",") if c]
23
+ self.members = [_Single(c, device) for c in ckpts]
24
+ first = self.members[0]
25
+ for m in self.members[1:]:
26
+ assert m.codec.chars == first.codec.chars and m.height == first.height, "incompatible ensemble members"
27
+ self.device, self.codec, self.height = first.device, first.codec, first.height
28
+ self.lm = charlm.load(lm_path) if lm_path else None
29
+ self.alpha = DEFAULT_LM["alpha"] if alpha is None else alpha
30
+ self.beta = DEFAULT_LM["beta"] if beta is None else beta
31
+ self.beam = DEFAULT_LM["beam"] if beam is None else beam
32
+
33
+ def probs(self, images, batch=32):
34
+ outs = [m.probs(images, batch) for m in self.members]
35
+ if len(outs) == 1:
36
+ return outs[0]
37
+ return [sum(ps) / len(ps) for ps in zip(*outs)]
38
+
39
+ def decode(self, prob):
40
+ if self.lm is None:
41
+ return self.codec.decode_greedy(prob.argmax(0).tolist())
42
+ return charlm.ctc_beam_search(prob, self.codec.labels, self.lm, self.alpha, self.beta, self.beam)
43
+
44
+ def __call__(self, images):
45
+ return [self.decode(p) for p in self.probs(images)]
46
+
47
+
48
+ class _Single:
49
+ def __init__(self, ckpt, device=None):
50
+ self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
51
+ if str(ckpt).endswith(".safetensors"): # published format: weights + <name>.json (codec, args)
52
+ from safetensors.torch import load_file
53
+ ck = json.loads(Path(ckpt).with_suffix(".json").read_text(encoding="utf-8"))
54
+ ck["model"] = load_file(ckpt)
55
+ else:
56
+ ck = torch.load(ckpt, map_location="cpu", weights_only=False)
57
+ a = ck["args"]
58
+ self.codec = Codec(ck["codec"])
59
+ self.height, self.max_width = a["height"], a["max_width"]
60
+ self.model = CRNN(len(self.codec.chars) + 1, a["backbone"], pretrained=False, hidden=a["hidden"],
61
+ dropout=0.0)
62
+ self.model.load_state_dict(ck["model"])
63
+ self.model.to(self.device).eval()
64
+
65
+ def _tensor(self, im: Image.Image):
66
+ im = im.convert("L")
67
+ w, h = im.size
68
+ nw = max(16, min(self.max_width, int(round(w * self.height / h))))
69
+ im = im.resize((nw, self.height), Image.BILINEAR)
70
+ return torch.from_numpy(np.asarray(im, dtype=np.float32) / 255.0)[None]
71
+
72
+ @torch.no_grad()
73
+ def probs(self, images, batch=32):
74
+ """Returns list of (C, T) numpy probability matrices."""
75
+ out = []
76
+ for i in range(0, len(images), batch):
77
+ xs = [self._tensor(im) for im in images[i:i + batch]]
78
+ W = max(x.shape[2] for x in xs)
79
+ x = torch.ones(len(xs), 1, self.height, W)
80
+ for j, t in enumerate(xs):
81
+ x[j, :, :, : t.shape[2]] = t
82
+ with torch.autocast("cuda", dtype=torch.float16, enabled=self.device.type == "cuda"):
83
+ logits = self.model(x.to(self.device))
84
+ p = logits.float().softmax(-1).cpu()
85
+ ol = CRNN.out_lengths(torch.tensor([t.shape[2] for t in xs]))
86
+ out += [p[j, : ol[j]].T.numpy() for j in range(len(xs))]
87
+ return out
88
+
scripts/segment_pages.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Segment page images into text lines with Kraken's default BLLA model and crop them.
2
+
3
+ Crops follow prepare_scam.py: the bounding box of the line polygon, with vertical
4
+ padding as a fraction of line height, so pseudo-labelled lines look like SCAM crops.
5
+
6
+ python scripts/segment_pages.py --pages data/raw/vatlib/pages --out data/vatlib_lines
7
+ Writes <out>/<page>__<NNN>.png and <out>/segmentation.jsonl (one record per page).
8
+ """
9
+ import argparse
10
+ import json
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import torch
15
+ from PIL import Image
16
+
17
+
18
+ def column_order(boxes, page_width):
19
+ """Reading order for multi-column pages: cluster lines into columns by their
20
+ horizontal centre (split at gaps wider than 12% of the page), then read each
21
+ column top to bottom, columns left to right. Returns a list of indices."""
22
+ if not boxes:
23
+ return []
24
+ centers = sorted(range(len(boxes)), key=lambda i: (boxes[i][0] + boxes[i][2]) / 2)
25
+ cols, cur = [], [centers[0]]
26
+ for a, b in zip(centers, centers[1:]):
27
+ ca = (boxes[a][0] + boxes[a][2]) / 2
28
+ cb = (boxes[b][0] + boxes[b][2]) / 2
29
+ if cb - ca > 0.12 * page_width:
30
+ cols.append(cur)
31
+ cur = []
32
+ cur.append(b)
33
+ cols.append(cur)
34
+ cols.sort(key=lambda c: min(boxes[i][0] for i in c))
35
+ return [i for c in cols for i in sorted(c, key=lambda i: boxes[i][1])]
36
+
37
+
38
+ def fast_polygons(baselines, im_feats=None, suppl_obj=None, topline=False, raise_on_error=False, **kw):
39
+ """Replacement for kraken's slow seam-carving polygonizer: a box around the
40
+ baseline whose height comes from the distance to the nearest line above."""
41
+ out = []
42
+ others = [np.asarray(o, dtype=float) for o in (suppl_obj or []) if len(o) >= 2]
43
+ for bl in baselines:
44
+ bl = np.asarray(bl, dtype=float)
45
+ x0, x1 = bl[:, 0].min(), bl[:, 0].max()
46
+ y = float(np.median(bl[:, 1]))
47
+ dists = []
48
+ for o in others:
49
+ if o[:, 0].max() < x0 or o[:, 0].min() > x1:
50
+ continue
51
+ oy = float(np.median(o[:, 1]))
52
+ if abs(oy - y) > 3:
53
+ dists.append(abs(oy - y))
54
+ d = min(dists) if dists else 40.0
55
+ top = [(float(x), float(yy) - 0.80 * d) for x, yy in bl]
56
+ bot = [(float(x), float(yy) + 0.18 * d) for x, yy in bl[::-1]]
57
+ out.append(np.array(top + bot))
58
+ return out
59
+
60
+
61
+ def main():
62
+ ap = argparse.ArgumentParser()
63
+ ap.add_argument("--pages", required=True, nargs="+", help="dirs or image files")
64
+ ap.add_argument("--out", required=True)
65
+ ap.add_argument("--pad", type=float, default=0.12)
66
+ ap.add_argument("--max-side", type=int, default=2000)
67
+ ap.add_argument("--device", default="cuda:0")
68
+ ap.add_argument("--model", help="segmentation model (default: kraken's BLLA)")
69
+ ap.add_argument("--exact-polygons", action="store_true", help="use kraken's slow polygonizer")
70
+ args = ap.parse_args()
71
+ if not args.exact_polygons:
72
+ import kraken.lib.vgsl.spred as spred
73
+ spred.calculate_polygonal_environment = fast_polygons
74
+ args.pad = 0.0
75
+
76
+ from kraken.configs import SegmentationInferenceConfig
77
+ from kraken.tasks import SegmentationTaskModel
78
+
79
+ model = SegmentationTaskModel.load_model(args.model) if args.model else SegmentationTaskModel.load_model()
80
+ try:
81
+ model = model.to(args.device)
82
+ except Exception:
83
+ pass
84
+ cfg = SegmentationInferenceConfig(accelerator="cpu") if args.device == "cpu" else SegmentationInferenceConfig()
85
+ try:
86
+ cfg = SegmentationInferenceConfig(accelerator="gpu", device=[0]) if args.device.startswith("cuda") else cfg
87
+ except TypeError:
88
+ pass
89
+
90
+ files = []
91
+ for p in args.pages:
92
+ p = Path(p)
93
+ files += sorted(p.glob("*.jpg")) if p.is_dir() else [p]
94
+ out = Path(args.out)
95
+ out.mkdir(parents=True, exist_ok=True)
96
+ done = set()
97
+ seg_log = out / "segmentation.jsonl"
98
+ if seg_log.exists():
99
+ done = {json.loads(l)["page"] for l in open(seg_log)}
100
+ with open(seg_log, "a") as log:
101
+ for i, f in enumerate(files):
102
+ if f.stem in done:
103
+ continue
104
+ im = Image.open(f).convert("RGB")
105
+ if max(im.size) > args.max_side:
106
+ im.thumbnail((args.max_side, args.max_side))
107
+ try:
108
+ with torch.inference_mode():
109
+ seg = model.predict(im, cfg)
110
+ except Exception as e: # keep going on odd pages
111
+ print("FAIL", f.name, e, flush=True)
112
+ continue
113
+ lines = []
114
+ cand = []
115
+ for ln in seg.lines:
116
+ xs = [x for x, _ in ln.boundary]
117
+ ys = [y for _, y in ln.boundary]
118
+ h = max(ys) - min(ys)
119
+ if h < 8 or (max(xs) - min(xs)) < 2 * h:
120
+ continue # drop specks before ordering: they can bridge the column gap
121
+ cand.append((min(xs), min(ys), max(xs), max(ys), ln))
122
+ ordered = [cand[k][4] for k in column_order([c[:4] for c in cand], im.width)]
123
+ for j, ln in enumerate(ordered):
124
+ xs = [x for x, _ in ln.boundary]
125
+ ys = [y for _, y in ln.boundary]
126
+ h = max(ys) - min(ys)
127
+ if h < 8 or (max(xs) - min(xs)) < 2 * h:
128
+ continue
129
+ x0, x1 = max(0, int(min(xs) - 0.05 * h)), min(im.width, int(max(xs) + 0.05 * h))
130
+ y0, y1 = max(0, int(min(ys) - args.pad * h)), min(im.height, int(max(ys) + args.pad * h))
131
+ name = f"{f.stem.replace('.', '-')}__{j:03d}.png"
132
+ im.crop((x0, y0, x1, y1)).save(out / name)
133
+ lines.append({"file": name, "bbox": [x0, y0, x1, y1], "baseline": ln.baseline})
134
+ log.write(json.dumps({"page": f.stem, "size": im.size, "lines": lines}) + "\n")
135
+ log.flush()
136
+ if i % 20 == 0:
137
+ print(i, f.name, len(lines), flush=True)
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
scripts/textnorm.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One text normalization used everywhere (ground truth, synthetic text, predictions).
2
+
3
+ Every model is scored after the same normalization, so changing this file
4
+ changes the benchmark: bump BENCHMARK_VERSION in eval.py if you edit it.
5
+ """
6
+ import re
7
+ import unicodedata
8
+
9
+ _WS = re.compile(r"\s+")
10
+
11
+
12
+ def normalize(s: str) -> str:
13
+ s = unicodedata.normalize("NFC", s)
14
+ s = s.replace(" ", " ").replace("\t", " ")
15
+ s = _WS.sub(" ", s).strip()
16
+ return s
scripts/train_crnn.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Line recognizer: ImageNet-pretrained ResNet + BiLSTM + CTC.
2
+
3
+ python scripts/train_crnn.py --name E04_resnet_scam --train data/scam_a/train.lst \
4
+ [--synth data/synth/v1 --synth-ratio 0.5] [--init runs/X/best.pt] --steps 6000
5
+
6
+ Writes runs/<name>/{config.json, log.jsonl, best.pt, preds_val.tsv, probs_val.pkl, scores_val.json}
7
+ Validation (SCAM-A val, greedy CTC) runs every --eval-every steps; best.pt keeps the lowest val CER.
8
+ """
9
+ import argparse
10
+ import json
11
+ import math
12
+ import pickle
13
+ import random
14
+ import sys
15
+ import time
16
+ import unicodedata
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ import torchvision
24
+ from PIL import Image, ImageFilter
25
+ from torch.utils.data import DataLoader, Dataset
26
+
27
+ sys.path.insert(0, str(Path(__file__).parent))
28
+ from metrics import score # noqa: E402
29
+ from textnorm import normalize # noqa: E402
30
+
31
+ ROOT = Path(__file__).resolve().parent.parent
32
+
33
+
34
+ # ------------------------------------------------------------------ data
35
+ def gt_of(img: str) -> str:
36
+ return normalize(Path(img[: img.rfind(".")] + ".gt.txt").read_text(encoding="utf-8"))
37
+
38
+
39
+ def read_list(path):
40
+ return [l.strip() for l in open(path) if l.strip()]
41
+
42
+
43
+ class Codec:
44
+ """Code-point level codec; label 0 is the CTC blank."""
45
+
46
+ def __init__(self, chars):
47
+ self.chars = sorted(set(chars))
48
+ self.c2i = {c: i + 1 for i, c in enumerate(self.chars)}
49
+
50
+ def encode(self, s):
51
+ return [self.c2i[c] for c in s if c in self.c2i]
52
+
53
+ def decode_greedy(self, ids):
54
+ out, prev = [], 0
55
+ for i in ids:
56
+ if i != prev and i != 0:
57
+ out.append(self.chars[i - 1])
58
+ prev = i
59
+ return "".join(out)
60
+
61
+ @property
62
+ def labels(self):
63
+ return {i + 1: c for i, c in enumerate(self.chars)}
64
+
65
+
66
+ def augment_real(im: Image.Image, rng: random.Random, strength: float) -> Image.Image:
67
+ """Geometric + photometric augmentation for real manuscript lines."""
68
+ if strength <= 0:
69
+ return im
70
+ w, h = im.size
71
+ # shear / rotation / scale through an affine transform
72
+ sh = rng.uniform(-0.2, 0.2) * strength
73
+ ang = math.radians(rng.uniform(-2.5, 2.5) * strength)
74
+ sx = 1 + rng.uniform(-0.15, 0.15) * strength
75
+ sy = 1 + rng.uniform(-0.12, 0.12) * strength
76
+ a, b = sx * math.cos(ang), sx * (math.sin(ang) + sh)
77
+ c, d = -sy * math.sin(ang), sy * math.cos(ang)
78
+ det = a * d - b * c
79
+ ia, ib, ic, id_ = d / det, -b / det, -c / det, a / det
80
+ cx, cy = w / 2, h / 2
81
+ tx = cx - (ia * cx + ib * cy) + rng.uniform(-0.03, 0.03) * w * strength
82
+ ty = cy - (ic * cx + id_ * cy) + rng.uniform(-0.06, 0.06) * h * strength
83
+ fill = tuple(int(v) for v in np.median(np.asarray(im).reshape(-1, len(im.getbands())), axis=0))
84
+ im = im.transform((w, h), Image.AFFINE, (ia, ib, tx, ic, id_, ty), resample=Image.BILINEAR,
85
+ fillcolor=fill if len(fill) > 1 else fill[0])
86
+ if rng.random() < 0.3 * strength:
87
+ im = im.filter(ImageFilter.GaussianBlur(rng.uniform(0.3, 1.2)))
88
+ if rng.random() < 0.2 * strength:
89
+ k = rng.choice([ImageFilter.MinFilter(3), ImageFilter.MaxFilter(3)])
90
+ im = im.filter(k)
91
+ # random crop of a few pixels at each side (polygon crops vary)
92
+ if rng.random() < 0.5:
93
+ l = rng.randint(0, max(1, int(0.03 * w))); r = rng.randint(0, max(1, int(0.03 * w)))
94
+ t = rng.randint(0, max(1, int(0.08 * h))); bt = rng.randint(0, max(1, int(0.08 * h)))
95
+ im = im.crop((l, t, w - r, h - bt))
96
+ return im
97
+
98
+
99
+ class LineDataset(Dataset):
100
+ def __init__(self, items, height, max_width, augment=0.0, photometric=True, seed=0, showthrough=0.0):
101
+ self.items = items # list of (img_path, text)
102
+ self.height, self.max_width = height, max_width
103
+ self.augment, self.photometric = augment, photometric
104
+ self.seed = seed
105
+ self.showthrough = showthrough # probability of blending in mirrored text from another line
106
+
107
+ def _ghost(self, rng, nw):
108
+ """Ink from the other side of the leaf: another line, mirrored, blurred, faded; values in [0,1], 1 = paper."""
109
+ p, _ = self.items[rng.randrange(len(self.items))]
110
+ g = Image.open(p).convert("L").transpose(Image.FLIP_LEFT_RIGHT)
111
+ g = g.filter(ImageFilter.GaussianBlur(rng.uniform(0.5, 2.0)))
112
+ gw = max(16, int(round(g.width * self.height / g.height)))
113
+ g = g.resize((gw, self.height), Image.BILINEAR)
114
+ t = torch.from_numpy(np.asarray(g, dtype=np.float32) / 255.0)
115
+ t = (t - t.median()).clamp(max=0) + 1 # keep only ink darker than the paper
116
+ dy = rng.randint(-self.height // 3, self.height // 3)
117
+ t = torch.roll(t, dy, 0)
118
+ if gw < nw:
119
+ t = torch.cat([t] * (nw // gw + 1), 1)
120
+ x0 = rng.randint(0, t.shape[1] - nw)
121
+ return t[:, x0:x0 + nw]
122
+
123
+ def __len__(self):
124
+ return len(self.items)
125
+
126
+ def __getitem__(self, i):
127
+ path, text = self.items[i]
128
+ rng = random.Random()
129
+ im = Image.open(path).convert("L")
130
+ im = augment_real(im, rng, self.augment)
131
+ w, h = im.size
132
+ nw = max(16, min(self.max_width, int(round(w * self.height / h))))
133
+ im = im.resize((nw, self.height), Image.BILINEAR)
134
+ x = torch.from_numpy(np.asarray(im, dtype=np.float32) / 255.0)[None]
135
+ if self.showthrough > 0 and rng.random() < self.showthrough:
136
+ x = x * (1 - rng.uniform(0.25, 0.6) * (1 - self._ghost(rng, nw)))[None]
137
+ if self.augment > 0 and self.photometric:
138
+ # contrast / brightness / gamma / noise
139
+ g = math.exp(rng.uniform(-0.4, 0.4) * self.augment)
140
+ x = x.clamp(1e-4, 1) ** g
141
+ x = (x - x.mean()) * rng.uniform(0.7, 1.3) + x.mean() + rng.uniform(-0.1, 0.1) * self.augment
142
+ if rng.random() < 0.3:
143
+ x = x + torch.randn_like(x) * rng.uniform(0.01, 0.05)
144
+ if rng.random() < 0.2 * self.augment: # erase a small vertical strip
145
+ sw = rng.randint(2, max(3, nw // 25)); sx = rng.randint(0, max(0, nw - sw))
146
+ x[..., sx:sx + sw] = x.mean()
147
+ x = x.clamp(0, 1)
148
+ return x, text, path
149
+
150
+
151
+ def collate(batch):
152
+ xs, texts, paths = zip(*batch)
153
+ H = xs[0].shape[1]
154
+ W = max(x.shape[2] for x in xs)
155
+ out = torch.ones(len(xs), 1, H, W)
156
+ widths = []
157
+ for i, x in enumerate(xs):
158
+ out[i, :, :, : x.shape[2]] = x
159
+ widths.append(x.shape[2])
160
+ return out, list(texts), list(paths), torch.tensor(widths)
161
+
162
+
163
+ class MixedSampler(torch.utils.data.Sampler):
164
+ """Infinite sampler drawing from real items with prob (1-ratio) and synth with prob ratio."""
165
+
166
+ def __init__(self, n_real, n_synth, ratio, seed=0):
167
+ self.n_real, self.n_synth, self.ratio = n_real, n_synth, ratio
168
+ self.rng = random.Random(seed)
169
+
170
+ def __iter__(self):
171
+ while True:
172
+ if self.n_synth and self.rng.random() < self.ratio:
173
+ yield self.n_real + self.rng.randrange(self.n_synth)
174
+ else:
175
+ yield self.rng.randrange(self.n_real)
176
+
177
+ def __len__(self):
178
+ return 1 << 40
179
+
180
+
181
+ class ConcatItems(Dataset):
182
+ def __init__(self, real, synth):
183
+ self.real, self.synth = real, synth
184
+
185
+ def __len__(self):
186
+ return len(self.real) + (len(self.synth) if self.synth else 0)
187
+
188
+ def __getitem__(self, i):
189
+ return self.real[i] if i < len(self.real) else self.synth[i - len(self.real)]
190
+
191
+
192
+ # ------------------------------------------------------------------ model
193
+ class CRNN(nn.Module):
194
+ def __init__(self, n_classes, backbone="resnet34", pretrained=True, hidden=256, layers=2, dropout=0.2):
195
+ super().__init__()
196
+ weights = "DEFAULT" if pretrained else None
197
+ net = getattr(torchvision.models, backbone)(weights=weights)
198
+ # keep conv1..layer3; make layer3 stride (2,1) so width keeps 1/8 resolution
199
+ b0 = net.layer3[0]
200
+ bottleneck = hasattr(b0, "conv3") # resnet50+: torchvision puts the stride on conv2
201
+ (b0.conv2 if bottleneck else b0.conv1).stride = (2, 1)
202
+ b0.downsample[0].stride = (2, 1)
203
+ self.cnn = nn.Sequential(net.conv1, net.bn1, net.relu, net.maxpool, net.layer1, net.layer2, net.layer3)
204
+ last = net.layer3[-1]
205
+ ch = (last.bn3 if bottleneck else last.bn2).num_features
206
+ self.drop = nn.Dropout(dropout)
207
+ self.rnn = nn.LSTM(ch, hidden, num_layers=layers, bidirectional=True, batch_first=True, dropout=dropout)
208
+ self.fc = nn.Linear(2 * hidden, n_classes)
209
+ self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
210
+ self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))
211
+
212
+ def forward(self, x): # x: (N,1,H,W) in [0,1]
213
+ x = (x.expand(-1, 3, -1, -1) - self.mean) / self.std
214
+ f = self.cnn(x) # (N, C, H', W/8)
215
+ f = f.mean(2).transpose(1, 2) # (N, T, C)
216
+ f, _ = self.rnn(self.drop(f))
217
+ return self.fc(self.drop(f)) # (N, T, K)
218
+
219
+ @staticmethod
220
+ def out_lengths(widths):
221
+ return torch.div(widths + 7, 8, rounding_mode="floor").clamp(min=1)
222
+
223
+
224
+ # ------------------------------------------------------------------ eval
225
+ @torch.no_grad()
226
+ def evaluate(model, loader, codec, device, keep_probs=False):
227
+ model.eval()
228
+ pairs, rows, probs_out = [], [], []
229
+ for x, texts, paths, widths in loader:
230
+ with torch.autocast("cuda", dtype=torch.float16, enabled=device.type == "cuda"):
231
+ logits = model(x.to(device))
232
+ prob = logits.float().softmax(-1).cpu()
233
+ olens = CRNN.out_lengths(widths)
234
+ for i in range(len(texts)):
235
+ p = prob[i, : olens[i]]
236
+ pred = codec.decode_greedy(p.argmax(-1).tolist())
237
+ pairs.append((pred, texts[i]))
238
+ rows.append(f"{Path(paths[i]).name}\t{texts[i]}\t{pred}")
239
+ if keep_probs:
240
+ probs_out.append((paths[i], p.T.numpy())) # (C, T) like kraken
241
+ model.train()
242
+ return score(pairs), rows, probs_out
243
+
244
+
245
+ # ------------------------------------------------------------------ main
246
+ def main():
247
+ ap = argparse.ArgumentParser()
248
+ ap.add_argument("--name", required=True)
249
+ ap.add_argument("--train", default=str(ROOT / "data/scam_a/train.lst"))
250
+ ap.add_argument("--val", default=str(ROOT / "data/scam_a/val.lst"))
251
+ ap.add_argument("--synth", nargs="*", default=[], help="dirs of synthetic <id>.png/<id>.gt.txt")
252
+ ap.add_argument("--synth-ratio", type=float, default=0.0)
253
+ ap.add_argument("--init", help="checkpoint to start from (codec is merged)")
254
+ ap.add_argument("--backbone", default="resnet34")
255
+ ap.add_argument("--no-pretrained", action="store_true")
256
+ ap.add_argument("--height", type=int, default=64)
257
+ ap.add_argument("--max-width", type=int, default=1200)
258
+ ap.add_argument("--hidden", type=int, default=256)
259
+ ap.add_argument("--dropout", type=float, default=0.2)
260
+ ap.add_argument("--batch", type=int, default=24)
261
+ ap.add_argument("--steps", type=int, default=6000)
262
+ ap.add_argument("--lr", type=float, default=5e-4)
263
+ ap.add_argument("--wd", type=float, default=1e-2)
264
+ ap.add_argument("--warmup", type=int, default=300)
265
+ ap.add_argument("--augment", type=float, default=1.0)
266
+ ap.add_argument("--showthrough", type=float, default=0.0, help="prob. of simulated bleed-through on real lines")
267
+ ap.add_argument("--eval-every", type=int, default=250)
268
+ ap.add_argument("--workers", type=int, default=6)
269
+ ap.add_argument("--seed", type=int, default=0)
270
+ args = ap.parse_args()
271
+
272
+ torch.manual_seed(args.seed); random.seed(args.seed); np.random.seed(args.seed)
273
+ run = ROOT / "runs" / args.name
274
+ run.mkdir(parents=True, exist_ok=True)
275
+ (run / "config.json").write_text(json.dumps(vars(args), indent=1))
276
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
277
+
278
+ real = [(p, gt_of(p)) for p in read_list(args.train)]
279
+ synth = []
280
+ for d in args.synth:
281
+ for p in sorted(Path(d).glob("*.png")):
282
+ synth.append((str(p), gt_of(str(p))))
283
+ val = [(p, gt_of(p)) for p in read_list(args.val)]
284
+
285
+ chars = set("".join(t for _, t in real + synth))
286
+ init = None
287
+ if args.init:
288
+ init = torch.load(args.init, map_location="cpu", weights_only=False)
289
+ chars |= set(init["codec"])
290
+ codec = Codec(chars)
291
+ print(f"real {len(real)} synth {len(synth)} val {len(val)} classes {len(codec.chars)+1}", flush=True)
292
+
293
+ model = CRNN(len(codec.chars) + 1, args.backbone, not args.no_pretrained, args.hidden, dropout=args.dropout)
294
+ if init is not None:
295
+ sd = init["model"]
296
+ old = init["codec"]
297
+ # remap output layer rows to the new codec
298
+ W, b = sd.pop("fc.weight"), sd.pop("fc.bias")
299
+ model.load_state_dict(sd, strict=False)
300
+ with torch.no_grad():
301
+ model.fc.weight[0], model.fc.bias[0] = W[0], b[0]
302
+ for j, c in enumerate(old):
303
+ if c in codec.c2i:
304
+ model.fc.weight[codec.c2i[c]] = W[j + 1]
305
+ model.fc.bias[codec.c2i[c]] = b[j + 1]
306
+ model.to(device)
307
+
308
+ ds_real = LineDataset(real, args.height, args.max_width, augment=args.augment, showthrough=args.showthrough)
309
+ ds_synth = LineDataset(synth, args.height, args.max_width, augment=args.augment * 0.5) if synth else None
310
+ ds = ConcatItems(ds_real, ds_synth)
311
+ sampler = MixedSampler(len(real), len(synth), args.synth_ratio if synth else 0.0, args.seed)
312
+ dl = DataLoader(ds, batch_size=args.batch, sampler=sampler, collate_fn=collate, num_workers=args.workers,
313
+ persistent_workers=True, prefetch_factor=4)
314
+ vdl = DataLoader(LineDataset(val, args.height, args.max_width), batch_size=32, collate_fn=collate, num_workers=2)
315
+
316
+ opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd)
317
+ sched = torch.optim.lr_scheduler.LambdaLR(
318
+ opt, lambda s: min(1.0, (s + 1) / args.warmup) * 0.5 * (1 + math.cos(math.pi * min(1.0, s / args.steps))))
319
+ scaler = torch.amp.GradScaler(enabled=device.type == "cuda")
320
+ ctc = nn.CTCLoss(blank=0, zero_infinity=True)
321
+
322
+ best = (1e9, -1)
323
+ log = open(run / "log.jsonl", "a")
324
+ t0 = time.time()
325
+ it = iter(dl)
326
+ running = 0.0
327
+ for step in range(1, args.steps + 1):
328
+ x, texts, _, widths = next(it)
329
+ targets = [torch.tensor(codec.encode(t), dtype=torch.long) for t in texts]
330
+ tl = torch.tensor([len(t) for t in targets])
331
+ x = x.to(device, non_blocking=True)
332
+ with torch.autocast("cuda", dtype=torch.float16, enabled=device.type == "cuda"):
333
+ logits = model(x)
334
+ lp = logits.float().log_softmax(-1).transpose(0, 1) # (T, N, K)
335
+ ol = CRNN.out_lengths(widths).clamp(max=lp.shape[0])
336
+ loss = ctc(lp, torch.cat(targets), ol, tl)
337
+ opt.zero_grad(set_to_none=True)
338
+ scaler.scale(loss).backward()
339
+ scaler.unscale_(opt)
340
+ nn.utils.clip_grad_norm_(model.parameters(), 5.0)
341
+ scaler.step(opt); scaler.update(); sched.step()
342
+ running = 0.98 * running + 0.02 * loss.item() if step > 1 else loss.item()
343
+
344
+ if step % args.eval_every == 0 or step == args.steps:
345
+ s, rows, _ = evaluate(model, vdl, codec, device)
346
+ rec = {"step": step, "loss": round(running, 4), "lr": sched.get_last_lr()[0],
347
+ "val_cer": round(s["cer"], 2), "val_ser": round(s["ser"], 2), "min": round((time.time() - t0) / 60, 1)}
348
+ print(json.dumps(rec), flush=True)
349
+ log.write(json.dumps(rec) + "\n"); log.flush()
350
+ if s["cer"] < best[0]:
351
+ best = (s["cer"], step)
352
+ torch.save({"model": model.state_dict(), "codec": codec.chars, "args": vars(args), "step": step,
353
+ "val": s}, run / "best.pt")
354
+
355
+ # final: reload best, write predictions + probabilities for LM sweeps
356
+ ck = torch.load(run / "best.pt", map_location=device, weights_only=False)
357
+ model.load_state_dict(ck["model"])
358
+ s, rows, probs = evaluate(model, vdl, codec, device, keep_probs=True)
359
+ (run / "preds_val.tsv").write_text("image\tgt\tpred\n" + "\n".join(rows) + "\n", encoding="utf-8")
360
+ with open(run / "probs_val.pkl", "wb") as f:
361
+ pickle.dump({"labels": codec.labels, "lines": probs}, f)
362
+ s["best_step"] = best[1]
363
+ (run / "scores_val.json").write_text(json.dumps(s, indent=1))
364
+ print("BEST", json.dumps(s), flush=True)
365
+
366
+
367
+ if __name__ == "__main__":
368
+ main()
scripts/transcribe.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transcribe Coptic from a photo or scan of a page.
2
+
3
+ .venv/bin/python scripts/transcribe.py page.jpg [more.jpg ...] \
4
+ [--rec models/recognizer.pt] [--seg models/segmenter.safetensors] [--no-lm] [--overlay out.jpg]
5
+
6
+ Pipeline: baseline segmentation (Kraken BLLA, fine-tuned on SCAM pages) ->
7
+ line crops -> ResNet-CRNN recognizer -> CTC beam search with a Coptic character
8
+ LM. Prints one recognised line per text line, in reading order.
9
+ Use --lines if the input images are already single text lines.
10
+ """
11
+ import argparse
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from PIL import Image, ImageDraw, ImageOps
16
+
17
+ sys.path.insert(0, str(Path(__file__).parent))
18
+ ROOT = Path(__file__).resolve().parent.parent
19
+ DEFAULTS = {
20
+ "rec": ROOT / "models/recognizer.safetensors",
21
+ "seg": ROOT / "models/segmenter.safetensors",
22
+ "lm": ROOT / "models/coptic_char5.pkl",
23
+ }
24
+
25
+
26
+ def load_segmenter(path, device):
27
+ import segment_pages # noqa: F401 (installs the fast polygonizer patch below)
28
+ import kraken.lib.vgsl.spred as spred
29
+ from kraken.configs import SegmentationInferenceConfig
30
+ from kraken.tasks import SegmentationTaskModel
31
+
32
+ spred.calculate_polygonal_environment = segment_pages.fast_polygons
33
+ model = SegmentationTaskModel.load_model(str(path)) if path and Path(path).exists() else SegmentationTaskModel.load_model()
34
+ if device.startswith("cuda"):
35
+ cfg = SegmentationInferenceConfig(accelerator="gpu", device=[0])
36
+ else:
37
+ cfg = SegmentationInferenceConfig(accelerator="cpu")
38
+ return model, cfg
39
+
40
+
41
+ def segment(model, cfg, im, max_side=2000):
42
+ import torch
43
+ scale = 1.0
44
+ if max(im.size) > max_side:
45
+ scale = max_side / max(im.size)
46
+ im = im.resize((int(im.width * scale), int(im.height * scale)), Image.BILINEAR)
47
+ with torch.inference_mode():
48
+ seg = model.predict(im, cfg)
49
+ boxes = []
50
+ for ln in seg.lines:
51
+ xs = [x for x, _ in ln.boundary]
52
+ ys = [y for _, y in ln.boundary]
53
+ h = max(ys) - min(ys)
54
+ if h < 8 or (max(xs) - min(xs)) < 2 * h:
55
+ continue
56
+ x0, x1 = max(0, min(xs) - 0.05 * h), min(im.width, max(xs) + 0.05 * h)
57
+ y0, y1 = max(0, min(ys)), min(im.height, max(ys))
58
+ boxes.append(tuple(int(v / scale) for v in (x0, y0, x1, y1)))
59
+ from segment_pages import column_order
60
+ return [boxes[i] for i in column_order(boxes, im.width / scale)]
61
+
62
+
63
+ def main():
64
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
65
+ ap.add_argument("images", nargs="+")
66
+ ap.add_argument("--rec", default=str(DEFAULTS["rec"]))
67
+ ap.add_argument("--seg", default=str(DEFAULTS["seg"]))
68
+ ap.add_argument("--lm", default=str(DEFAULTS["lm"]))
69
+ ap.add_argument("--no-lm", action="store_true")
70
+ ap.add_argument("--lines", action="store_true", help="inputs are already single-line images")
71
+ ap.add_argument("--overlay", help="write an overlay image with line boxes (first page only)")
72
+ ap.add_argument("--device", default="cuda" if __import__("torch").cuda.is_available() else "cpu")
73
+ args = ap.parse_args()
74
+
75
+ from recognize import Recognizer
76
+ rec = Recognizer(args.rec, device=args.device, lm_path=None if args.no_lm else args.lm)
77
+ if args.lines:
78
+ ims = [ImageOps.exif_transpose(Image.open(p)) for p in args.images]
79
+ for p, t in zip(args.images, rec(ims)):
80
+ print(f"{p}\t{t}")
81
+ return
82
+ seg_model, cfg = load_segmenter(args.seg, args.device)
83
+ for n, path in enumerate(args.images):
84
+ im = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
85
+ boxes = segment(seg_model, cfg, im)
86
+ texts = rec([im.crop(b) for b in boxes]) if boxes else []
87
+ if len(args.images) > 1:
88
+ print(f"=== {path}")
89
+ for t in texts:
90
+ print(t)
91
+ if args.overlay and n == 0:
92
+ ov = im.copy()
93
+ d = ImageDraw.Draw(ov)
94
+ for i, b in enumerate(boxes):
95
+ d.rectangle(b, outline=(220, 30, 30), width=3)
96
+ d.text((b[0], b[1] - 12), str(i + 1), fill=(220, 30, 30))
97
+ ov.save(args.overlay)
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()