File size: 20,828 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Builds records/R5/TESTPASS2/plan.json (test pass 2 pre-registration) from fixed text below plus the hash and check files.
usage: tp2_make_plan.py TESTPASS2_DIR
"""
import hashlib
import json
import os
import sys
import time

TP = sys.argv[1]
H = json.load(open(os.path.join(TP, "checks", "hashes.json"), encoding="utf-8"))
O = json.load(open(os.path.join(TP, "checks", "overlap.json"), encoding="utf-8"))
TOBP = json.load(open(os.path.join(TP, "checks", "tob_prep.json"), encoding="utf-8"))
D = "/path/to/TURKIC_OCR_DATA"
C = "/path/to/TURKIC_OCR_CODE"


def fsha(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


def wl(key):
    return [{"file": os.path.basename(r["path"]), "path": r["path"], "bytes": r.get("bytes"), "sha256": r.get("sha256")} for r in H["weights"][key]]


code_sha = {r["path"]: r["sha256"] for r in H["code"]}
SETS = ["az_localdoc_test", "rukopys_test", "hkr_test1", "hkr_test2", "chd_test", "school_test", "synth_hand_test", "synth_typed_test"]
LABELS = {
    "az_localdoc_test": ("human-made", "primary",
                         "data/raw/localdoc_az_htr/README.md, sections 'How it was built' step 3 ('Each line was manually bounded ... and "
                         "transcribed') and the opening line ('A manually annotated benchmark ... annotated in Label Studio'); manifest field "
                         "text = the card's field 'text' ('Ground truth transcription')."),
    "rukopys_test": ("human-made", "primary (Ukrainian is not a target language: tests unseen Cyrillic handwriting)",
                     "data/raw/rukopys_test/README.md, Splits table: test, annotation_source 'annotator'; annotation_source table: "
                     "'annotator' = 'Labeled by Keymakr - professional human annotation service'. Raw test/metadata.jsonl field "
                     "annotation_source counted by tp2_overlap.py: 385 of 385 pages 'annotator'. Manifest rows: regions of type "
                     "handwritten, language uk, legibility legible, no ~~ or [illegible] markers (build_logs/stage_rukopys.json, field rule)."),
    "hkr_test1": ("labels from the printed template text; human verification not stated", "descriptive",
                  "HKR paper arXiv 2007.03579v2 (HTML), section 1 ('forms, which consisted of machine-typed texts, and empty lines next to "
                  "those texts'), section 3.1 ('an easy task to generate the correct labels for the printed text on the forms'), section "
                  "4.1 'Automated Labeling'; no manual check of the handwriting against its label is stated. Test1/Test2 meaning not stated "
                  "in arXiv v2 (the plan's 'unseen words' / 'seen words, other writers' is unverified). Read by a web fetch "
                  "on 25 Nov 2026 (READ-FULL of the HTML version)."),
    "hkr_test2": ("labels from the printed template text; human verification not stated", "descriptive", "as hkr_test1"),
    "chd_test": ("not stated", "descriptive",
                 "Kaggle API metadata of constantinwerner/cyrillic-handwriting-dataset (HTTP 200 on 25 Nov 2026): 'The data was collected from "
                 "open web sources and materials of members of the team'; version 5 note 'fix: transcription for an image'; who made or "
                 "checked labels not stated. The Kaggle HTML page is JavaScript only (BLOCKED for reading)."),
    "school_test": ("transcribed by the dataset team; human or model not stated", "descriptive",
                    "github.com/ai-forever/htr_datasets/tree/main/school_notebooks README: 'Затем каждое слово транскрибировалось отдельно' and "
                    "'который мы собрали и разметили'; data/raw/school_notebooks_ru/README.md 'Annotation format' (field attributes.translation) "
                    "says nothing on who transcribed."),
    "synth_hand_test": ("exact by construction (generated text rendered with held-out fonts)", "primary",
                        "pagesynth-0.3.0 renders the manifest text; frozen read-only copy (registry frozen_copy note)."),
    "synth_typed_test": ("exact by construction", "primary", "pagesynth-0.3.0 renders the manifest text; frozen read-only copy."),
}
sets = {}
for s in SETS:
    m = H["manifests"][s]
    sets[s] = {"manifest": m["path"], "manifest_sha256": m["sha256"], "matches_registry_sha256": m["sha256_matches_registry"],
               "n_rows": m["census"]["rows"], "n_groups": m["census"]["groups"], "bootstrap_group_unit": m["registry_group_unit"],
               "unit": list(m["census"]["unit"]), "kind": list(m["census"]["kind"]), "langs": m["census"]["lang"],
               "split_values": m["census"]["split"], "label_provenance": LABELS[s][0], "status": LABELS[s][1], "label_evidence": LABELS[s][2],
               "sidecar": m.get("sidecar", {}).get("path")}
plan = {
    "plan": "R5 test pass 2 (pre-registration)", "version": 1, "written_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    "author": "stage TESTPASS2",
    "purpose": ("Score the frozen final model M1 once on every locked handwriting test set it has not been scored on, plus the generated "
                "handwriting and typed tests, on CPU; read TurkishOCR-Bench pages with the two-model pipeline. Nothing is tuned on test "
                "results. Every test set is opened once (one prediction run per model and set)."),
    "pre_registration_log": [
        "Before this plan was written, no M1 or Qwen3-VL-2B output on any set below existed or was seen (the R5 task r8:paddleocr_vl_1_6:leader:rest "
        "and r8:qwen3_vl_2b:leader:rest were never started, records/R5/FINAL/close_notes.txt).",
        "M2 aggregate figures WERE seen before writing: the M2 greedy score file of az_localdoc_test (opened to learn the score-file layout) and "
        "the per-set CER/WER of preds/A1/long2x/meta_test_pass.json (kohtd_test_p2, p2b, hkr_test1, hkr_test2, chd_test, printed while reading "
        "the file). M2 is not re-run or changed, so this cannot steer M2; it is recorded so readers know it.",
        "TurkishOCR-Bench: README read; the first line of metadata.jsonl (an academic printed page: title, source and about 200 characters of its "
        "ground truth) was shown once when listing the folder. No test image was viewed. No other test label was viewed.",
        "Rule slip: one 'sed -n' was run inside ssh at about 06:00 UTC to read linedet/det_prep.py lines 160-172 and 240-250 (code, not data).",
    ],
    "models": {
        "M1": {"name": "PaddleOCR-VL 1.6 fine-tuned, R5 leader (B1, the final model)", "dir": D + "/checkpoints/r5/paddleocr_vl_1_6/leader",
               "files": wl("M1_paddleocr_vl_1_6_leader"), "run": "new, on CPU, this pass"},
        "M2": {"name": "PP-OCRv6 medium (arm A1) at checkpoint long2x; greedy CTC, and the same with the gated character LM",
               "files": wl("M2_A1_long2x") + wl("M2_char_lm"),
               "run": ("REUSED, not re-run: predictions and score files made in the 24 Nov 2026 sealed pass (step 8, line tasks ~20:41-20:46 GMT+5 "
                       "= 15:41-15:46Z; R5 final scoring job 54835, scored 16:56-16:57Z, scorer code 9d5f3205). Re-running would open these sets a "
                       "second time for M2."),
               "reused_files": "checks/hashes.json key m2_reused (sha256 of every prediction TSV, score JSON, meta.json, meta_test_pass.json; all "
                               "16 score files status 'scored', coverage complete, stored pred sha256 equal to the file on disk)",
               "lm_gated_rule": "as DATA/outputs/r5/preds/A1/long2x_lm_gated/meta.json (char6.klm, gate rule version of 23 Nov 2026); unchanged"},
        "Qwen3-VL-2B": {"name": "Qwen3-VL-2B fine-tuned, R5 leader (B2)", "dir": D + "/checkpoints/r5/qwen3_vl_2b/leader",
                        "files": wl("Q_qwen3_vl_2b_leader"), "run": "new, on CPU, only on the small sets of section qwen"},
        "detector": {"name": "YOLO11s stage 2 line detector", "files": wl("detector_yolo11s_stage2"),
                     "run": "new, on CPU, TurkishOCR-Bench pages only (no stored boxes exist for them)"},
    },
    "decoding": {
        "vlm": ("CODE/scripts/r5_vlma/eval_vlm_test.py unchanged (sha256 %s), which imports vlm_common.py (sha256 %s) and postproc.py: the model's "
                "own processor and chat template with the training instruction 'Transcribe the text in this image exactly.', one image, "
                "generation prompt on; greedy, num_beams 1, repetition_penalty 1.0, no_repeat_ngram 0; stop on generation-config eos + "
                "tokenizer eos + the trained answer-end token (r5_export.json answer_suffix_ids); max_new_tokens 48 for unit word and 192 for "
                "unit line (vlm_common.MAXNEW, the R5 caps); batch 16, left padding; weights and inputs bf16 (torch.bfloat16) on CPU, "
                "--device cpu, OMP_NUM_THREADS=16. The script also writes its cap-retry folder leader_retry (temperature 0.3, seed 20261121, "
                "only rows that hit the cap); the GREEDY folder is the reported figure.") % (
                    code_sha.get(C + "/scripts/r5_vlma/eval_vlm_test.py"), code_sha.get(C + "/scripts/r5_vlma/vlm_common.py")),
        "cpu_vs_gpu": ("The R5 figures of M1 were made on H100 in bf16; these are CPU bf16. The smoke test measures agreement of CPU and GPU outputs "
                       "on validation rows and the result is reported with the figures."),
        "m2": "reused; greedy CTC (argmax per frame) and gated LM decoding exactly as made on 24 Nov",
        "deadline": "--deadline-utc 2026-11-27T00:00:00Z (so the script's 24 Nov default cannot stop batches); a task not started by "
                    "2026-11-26T06:00:00Z is 'not run'. A set counts only when complete (the script writes <set>.tsv only then).",
    },
    "sets": sets,
    "sets_not_run": {
        "kz_benchmark (Omar-2002/kz_benchmark_data, 150 handwritten pages)": (
            "not on the cluster: find over DATA and CODE (maxdepth 7) for *omar*, *kz_benchmark*, *kzbench* returned nothing on 25 Nov 2026; "
            "the plan forbids a new download without listing it first, so it is listed for approval and not run. Its references are "
            "model-drafted per the findings page (CL-30), so it would be descriptive only."),
        "TurkishOCR-Bench categories tablo, formul, slayt, fis_fatura_form": (
            "not read: tables and LaTeX need their own normalisation; the receipt/invoice pages are probably rendered, not photographed "
            "(findings N7 record); 205 pages."),
    },
    "pages": {
        "sets": {"tob_hand": {"pages": TOBP["hand_pages"], "documents": TOBP["documents_per_category"]["el_yazisi"], "status": "primary",
                              "list": D + "/outputs/r5/testpass2/tob/pages_hand.tsv",
                              "list_sha256": "057daeb6a0474c523b5327f105225f5e8bbdf987940ca071f9c2a1409510ee3a"},
                 "tob_print_text_categories": {"pages": TOBP["print_pages"], "categories": {k: v for k, v in TOBP["pages_per_category"].items()
                                                                                          if k != "el_yazisi"},
                                               "status": "descriptive, reported separately and per category",
                                               "list": D + "/outputs/r5/testpass2/tob/pages_print.tsv",
                                               "list_sha256": "04f17a98b285941004eacf45c166ad4d6385e31d2a6ecfef5b91887c81c198a1"}},
        "source": D + "/data/raw/turkishocr_bench (moganai/TurkishOCR-Bench), metadata.jsonl sha256 " + H["tob_metadata"]["sha256"],
        "label_provenance": ("human-checked: github.com/moganai/TurkishOCR-Bench PUANLAMA.md section 8 'Doğru metin ve bilinen sınırlar': drafts by 4 "
                             "models merged by an LLM judge, line check against PDF text layer and Vision boxes, 'Üç ayrı kişi kelime kelime kontrol "
                             "etti' (three people checked word by word), 86 spots re-examined, 39 corrected. No separate note for the handwritten "
                             "pages. Same section warns the draft models may keep a small advantage on their own pages (not our models)."),
        "licence": "per page; the 50 handwritten pages state no licence (README); research-only, non-commercial use, evaluation only",
        "pipeline": ("tp2_tob_prep.py: the page as a viewer shows it (EXIF orientation applied: all 283 pages have orientation 1; alpha flattened "
                     "on white), resized to a long side of 1280 px as linedet.det_prep does for School Notebooks pages (cv2 INTER_AREA when "
                     "shrinking, INTER_LINEAR when enlarging), JPEG q95. tp2_tob_detect.py: YOLO11s stage 2 on CPU, imgsz 1280, conf 0.25, iou "
                     "0.6, max_det 300 (det_eval settings). tp2_tob_read.py (copy of the reading part of records/R5/PAGECHK/detb1_page_check.py): "
                     "reading order (centre_y // 15, centre_x) in the 1280 px page, margins x 1% + 2 px, y 10% + 1 px, crops from the full-"
                     "resolution page, M1 with the decoding above (unit line, cap 192), output NFC with whitespace collapsed, empty outputs dropped."),
        "reference": ("tp2_tob_img.tob_ref_lines on dogru_metin/<cat>/<id>.md: NFC; HTML comments removed; </td> </th> to a space; </tr> and <br> to "
                      "a line break; tags header, footer, figure, table, thead, tbody, tfoot, tr, td, th, br, sup, sub, span, div, p, b, i, u, em, "
                      "strong, img, caption, colgroup, col removed with their text kept (header and footer text is kept: the pipeline reads it); per "
                      "line a leading Markdown heading marker and the ** and __ emphasis markers removed; whitespace collapsed; empty lines dropped; "
                      "LaTeX and everything else kept. Unit-tested on a made-up string before this plan."),
        "metric": ("linedet.det_eval.page_cers imported unchanged: M28 reading-order page CER (lines joined by one space) and M29 order-free page "
                   "CER (one-to-one line matching by minimum edit distance, unmatched lines charged in full). Micro over pages. Primary: case-"
                   "sensitive M28. Secondary: M29; both with the Turkish case fold (textnorm.fold_lower, lang tr), because the benchmark's own "
                   "handwriting rule ignores case. Invented text: output characters per reference character; pages with no output line."),
        "caveats": ("M29 is weak here: reference lines are logical lines (words hyphenated at line ends joined, paragraphs on one line), not "
                    "physical lines, so one-to-one line matching charges correct text; read M28 first. Multi-column printed pages are read in "
                    "row order across columns (centre_y // 15), which costs M28. The detector was trained on generated pages and School Notebooks only."),
        "interval": "95% percentile bootstrap over source documents (metadata field belge), B 10000, seed 20261121 (r5eval.stats.boot_matmul, ratio_ci)",
    },
    "scoring": {
        "crops": ("CODE/scripts/r5eval/score.py unchanged (sha256 %s), r5eval code sha256 %s (equal to the 24 Nov attested 9d5f3205...), run once per "
                  "prediction root with --test-pass and the test pass 2 gate file, B 10000, seed 20261121, K_train default. Reported figure: "
                  "profile 'plain' (N0: NFC, whitespace runs to one space, strip; case, punctuation and look-alikes kept; amendment 3.2 C10 "
                  "decision figure).") % (code_sha.get(C + "/scripts/r5eval/score.py"), H["r5eval_code_sha256"]),
        "reported": ["n", "CER with 95% interval", "WER", "exact-match rate", "case-folded CER (secondary)",
                     "invented text: HR3 (overlong or garbage outputs, references of 5+ characters), HR4 (repetition loops), fabricated-word rate "
                     "(output words near no reference word), empty-output rate", "hit-cap rows"],
        "interval": ("95% percentile cluster bootstrap of the scorer over the manifest column 'group'; the unit per set is in sets.<name>."
                     "bootstrap_group_unit (KOHTD-style forms do not apply here: page for RUKOPYS and az_localdoc, notebook page for School, "
                     "HKR template and form instance, CHD word type (no writer id exists), composed page / source document for the synthetic sets). "
                     "Single seed per model: the interval is over data, not training seeds."),
        "secondary": [
            "M1 minus M2 greedy CER, paired cluster bootstrap (r5eval.stats.paired_ratio_difference), descriptive, no decision attached",
            "sensitivity: CER without the test rows that have a training partner in the report-only duplicate check of 21 Nov "
            "(build_logs/dedupe_all_dropped.tsv; counts in checks.json), recomputed from the prediction TSVs with the scorer's N0 text and edit distance",
        ],
        "results_code": "tp2_results.py, tp2_page_score.py, tp2_score_all.py (sha256 in checks/hashes.json and the copy of this plan)",
    },
    "qwen": {"sets_always": ["az_localdoc_test", "chd_test"], "sets_conditional": ["hkr_test1", "hkr_test2"],
             "rule": ("hkr_test1 and hkr_test2 are run only if the smoke test's Qwen seconds per word row on hkr_val_s2000 (CPU, wall seconds of the "
                      "set / rows) times 5,043 is at most 28,800 s (8 h for one 16-CPU task). Decided from validation timing only."),
             "order": "after all M1 tasks and page tasks in the same array (throttle 6)"},
    "running": ("ZEN4 array tp2_test.sbatch, 16 CPUs and 64 GB per task, at most 6 tasks at once (%6), one set per task, each task its own "
                "prediction root DATA/outputs/r5/testpass2/preds/<model>_<set> (no shared meta.json). A failed task is rerun alone with the same "
                "settings (raw.jsonl resumes) and logged in jobs.json. Smoke test first, on 20 rows of hkr_val_s2000 and synth_hand_val "
                "(validation) with the identical command, plus the detector, page reader and page scorer on 2 generated validation pages."),
    "gate": ("DATA/outputs/r5/testpass2/GATE_testpass2_started.txt is created only after this plan (and any amendment) is copied to "
             "DATA/outputs/r5/testpass2/plan.json with plan.json.sha256; the gate file records the plan sha256. Every test script refuses to run "
             "without it."),
    "checks_done_before_plan": {
        "overlap_ids_paths": ("no test id or image path of the 8 crop sets appears in any frozen_mix_v1 manifest or in the 6,000,000-row training "
                              "sequence seq/mix_v1_seq.tsv (%d unique ids); no training row mentions rukopys or turkishocr") % O["training_sequence"]["unique_ids"],
        "duplicate_check_partners": {s: len(O["dedupe_all_test_rows_with_a_training_partner"][s]) for s in SETS},
        "rukopys_contamination": ("no evidence: only the test split was downloaded (data/raw/rukopys_test, j05_noise_sources.py tree_path 'test'); "
                                  "clutter crops come from pagesynth-0.3.0 (manifest column source), whose package code reads no image file "
                                  "(only cv2.imencode in geometry.py); assets are fonts and Natural Earth map data; paper.py was 'calibrated against "
                                  "RUKOPYS reference photos (viewed, not copied)'; the J05 composited noise set that planned RUKOPYS crops was never "
                                  "built (no output folder); RUKOPYS test was in the sha256/pHash duplicate check with 0 training partners. Residual "
                                  "unknowns: paper style calibrated by viewing RUKOPYS photos (design-level influence); the public pretraining data "
                                  "of the PaddleOCR-VL 1.6 and Qwen3-VL base models are not known."),
        "tob_overlap": ("print_real_train has 340 rows from 1 DergiPark source; no TurkishOCR-Bench document number occurs in print_real_train "
                        "source or group values; the handwritten pages are photos of lecture notes not in any training manifest"),
    },
    "not_done": ["no tuning of any kind on test results", "no test label is printed beyond aggregates (at most 3 example rows per set)",
                 "other users' and other sessions' jobs (aerial_*, c03v_*, om_*, rc1_*, onemodel_run) are not touched"],
    "amendments": [],
}
out = os.path.join(TP, "plan.json")
json.dump(plan, open(out, "w", encoding="utf-8"), indent=1, ensure_ascii=False)
print("written", out, fsha(out))