diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..7708d8fc91905b2d65be792ed836ad18483a5188 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +results/figures/fig1_overview.png filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6d4d805fbfd2aabee0c977ab169d0fc974121a2c --- /dev/null +++ b/.gitignore @@ -0,0 +1,36 @@ +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +.venv*/ +.pytest_cache/ +.ruff_cache/ + +# data, fonts, weights and run outputs at the top level (never committed) +/data/ +/outputs/ +/out/ +/models/ +/checkpoints/ +/logs/ +/hf_cache/ +/tmp/ +src/pagesynth/assets/fonts/ +*.pt +*.pth +*.ckpt +*.safetensors +*.onnx +*.arpa +*.klm +*.parquet +*.zip +*.7z +*.tar +*.tgz +*.tar.gz + +# editors and systems +.DS_Store +.idea/ +.vscode/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..b6b3611f4bfb91bc3ba1d3a7fae5350debf22b85 --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ +PYTHON ?= python3.12 +VENV ?= .venv +PY = $(VENV)/bin/python +SAMPLE_OUT ?= outputs/sample_eval + +.PHONY: setup test lint sample-eval + +setup: + $(PYTHON) -m venv $(VENV) + $(PY) -m pip install -r requirements.txt + +test: + $(PY) -m pytest + +lint: + $(PY) -m ruff check tests + +sample-eval: + $(PY) scripts/r5eval/score.py --preds tests/data/sample_eval/preds --registry tests/data/sample_eval/evalsets.json \ + --out $(SAMPLE_OUT) --B 1000 --settle 0 --force + @grep -o '"plain":{"groups":{"all":{"n_items":[0-9]*,"n_clusters":[0-9]*,"metrics":{"cer":{[^}]*}' \ + $(SAMPLE_OUT)/demo/final/sample_lines.json diff --git a/NOTICE b/NOTICE index ce272389ec6d52983bad53cff3bf2bd1273e8acc..7b79c8c9d82f61e2478745430942f3dfbb29ea3d 100644 --- a/NOTICE +++ b/NOTICE @@ -1,9 +1,9 @@ -Turkic OCR: code of the generator, training and evaluation (release candidate rc1_code) +Turkic OCR: code of the generator, training and evaluation -Copyright 2026 Anuar Suleimenov, Zhalgasbek Bolatov, Aidana Baglanova, Ainur Zhumabay, Anel Kadirbekova +Copyright 2026 the authors of the project report -Cite as: Suleimenov, A., Bolatov, Z., Baglanova, A., Zhumabay, A., Kadirbekova, A. (2026). A Handwriting Recognition -Model for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev University. +Cite as: A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev +University, 2026. LICENCES @@ -49,7 +49,7 @@ THIRD-PARTY SOFTWARE NOT INCLUDED The code imports third-party packages (PyTorch, Hugging Face Transformers, kraken, Ultralytics, KenLM, PaddleOCR and others) that are installed separately under their own licences; the environments/ folder lists the versions used. -The PP-OCRv3 reference re-run (scripts/r5_ref, arm R2) expects PaddleOCR release v2.10.0 +The PP-OCRv3 reference re-run (scripts/r5_ref) expects PaddleOCR release v2.10.0 (7 March 2025) of https://github.com/PaddlePaddle/PaddleOCR (Apache-2.0) in the folder under src/ref/ that scripts/r5_ref/ref_common.py sets (PPOCR_ROOT); it is not included. diff --git a/README b/README deleted file mode 100644 index 173447fcf8fe92a4f17523c553a26a860145d632..0000000000000000000000000000000000000000 --- a/README +++ /dev/null @@ -1,224 +0,0 @@ -TURKIC OCR: CODE OF THE GENERATOR, TRAINING AND EVALUATION -(release candidate rc1_code) - -This package holds the code behind the project report - - Suleimenov, A., Bolatov, Z., Baglanova, A., Zhumabay, A., Kadirbekova, A. (2026). A Handwriting Recognition Model - for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev University. - - @techreport{suleimenov2026turkic, - author = {Suleimenov, Anuar and Bolatov, Zhalgasbek and Baglanova, Aidana and Zhumabay, Ainur and Kadirbekova, Anel}, - title = {A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script}, - institution = {Nazarbayev University}, - type = {Project report}, - year = {2026} - } - -It contains the page and line generator (pagesynth 0.3.0) with its text filters, the builders of the real-data -manifests and of the training mix, the training code of the vision-language readers and of the CTC line recognizers, -the training and inference code of the line detector, the scorer with its bootstrap intervals and selection rules, the -test-pass and page-scoring scripts, the inference scripts of the release packages, and the code of the planned RQ2 -augmentation study. "The paper" below means the report cited above; section numbers refer to it (S1 to S11 are the -sections of its supplementary material). Comments in the code name the project's work stages in capitals (for example -GEN for the generator, DATA for the real-data manifests, PRINT, FREEZE, LINEDET, REF, VLMA, VLMB, EVALCODE) and use the -round name R5 for the run that produced the paper's results. - - -1. WHAT IS NOT IN THIS PACKAGE - -- No data. None of the real datasets is included, and neither are the project's generated data, manifests, splits or - predictions. Where to obtain the real datasets is listed in part 6. The generated data are released separately under - CC BY-SA 4.0. -- No reader weights. The fine-tuned weights of the three readers (PaddleOCR-VL-1.6, the final model; Qwen3-VL-2B; and - the PP-OCRv6-medium line recognizer with its character language model) are not released. They were trained on KOHTD - and HKR, whose terms limit use to the applicant's group and to academic research, and their authors have not given - permission to share models trained on them. The code here lets others train their own readers from the released - generated data and the real datasets obtained from their sources. -- The line detector's weights are released separately, with this code path, under AGPL-3.0. -- No font files. The generator needs the 73 fonts listed in src/pagesynth/assets/fonts_manifest.tsv (file name, - licence class, and whether the font is held out of training). Place them in src/pagesynth/assets/fonts/ or - point the environment variable PAGESYNTH_FONTS to their folder. Eight of them are personal-use fonts (licence class - personal_use_only); they may not be redistributed, and the released generated data contain no item drawn with them. -- Not included: the vendored PaddleOCR source used only by the PP-OCRv3 reference re-run (see NOTICE), earlier - generator versions (0.1 and 0.2.0; the text filters of 0.2.0 are identical to those of 0.3.0), staging and test copies of - scripts, one-off probes, the corrector pilot (never trained), the unfinished full-schedule PP-OCRv3 re-run, and the - download and extraction scripts of KOHTD, which need access credentials from its authors. -- config_r5eval/sota_checklist.json is not included. scripts/r5_select_verdict.sbatch passes it to - scripts/r5eval/verdict.py; remove that argument (verdict.py runs without it) or supply your own checklist. - - -2. LICENCES - -Apache-2.0 (LICENSE) for everything except: the line detector's training and inference path and the page pipeline, -which are AGPL-3.0 (LICENSE.AGPL-3.0; the files are listed in NOTICE); the vendored HTR-Flor copy in -src/ref/ (repository state of 23 June 2021; MIT, its own LICENSE); and the Natural Earth map files in -src/pagesynth/assets/naturalearth/ (public domain). Copyright and third-party notices are in NOTICE. - - -3. SETTING UP - -3.1 Paths. The code ran on a Slurm cluster with one code folder and one data folder. Every absolute path in the -package now starts with a placeholder: - - /path/to/TURKIC_OCR_CODE the folder that holds this package (src/, scripts/, ... and the virtual environments) - /path/to/TURKIC_OCR_DATA the data folder, with data/raw, data/processed, outputs, checkpoints, logs, hf_cache, tmp - -Replace both with your own folders before running anything, for example: - - grep -rlF /path/to/TURKIC_OCR_CODE . | xargs sed -i 's#/path/to/TURKIC_OCR_CODE#/home/me/turkic_ocr#g' - grep -rlF /path/to/TURKIC_OCR_DATA . | xargs sed -i 's#/path/to/TURKIC_OCR_DATA#/data/turkic_ocr#g' - -Neither placeholder is a prefix of the other, so the order does not matter. The Slurm headers name -the partitions (H100, ZEN4) and quality-of-service names of the original cluster; adapt them to yours. Many scripts -and comments refer to the project's working records (paths that begin with records/, or files under the data folder -such as manifests and score files); these records are not part of this package. - -3.2 Python environments. The scripts call the interpreter of a project environment, for example -/path/to/TURKIC_OCR_CODE/.venv_gen/bin/python. The folder environments/ holds the exact package list of each -environment, made with 'uv pip freeze'. To rebuild one: - - uv venv --python 3.12 /path/to/TURKIC_OCR_CODE/.venv_gen - uv pip install --python /path/to/TURKIC_OCR_CODE/.venv_gen/bin/python -r environments/venv_gen.requirements - -PyTorch builds with a +cu suffix in the lists come from the PyTorch package index (add ---extra-index-url https://download.pytorch.org/whl/, the tag matching the suffix). - - environment (file) Python main use - .venv (venv.requirements) 3.12 real-data manifests (scripts/r5), KOHTD split and leak checks, zero-shot screen - .venv_gen (venv_gen.requirements) 3.12 generator, training-mix freeze, release data build - .venv_kraken 3.12 CTC line recognizers, letter model, detector, scorer jobs, test pass 2, RQ2 - .venv_vlm 3.12 vision-language training and evaluation (scripts/r5_vlma), single page model, - loop guard, page check, showcase - .venv_vlm_ (9 files) 3.12 * one per extra candidate in scripts/r5_vlmb (* unlimited_ocr_2: 3.10) - .venv_print 3.12 real printed lines (scripts/r5_print) - .venv_ref_tf 3.11 HTR-Flor reference re-run (R1) - .venv_ref_paddle, .venv_ref_paddle_cpu 3.11 PP-OCRv3 reference re-run (R2) - .venv_dl see file download tools (Kazakh web benchmark) - -The exact Python version of each environment is in its file's first line. Each shell and sbatch file names the -environment its step used. The release packages in release/ carry their own requirements.txt. - - -4. FOLDERS AND WHERE THEY APPEAR IN THE PAPER - -src/pagesynth/ Page and line generator 0.3.0: text cleaning and filters (text.py, langtext.py, - textbuild.py, vocab.py), fonts and the glyph gate, the simulated writer, layouts, paper, - marks, maps, capture, cropping; produce_r5.py and scripts/ run the text build, the text - split by source document and the production. Paper: Section 2.2, S2. -src/linedet/ CTC line recognizers (PP-OCRv6 medium and small, CRNN, HTR-VT-style model), training - driver, prediction, the character 6-gram letter model with beam search and its gate, and - (det_*.py, AGPL-3.0) the YOLO11s line detector: data preparation, training, evaluation. - Paper: Sections 3.4 and 3.5, S6, S9, S10. -src/r5eval/, scripts/r5eval/ Scorer: text normalisation, CER and WER, look-alike repair, form-level bootstrap, -config_r5eval/, tests_r5eval/ Holm correction, selection of leaders and of the final model, decision rules, report - cards; with its configuration and tests. Paper: Section 4, S7. -scripts/r5_score.sbatch and Scoring, selection, verdict, learning-curve and self-test jobs of the scorer. - the other scripts/r5_*.sbatch Paper: Section 4, S7. -scripts/r5_gate/ Gate files that kept the test sets sealed until the single test pass. Paper: Section 4, S7. -scripts/r5/ Real-data manifests (KOHTD, HKR, Cyrillic Handwriting Dataset, School Notebooks, RUKOPYS, - LocalDoc), de-duplication against held-out images, the registry of training, validation - and test sets, validation subsets and the unseen-word slice. Paper: Section 2.1, S1, S4, S7. -scripts/k1_labels_all.py, KOHTD split by exam form (a salted deterministic function of the form number). Paper: Section 2.1, S4. - scripts/k1_build_split.py -scripts/kohtd_leak_* Checks that no KOHTD training crop without a form number is a copy of a validation or - test crop. Paper: S4. -scripts/r5_print/ Real printed lines: candidate PDFs from FinePDFs, text-layer check, line cutting, pixel - checks, split by document. Paper: Section 2.1, S3. -scripts/r5_freeze/ Freeze of the training mix (shares, de-duplication against held-out sets, sample - sequences). Paper: Section 2.3, S2. -scripts/j2/ Zero-shot screen of released document models on KOHTD validation words. Paper: Section 3.2. -scripts/r5_vlma/ Fine-tuning and evaluation of the vision-language readers (shared recipe, short and long - runs, slot runners), preference post-training (DPO, GRPO), and the sealed test pass. - Paper: Sections 3.2, 3.3 and 4, S5, S6, S7. -scripts/r5_vlmb/ Adapters, environments and runner for the extra vision-language candidates. Paper: S5, S6. -scripts/r5_linedet/ Jobs of the line recognizers, the detector and the letter model. Paper: Sections 3.4, 3.5, S6. -scripts/r5_ref/, src/ref/ Reference re-runs: HTR-Flor (R1, vendored copy in src/ref/) and PP-OCRv3 (R2, PaddleOCR - not included). Paper: Section 5, S10. -scripts/r5_testpass2/ Second test pass and its amendments: real handwriting and print tests, page tests - (TurkishOCR-Bench, Kazakh web benchmark), label-free re-reading of the line recognizer, - per-language tables, error analysis. Paper: Section 5, S7, S8, S9. -scripts/tp2_proposal_metrics.py Measures for the research questions. Paper: Section 6.1, S8. -scripts/r5_erran/ Error analysis of validation outputs (label errors, ambiguous handwriting). Paper: S7. -scripts/b1_page_check/ Page check: the final model on whole pages, alone and after the detector. Paper: S9. -scripts/r5_onemodel/ Single page model: page records, training, page scoring. Paper: S6, S9. -scripts/r5_loopguard/ Loop guard for the single page model. Paper: S9, S10. -scripts/r5_showcase/ Showcase pages: the generator stages of chosen validation pages (material for Figure 2) - and pages read by the pipeline. Paper: Section 2.2, S11. -scripts/r5_release/ Checks of the first release candidate, including the batching diagnostic of the line - recognizer. Paper: S7 (the batching leak). -scripts/release2/ Release build: data package, Parquet shards, regeneration check of every released page, - Sakha-text check, cards and file verification; rel2_d5_* (AGPL-3.0) retrain and check the - released detector without the personal-use-font pages. Paper: S11. -release/ Inference scripts and requirements of the release packages: the three readers (whose - weights are not released), the line detector and the page pipeline (AGPL-3.0). Paper: S11. -src/rq2/, scripts/r5_rq2/, RQ2 augmentation study (line height 32 or 64 px crossed with a typical or a diacritic-safe -src/lettersynth/ augmentation policy) and its pixel probe; src/lettersynth holds only the letter-sheet - reader that the probe uses. This code was written after the paper's results; the paper - states that the study was not run, and no RQ2 result is part of it. -environments/ Package lists of the Python environments (part 3.2). - - -5. KNOWN ISSUES - -- Content pins. Some files pin the exact content of other files as it was on the cluster, and a few check it at start. - Making the paths configurable changed some pinned files, so those pins no longer match (the list of affected pins - is in part 7). Update the pinned values after configuring the paths, or skip the check. -- release/turkic-ocr-ppocrv6-medium/infer.py is the inference script of the withheld PP-OCRv6 package. Its docstring - was written before the corrections the paper reports in S7 (the batching leak) and was not updated; the paper's - figures supersede the ones it quotes. -- The generator reproduces the content of a page from its seed but not every byte (paper, S11). -- The scripts were written for one cluster and one run of the project: many take their inputs from fixed paths and - write records of that run. They document what was done; running them elsewhere needs the data, the paths and the - job headers set up as described in part 3. - - -6. REAL DATASETS: NOT INCLUDED, WHERE TO OBTAIN THEM - - KOHTD (Kazakh handwriting) https://github.com/abdoelsayed2016/KOHTD (the authors' application form) - HKR (Kazakh and Russian) https://github.com/abdoelsayed2016/HKR_Dataset (the authors' application form) - School Notebooks RU https://huggingface.co/datasets/ai-forever/school_notebooks_RU - Cyrillic Handwriting Dataset https://www.kaggle.com/datasets/constantinwerner/cyrillic-handwriting-dataset - Azerbaijani Handwritten OCR - Benchmark (LocalDoc) https://huggingface.co/datasets/LocalDoc/azerbaijani-htr-benchmark - TurkishOCR-Bench https://huggingface.co/datasets/moganai/TurkishOCR-Bench - RUKOPYS (Ukrainian) https://huggingface.co/datasets/UkrainianCatholicUniversity/rukopys - FinePDFs (real printed lines) https://huggingface.co/datasets/HuggingFaceFW/finepdfs - FineWeb-2 (generator text) https://huggingface.co/datasets/HuggingFaceFW/fineweb-2 - Wikipedia (generator text) https://huggingface.co/datasets/wikimedia/wikipedia (snapshot 20231101) - PP-OCRv6 medium base weights https://doi.org/10.5281/zenodo.21788410 - -Each dataset keeps its own licence and terms. Three further sources are read by the code but are not in the paper's -reference list; their identifiers are taken from the code: - Kazakh web benchmark Hugging Face dataset Omar-2002/kz_benchmark_data (scripts/r5_testpass2/tp2_kzb_fetch.py) - Sakha newspaper corpus Hugging Face dataset ailabykt/sakha-corpus-mono (generator text for Sakha) - Kazakh handwritten letter sheets https://github.com/Nuray-Sheriyeva/Kazakh_Handwritten_Letter_Dataset (dataset_split_v2; - read by the RQ2 pixel probe) - - -7. EDITS MADE FOR THE PACKAGE, AND CONTENT PINS - -The package was made from the project's files by these edits only: absolute paths were replaced by the placeholders of -part 3.1; comments and descriptive strings were reworded; the folder scripts/r5_gate was renamed; two output fields -were renamed (endpoints_confirmed in the verdict written by scripts/r5eval/verdict.py, added_beyond_plan in the set -registry written by scripts/r5/r5_registry.py); one verdict text of scripts/r5_freeze/dedupe_verdict.py now reads -"NEEDS MANUAL REVIEW"; and scripts/r5_testpass2/tp2_make_plan.py no longer records the fingerprint of a planning note. - -Two pins that the code checks at run time were updated to the shipped files, so they match: - src/r5eval/cards.py (label-rule pin) the content of config_r5eval/r5_descriptive_labels.txt (reworded first line), - checked by scripts/r5eval/report_cards.py. - src/r5eval/frozen.py (frozen-file pin) the content of src/r5eval/frozen/postproc_vlma.py (one reworded docstring line; - scripts/r5_vlma/postproc.py and scripts/r5_vlmb/postproc.py are identical - copies), checked whenever the scorer is imported. - -Four pins refer to a file that these edits changed and were left as they were: - - src/rq2/geom.py pins src/linedet/common.py (paths). Checked at start: the RQ2 wrappers stop - with "REFUSED". After configuring the paths, put the new fingerprint of - src/linedet/common.py into PINNED in src/rq2/geom.py. The same table pins - four kraken files of the installed kraken package and three data files. - scripts/r5_vlma/make_vlmb_testpass.py pins scripts/r5_vlmb/vlmb_eval_vlm.py (a reworded comment); it is the one-time - builder of scripts/r5_vlmb/vlmb_eval_vlm_testpass.py, which also quotes that - fingerprint in a comment. - scripts/r5_vlma/testpass_config.json quotes the fingerprint of scripts/r5_linedet/test_pass_commands.sh (paths) in a note. - -All other pins inside the package still match. diff --git a/README.md b/README.md index 09b715c52ab1afe357271bcee3b89df724d928e0..7497b3cba4e176b6d5cbc5daaff57285151d57c1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ --- -# Licence: Apache-2.0 for the package, except the line detector's training and inference path and the page -# pipeline, which are AGPL-3.0 (LICENSE.AGPL-3.0; the files are listed in NOTICE); see also README part 2. +# Apache-2.0 for the package, except the line detector's training and inference path and the page pipeline, +# which are AGPL-3.0 (LICENSE.AGPL-3.0; the files are listed in NOTICE). license: apache-2.0 language: - kk @@ -25,227 +25,195 @@ tags: - latin-script --- -TURKIC OCR: CODE OF THE GENERATOR, TRAINING AND EVALUATION -(release candidate rc1_code) - -This package holds the code behind the project report - - Suleimenov, A., Bolatov, Z., Baglanova, A., Zhumabay, A., Kadirbekova, A. (2026). A Handwriting Recognition Model - for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev University. - - @techreport{suleimenov2026turkic, - author = {Suleimenov, Anuar and Bolatov, Zhalgasbek and Baglanova, Aidana and Zhumabay, Ainur and Kadirbekova, Anel}, - title = {A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script}, - institution = {Nazarbayev University}, - type = {Project report}, - year = {2026} - } - -It contains the page and line generator (pagesynth 0.3.0) with its text filters, the builders of the real-data -manifests and of the training mix, the training code of the vision-language readers and of the CTC line recognizers, -the training and inference code of the line detector, the scorer with its bootstrap intervals and selection rules, the -test-pass and page-scoring scripts, the inference scripts of the release packages, and the code of the planned RQ2 -augmentation study. "The paper" below means the report cited above; section numbers refer to it (S1 to S11 are the -sections of its supplementary material). Comments in the code name the project's work stages in capitals (for example -GEN for the generator, DATA for the real-data manifests, PRINT, FREEZE, LINEDET, REF, VLMA, VLMB, EVALCODE) and use the -round name R5 for the run that produced the paper's results. - - -1. WHAT IS NOT IN THIS PACKAGE - -- No data. None of the real datasets is included, and neither are the project's generated data, manifests, splits or - predictions. Where to obtain the real datasets is listed in part 6. The generated data are released separately under - CC BY-SA 4.0. -- No reader weights. The fine-tuned weights of the three readers (PaddleOCR-VL-1.6, the final model; Qwen3-VL-2B; and - the PP-OCRv6-medium line recognizer with its character language model) are not released. They were trained on KOHTD - and HKR, whose terms limit use to the applicant's group and to academic research, and their authors have not given - permission to share models trained on them. The code here lets others train their own readers from the released - generated data and the real datasets obtained from their sources. -- The line detector's weights are released separately, with this code path, under AGPL-3.0. -- No font files. The generator needs the 73 fonts listed in src/pagesynth/assets/fonts_manifest.tsv (file name, - licence class, and whether the font is held out of training). Place them in src/pagesynth/assets/fonts/ or - point the environment variable PAGESYNTH_FONTS to their folder. Eight of them are personal-use fonts (licence class - personal_use_only); they may not be redistributed, and the released generated data contain no item drawn with them. -- Not included: the vendored PaddleOCR source used only by the PP-OCRv3 reference re-run (see NOTICE), earlier - generator versions (0.1 and 0.2.0; the text filters of 0.2.0 are identical to those of 0.3.0), staging and test copies of - scripts, one-off probes, the corrector pilot (never trained), the unfinished full-schedule PP-OCRv3 re-run, and the - download and extraction scripts of KOHTD, which need access credentials from its authors. -- config_r5eval/sota_checklist.json is not included. scripts/r5_select_verdict.sbatch passes it to - scripts/r5eval/verdict.py; remove that argument (verdict.py runs without it) or supply your own checklist. - - -2. LICENCES - -Apache-2.0 (LICENSE) for everything except: the line detector's training and inference path and the page pipeline, -which are AGPL-3.0 (LICENSE.AGPL-3.0; the files are listed in NOTICE); the vendored HTR-Flor copy in -src/ref/ (repository state of 23 June 2021; MIT, its own LICENSE); and the Natural Earth map files in -src/pagesynth/assets/naturalearth/ (public domain). Copyright and third-party notices are in NOTICE. - - -3. SETTING UP - -3.1 Paths. The code ran on a Slurm cluster with one code folder and one data folder. Every absolute path in the -package now starts with a placeholder: - - /path/to/TURKIC_OCR_CODE the folder that holds this package (src/, scripts/, ... and the virtual environments) - /path/to/TURKIC_OCR_DATA the data folder, with data/raw, data/processed, outputs, checkpoints, logs, hf_cache, tmp - -Replace both with your own folders before running anything, for example: - - grep -rlF /path/to/TURKIC_OCR_CODE . | xargs sed -i 's#/path/to/TURKIC_OCR_CODE#/home/me/turkic_ocr#g' - grep -rlF /path/to/TURKIC_OCR_DATA . | xargs sed -i 's#/path/to/TURKIC_OCR_DATA#/data/turkic_ocr#g' - -Neither placeholder is a prefix of the other, so the order does not matter. The Slurm headers name -the partitions (H100, ZEN4) and quality-of-service names of the original cluster; adapt them to yours. Many scripts -and comments refer to the project's working records (paths that begin with records/, or files under the data folder -such as manifests and score files); these records are not part of this package. - -3.2 Python environments. The scripts call the interpreter of a project environment, for example -/path/to/TURKIC_OCR_CODE/.venv_gen/bin/python. The folder environments/ holds the exact package list of each -environment, made with 'uv pip freeze'. To rebuild one: - - uv venv --python 3.12 /path/to/TURKIC_OCR_CODE/.venv_gen - uv pip install --python /path/to/TURKIC_OCR_CODE/.venv_gen/bin/python -r environments/venv_gen.requirements - -PyTorch builds with a +cu suffix in the lists come from the PyTorch package index (add ---extra-index-url https://download.pytorch.org/whl/, the tag matching the suffix). - - environment (file) Python main use - .venv (venv.requirements) 3.12 real-data manifests (scripts/r5), KOHTD split and leak checks, zero-shot screen - .venv_gen (venv_gen.requirements) 3.12 generator, training-mix freeze, release data build - .venv_kraken 3.12 CTC line recognizers, letter model, detector, scorer jobs, test pass 2, RQ2 - .venv_vlm 3.12 vision-language training and evaluation (scripts/r5_vlma), single page model, - loop guard, page check, showcase - .venv_vlm_ (9 files) 3.12 * one per extra candidate in scripts/r5_vlmb (* unlimited_ocr_2: 3.10) - .venv_print 3.12 real printed lines (scripts/r5_print) - .venv_ref_tf 3.11 HTR-Flor reference re-run (R1) - .venv_ref_paddle, .venv_ref_paddle_cpu 3.11 PP-OCRv3 reference re-run (R2) - .venv_dl see file download tools (Kazakh web benchmark) - -The exact Python version of each environment is in its file's first line. Each shell and sbatch file names the -environment its step used. The release packages in release/ carry their own requirements.txt. - - -4. FOLDERS AND WHERE THEY APPEAR IN THE PAPER - -src/pagesynth/ Page and line generator 0.3.0: text cleaning and filters (text.py, langtext.py, - textbuild.py, vocab.py), fonts and the glyph gate, the simulated writer, layouts, paper, - marks, maps, capture, cropping; produce_r5.py and scripts/ run the text build, the text - split by source document and the production. Paper: Section 2.2, S2. -src/linedet/ CTC line recognizers (PP-OCRv6 medium and small, CRNN, HTR-VT-style model), training - driver, prediction, the character 6-gram letter model with beam search and its gate, and - (det_*.py, AGPL-3.0) the YOLO11s line detector: data preparation, training, evaluation. - Paper: Sections 3.4 and 3.5, S6, S9, S10. -src/r5eval/, scripts/r5eval/ Scorer: text normalisation, CER and WER, look-alike repair, form-level bootstrap, -config_r5eval/, tests_r5eval/ Holm correction, selection of leaders and of the final model, decision rules, report - cards; with its configuration and tests. Paper: Section 4, S7. -scripts/r5_score.sbatch and Scoring, selection, verdict, learning-curve and self-test jobs of the scorer. - the other scripts/r5_*.sbatch Paper: Section 4, S7. -scripts/r5_gate/ Gate files that kept the test sets sealed until the single test pass. Paper: Section 4, S7. -scripts/r5/ Real-data manifests (KOHTD, HKR, Cyrillic Handwriting Dataset, School Notebooks, RUKOPYS, - LocalDoc), de-duplication against held-out images, the registry of training, validation - and test sets, validation subsets and the unseen-word slice. Paper: Section 2.1, S1, S4, S7. -scripts/k1_labels_all.py, KOHTD split by exam form (a salted deterministic function of the form number). Paper: Section 2.1, S4. - scripts/k1_build_split.py -scripts/kohtd_leak_* Checks that no KOHTD training crop without a form number is a copy of a validation or - test crop. Paper: S4. -scripts/r5_print/ Real printed lines: candidate PDFs from FinePDFs, text-layer check, line cutting, pixel - checks, split by document. Paper: Section 2.1, S3. -scripts/r5_freeze/ Freeze of the training mix (shares, de-duplication against held-out sets, sample - sequences). Paper: Section 2.3, S2. -scripts/j2/ Zero-shot screen of released document models on KOHTD validation words. Paper: Section 3.2. -scripts/r5_vlma/ Fine-tuning and evaluation of the vision-language readers (shared recipe, short and long - runs, slot runners), preference post-training (DPO, GRPO), and the sealed test pass. - Paper: Sections 3.2, 3.3 and 4, S5, S6, S7. -scripts/r5_vlmb/ Adapters, environments and runner for the extra vision-language candidates. Paper: S5, S6. -scripts/r5_linedet/ Jobs of the line recognizers, the detector and the letter model. Paper: Sections 3.4, 3.5, S6. -scripts/r5_ref/, src/ref/ Reference re-runs: HTR-Flor (R1, vendored copy in src/ref/) and PP-OCRv3 (R2, PaddleOCR - not included). Paper: Section 5, S10. -scripts/r5_testpass2/ Second test pass and its amendments: real handwriting and print tests, page tests - (TurkishOCR-Bench, Kazakh web benchmark), label-free re-reading of the line recognizer, - per-language tables, error analysis. Paper: Section 5, S7, S8, S9. -scripts/tp2_proposal_metrics.py Measures for the research questions. Paper: Section 6.1, S8. -scripts/r5_erran/ Error analysis of validation outputs (label errors, ambiguous handwriting). Paper: S7. -scripts/b1_page_check/ Page check: the final model on whole pages, alone and after the detector. Paper: S9. -scripts/r5_onemodel/ Single page model: page records, training, page scoring. Paper: S6, S9. -scripts/r5_loopguard/ Loop guard for the single page model. Paper: S9, S10. -scripts/r5_showcase/ Showcase pages: the generator stages of chosen validation pages (material for Figure 2) - and pages read by the pipeline. Paper: Section 2.2, S11. -scripts/r5_release/ Checks of the first release candidate, including the batching diagnostic of the line - recognizer. Paper: S7 (the batching leak). -scripts/release2/ Release build: data package, Parquet shards, regeneration check of every released page, - Sakha-text check, cards and file verification; rel2_d5_* (AGPL-3.0) retrain and check the - released detector without the personal-use-font pages. Paper: S11. -release/ Inference scripts and requirements of the release packages: the three readers (whose - weights are not released), the line detector and the page pipeline (AGPL-3.0). Paper: S11. -src/rq2/, scripts/r5_rq2/, RQ2 augmentation study (line height 32 or 64 px crossed with a typical or a diacritic-safe -src/lettersynth/ augmentation policy) and its pixel probe; src/lettersynth holds only the letter-sheet - reader that the probe uses. This code was written after the paper's results; the paper - states that the study was not run, and no RQ2 result is part of it. -environments/ Package lists of the Python environments (part 3.2). - - -5. KNOWN ISSUES - -- Content pins. Some files pin the exact content of other files as it was on the cluster, and a few check it at start. - Making the paths configurable changed some pinned files, so those pins no longer match (the list of affected pins - is in part 7). Update the pinned values after configuring the paths, or skip the check. -- release/turkic-ocr-ppocrv6-medium/infer.py is the inference script of the withheld PP-OCRv6 package. Its docstring - was written before the corrections the paper reports in S7 (the batching leak) and was not updated; the paper's - figures supersede the ones it quotes. -- The generator reproduces the content of a page from its seed but not every byte (paper, S11). -- The scripts were written for one cluster and one run of the project: many take their inputs from fixed paths and - write records of that run. They document what was done; running them elsewhere needs the data, the paths and the - job headers set up as described in part 3. - - -6. REAL DATASETS: NOT INCLUDED, WHERE TO OBTAIN THEM - - KOHTD (Kazakh handwriting) https://github.com/abdoelsayed2016/KOHTD (the authors' application form) - HKR (Kazakh and Russian) https://github.com/abdoelsayed2016/HKR_Dataset (the authors' application form) - School Notebooks RU https://huggingface.co/datasets/ai-forever/school_notebooks_RU - Cyrillic Handwriting Dataset https://www.kaggle.com/datasets/constantinwerner/cyrillic-handwriting-dataset - Azerbaijani Handwritten OCR - Benchmark (LocalDoc) https://huggingface.co/datasets/LocalDoc/azerbaijani-htr-benchmark - TurkishOCR-Bench https://huggingface.co/datasets/moganai/TurkishOCR-Bench - RUKOPYS (Ukrainian) https://huggingface.co/datasets/UkrainianCatholicUniversity/rukopys - FinePDFs (real printed lines) https://huggingface.co/datasets/HuggingFaceFW/finepdfs - FineWeb-2 (generator text) https://huggingface.co/datasets/HuggingFaceFW/fineweb-2 - Wikipedia (generator text) https://huggingface.co/datasets/wikimedia/wikipedia (snapshot 20231101) - PP-OCRv6 medium base weights https://doi.org/10.5281/zenodo.21788410 - -Each dataset keeps its own licence and terms. Three further sources are read by the code but are not in the paper's -reference list; their identifiers are taken from the code: - Kazakh web benchmark Hugging Face dataset Omar-2002/kz_benchmark_data (scripts/r5_testpass2/tp2_kzb_fetch.py) - Sakha newspaper corpus Hugging Face dataset ailabykt/sakha-corpus-mono (generator text for Sakha) - Kazakh handwritten letter sheets https://github.com/Nuray-Sheriyeva/Kazakh_Handwritten_Letter_Dataset (dataset_split_v2; - read by the RQ2 pixel probe) - - -7. EDITS MADE FOR THE PACKAGE, AND CONTENT PINS - -The package was made from the project's files by these edits only: absolute paths were replaced by the placeholders of -part 3.1; comments and descriptive strings were reworded; the folder scripts/r5_gate was renamed; two output fields -were renamed (endpoints_confirmed in the verdict written by scripts/r5eval/verdict.py, added_beyond_plan in the set -registry written by scripts/r5/r5_registry.py); one verdict text of scripts/r5_freeze/dedupe_verdict.py now reads -"NEEDS MANUAL REVIEW"; and scripts/r5_testpass2/tp2_make_plan.py no longer records the fingerprint of a planning note. - -Two pins that the code checks at run time were updated to the shipped files, so they match: - src/r5eval/cards.py (label-rule pin) the content of config_r5eval/r5_descriptive_labels.txt (reworded first line), - checked by scripts/r5eval/report_cards.py. - src/r5eval/frozen.py (frozen-file pin) the content of src/r5eval/frozen/postproc_vlma.py (one reworded docstring line; - scripts/r5_vlma/postproc.py and scripts/r5_vlmb/postproc.py are identical - copies), checked whenever the scorer is imported. - -Four pins refer to a file that these edits changed and were left as they were: - - src/rq2/geom.py pins src/linedet/common.py (paths). Checked at start: the RQ2 wrappers stop - with "REFUSED". After configuring the paths, put the new fingerprint of - src/linedet/common.py into PINNED in src/rq2/geom.py. The same table pins - four kraken files of the installed kraken package and three data files. - scripts/r5_vlma/make_vlmb_testpass.py pins scripts/r5_vlmb/vlmb_eval_vlm.py (a reworded comment); it is the one-time - builder of scripts/r5_vlmb/vlmb_eval_vlm_testpass.py, which also quotes that - fingerprint in a comment. - scripts/r5_vlma/testpass_config.json quotes the fingerprint of scripts/r5_linedet/test_pass_commands.sh (paths) in a note. - -All other pins inside the package still match. +# Turkic OCR: generator, training and evaluation code + +This is the code behind one text reader for typed and handwritten text in nine Turkic languages: Kazakh, Kyrgyz, +Tatar, Bashkir and Sakha in Cyrillic, Turkish, Azerbaijani and Turkmen in Latin, and Uzbek in both scripts. A YOLO11s +detector finds the text lines on a page, and a fine-tuned PaddleOCR-VL-1.6 reads each line. Of the nine languages only +Kazakh has real handwriting to train on, so a page generator, pagesynth 0.3.0, writes real sentences onto simulated +school pages with exact line labels. The work is described in + +> A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev +> University, 2026. + +```bibtex +@techreport{turkicocr2026, + author = {{Project authors}}, + title = {A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script}, + institution = {Nazarbayev University}, + type = {Project report}, + year = {2026} +} +``` + +Related repositories: the generated data `treoa/turkic-ocr-generated-data` (CC BY-SA 4.0), the detector weights +`treoa/turkic-line-detector-yolo11s` and the page pipeline `treoa/turkic-ocr-page-pipeline` (both AGPL-3.0). + +## Layout + +| Folder | Contents | +|---|---| +| `src/pagesynth/` | page and line generator 0.3.0: text filters, fonts, simulated writer, layouts, paper, marks, maps, capture, cropping | +| `src/linedet/` | CTC line recognizers (PP-OCRv6-medium and others), the 6-gram character language model, the YOLO11s detector (`det_*.py`) | +| `src/r5eval/` | scorer: normalisation, CER and WER, look-alike repair, bootstrap intervals, model selection, report cards | +| `src/rq2/`, `src/lettersynth/` | augmentation study (line height 32 or 64 px crossed with two augmentation policies) | +| `src/ref/` | vendored HTR-Flor, used for the reference re-run | +| `scripts/` | job scripts: real-data manifests and splits, training mix, training, test passes, page scoring, release build | +| `config_r5eval/` | configuration of the scorer and the model selection (there is no separate `configs/` folder) | +| `release/` | inference scripts and requirements of the detector, the page pipeline and the three readers | +| `tests/` | unit tests of the scorer utilities and a small scoring sample (`tests/data/sample_eval/`) | +| `tests_r5eval/` | the scorer's original test suite (`python tests_r5eval/run_all.py SCRATCH_DIR`) | +| `results/` | `metrics.csv` (headline numbers of the 6-page paper) and the three paper figures | +| `environments/` | exact package lists of every Python environment used in the project | + +## Setup + +Python 3.12. On Linux or macOS: + +```bash +python3.12 -m venv .venv +.venv/bin/python -m pip install -r requirements.txt +``` + +`make setup` does the same (`make setup PYTHON=/path/to/python3.12` picks another interpreter). `requirements.txt` covers the tests, the scorer, the +generator and line detection on the CPU. Training used other environments; their exact package lists are in +`environments/` (for example `environments/venv_vlm.requirements` for the vision-language readers). PyTorch builds with +a `+cu` suffix there come from `https://download.pytorch.org/whl/`. + +The job scripts were written for one Slurm cluster. Absolute paths in them start with two placeholders, which you +replace with your own folders before running a job: + +```bash +grep -rlF /path/to/TURKIC_OCR_CODE . | xargs sed -i 's#/path/to/TURKIC_OCR_CODE#/home/me/turkic_ocr#g' +grep -rlF /path/to/TURKIC_OCR_DATA . | xargs sed -i 's#/path/to/TURKIC_OCR_DATA#/data/turkic_ocr#g' +``` + +The Slurm headers name the partitions of the original cluster. Many scripts read manifests and write records of the +original run; those files are not part of this package. + +## Data + +No dataset is stored here. The generated data are on the Hugging Face Hub, in four configurations (`hand`, `typed`, +`clutter`, `pages`), each with train, validation and test splits: + +```bash +hf download treoa/turkic-ocr-generated-data --repo-type dataset --local-dir data/generated +``` + +```python +from datasets import load_dataset # pip install datasets +hand_val = load_dataset("treoa/turkic-ocr-generated-data", "hand", split="validation") +``` + +The real datasets keep their own licences and must be obtained from their sources: + +| Set | Where | +|---|---| +| KOHTD (Kazakh handwriting) | https://github.com/abdoelsayed2016/KOHTD (application form of its authors) | +| HKR (Kazakh and Russian handwriting) | https://github.com/abdoelsayed2016/HKR_Dataset (application form of its authors) | +| School Notebooks RU | https://huggingface.co/datasets/ai-forever/school_notebooks_RU | +| Cyrillic Handwriting Dataset | https://www.kaggle.com/datasets/constantinwerner/cyrillic-handwriting-dataset | +| Azerbaijani Handwritten OCR Benchmark | https://huggingface.co/datasets/LocalDoc/azerbaijani-htr-benchmark | +| TurkishOCR-Bench | https://huggingface.co/datasets/moganai/TurkishOCR-Bench | +| RUKOPYS | https://huggingface.co/datasets/UkrainianCatholicUniversity/rukopys | +| FinePDFs (real printed lines) | https://huggingface.co/datasets/HuggingFaceFW/finepdfs | +| FineWeb-2, Wikipedia (generator text) | https://huggingface.co/datasets/HuggingFaceFW/fineweb-2, https://huggingface.co/datasets/wikimedia/wikipedia | +| PP-OCRv6-medium base weights | https://doi.org/10.5281/zenodo.21788410 | + +The code also reads the Kazakh web benchmark `Omar-2002/kz_benchmark_data`, the Sakha newspaper corpus +`ailabykt/sakha-corpus-mono` (generator text for Sakha) and the Kazakh handwritten letter sheets of +https://github.com/Nuray-Sheriyeva/Kazakh_Handwritten_Letter_Dataset (used by the augmentation study's pixel probe). + +## Running + +Tests (`make test`): the files in `tests/` check edit distance, text normalisation, look-alike repair and one full +scoring run. + +```bash +make test # pytest, 22 tests, under a minute on a laptop +make lint # ruff on tests/ +``` + +Scoring a prediction file (`make sample-eval`). The scorer reads a set registry, a manifest per set, and prediction +files laid out as `///.tsv` with the columns `id`, `ref`, `hyp`. The bundled sample has +ten made-up lines in eight languages with ten character errors: + +```bash +python scripts/r5eval/score.py --preds tests/data/sample_eval/preds --registry tests/data/sample_eval/evalsets.json \ + --out outputs/sample_eval --B 1000 --settle 0 +``` + +The score file `outputs/sample_eval/demo/final/sample_lines.json` holds the CER under +`profiles.plain.groups.all.metrics.cer`: 10 / 229 = 0.0437, with a 95% bootstrap interval over pages. + +Line detection on a page image, with the released weights (needs `torch` and `ultralytics` from `requirements.txt`): + +```bash +hf download treoa/turkic-line-detector-yolo11s best.pt --local-dir models/detector +python release/turkic-line-detector-yolo11s/infer.py --images page.jpg --weights models/detector/best.pt \ + --out boxes.tsv --device cpu +``` + +The output TSV has one row per image: `id`, `n_lines`, `boxes` (JSON list of `[x0, y0, x1, y1]` in pixels) and `scores`. +To read the lines as well, use the page pipeline repository; it needs reader weights, which are not released. + +Generating pages. The generator needs the 73 fonts listed in `src/pagesynth/assets/fonts_manifest.tsv` (font, licence +class, held out or not). The font files are not shipped: put them in `src/pagesynth/assets/fonts/` or point +`PAGESYNTH_FONTS` at their folder. It also needs a sentence bank per language, built from Wikipedia and FineWeb-2 by +`src/pagesynth/scripts/build_text.py` and `build_label_vocab.py`. Then, for ten Kazakh notebook pages: + +```bash +python src/pagesynth/generate_pages.py --type notebook --lang kk --n 10 --seed 1 --strength mixed \ + --out out/pages --text-dir TEXT --no-personal-fonts +``` + +`--no-personal-fonts` leaves out the eight fonts whose licence allows personal use only. The released generated data +contain no item drawn with them. + +Training. The training entry points are `scripts/r5_vlma/train_vlm.py` (full fine-tuning of the vision-language +readers), `scripts/r5_vlmb/vlmb_train.py` (readers that need their maker's code), `src/linedet/train_arm.py` (CTC line +recognizers), `src/linedet/det_yolo.py` (detector) and `scripts/r5_rq2/rq2_train.py` (augmentation study). The full +runs need H100 GPUs on a Slurm cluster and the licensed real data, KOHTD and HKR above all. The reader weights trained in +the project are not released: the terms of KOHTD and HKR limit their use to the applicant's group and to academic +research. The detector was trained on School Notebooks photos and generated pages, and its weights are released. + +## Seeds + +Fixed defaults in the code: `--seed 20261121` for the bootstrap of the scorer (`scripts/r5eval/score.py`), for the +sample stream of the line recognizers (`src/linedet/train_arm.py`) and for `scripts/r5_vlmb/vlmb_train.py`; +`--data-order-seed 20261121` is recorded by `scripts/r5_vlma/train_vlm.py`, whose data order comes from a fixed +sequence file; the generator draws each page from `--seed` (default 1) and the page index. The generator reproduces the +content of a page from its seed, but not every byte of the image. + +## Results + +`results/metrics.csv` lists the headline numbers of the 6-page paper, with 95% intervals where the paper gives them; +`results/figures/` holds its three figures. On the sealed KOHTD test of 18,615 Kazakh handwritten words the +fine-tuned PaddleOCR-VL-1.6 reads at 4.01% CER (3.71 to 4.32%), and on 8,265 real printed lines at 0.244%. On 50 +handwritten Turkish test pages its page CER is 49.8%. The long version of the report also gives the augmentation +study, run on validation data only. + +## Not included + +- Data of any kind: real datasets, generated data, manifests, splits, predictions. +- Weights of the fine-tuned readers (PaddleOCR-VL-1.6, Qwen3-VL-2B, PP-OCRv6-medium and its character language model). +- Font files. +- The scripts of the continued training on real Latin-script handwriting, of the IAM scoring and of the later, + more realistic generator version. +- The PaddleOCR source used by the PP-OCRv3 reference re-run (see NOTICE) and the KOHTD download scripts. +- `config_r5eval/sota_checklist.json`: `scripts/r5_select_verdict.sbatch` passes it to `scripts/r5eval/verdict.py`; + drop that argument, since `verdict.py` runs without it. + +## Known issues + +- Some scripts check at start that other files are unchanged byte for byte. Replacing the path placeholders changes + those files, so the checks fail: `src/rq2/geom.py` then stops with "REFUSED" until you update its `PINNED` table. +- The docstring of `release/turkic-ocr-ppocrv6-medium/infer.py` quotes figures from before the batching correction; + the paper's figures replace them. + +## Licences + +Apache-2.0 (`LICENSE`) for everything except: the detector's training and inference path and the page pipeline, +AGPL-3.0 (`LICENSE.AGPL-3.0`, files listed in `NOTICE`), because Ultralytics YOLO is AGPL-3.0; the vendored HTR-Flor +copy in `src/ref/` (MIT, its own `LICENSE`); and the Natural Earth map files in `src/pagesynth/assets/naturalearth/` +(public domain). Third-party notices are in `NOTICE`. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1126891092d9f2aa1991b7b9da00accd1a5fbc7c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,16 @@ +[project] +name = "turkic-ocr-code" +version = "1.0.0" +description = "Generator, training and evaluation code for one text reader in nine Turkic languages" +requires-python = ">=3.12" + +[tool.pytest.ini_options] +pythonpath = ["src"] +testpaths = ["tests"] + +[tool.ruff] +line-length = 120 +target-version = "py312" + +[tool.ruff.lint] +select = ["E", "F", "W", "I"] diff --git a/release/page-pipeline/infer.py b/release/page-pipeline/infer.py index 578169120fba713df52a39a3462e3cdb1052775f..16be78b1d44c14b6f8955dad98eb3f9010c5553d 100644 --- a/release/page-pipeline/infer.py +++ b/release/page-pipeline/infer.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -"""Read whole pages: find the text lines, cut a crop for every line, read every crop (Turkic OCR, release candidate 1). +"""Read whole pages: find the text lines, cut a crop for every line, read every crop (Turkic OCR). Stage 1 runs the detector package (turkic-line-detector-yolo11s) on the page image as a subprocess, because it needs ultralytics, which the reader's environment does not contain: pass --detector-python with a Python that has ultralytics (the default is this Python). -Stage 2 cuts one crop per box and reads every crop with the reader package (turkic-ocr-paddleocr-vl-1.6, final model of this release, -greedy, bfloat16, at most 192 new tokens per line, batches of 16 crops in reading order), in this process. +Stage 2 cuts one crop per box and reads every crop, in this process, with the reader package given by --reader-dir (bfloat16, batches of +16 crops in reading order). No reader is included: the project's fine-tuned PaddleOCR-VL-1.6 is not distributed (see model_card.json). -Crop and reading-order logic are those of our evaluation (CODE/src/linedet/det_eval.py and the page check detb1_page_check.py): +Crop and reading-order logic are those of our evaluation (src/linedet/det_eval.py and scripts/b1_page_check/detb1_page_check.py in treoa/turkic-ocr-code): - reading order: boxes sorted by (centre_y // band, centre_x) in the detection image, band = 15 px in a page whose longer side is 1280 px (the band grows in proportion for a larger or smaller page); - crop: the box widened by 1 % of its width plus 2 px on each side and heightened by 10 % of its height plus 1 px above and below, @@ -19,8 +19,8 @@ Outputs: --out, a TSV with one row per page: id, n_lines, text (the lines in rea --lines-out, a TSV with one row per crop: id, line, x0, y0, x1, y1, score, text (boxes in detection-image pixels). usage: - python infer.py --images page.jpg --out pages.tsv --lines-out lines.tsv - python infer.py --manifest pages.tsv --out pages.tsv --lines-out lines.tsv --detector-python /path/to/venv-with-ultralytics/bin/python + python infer.py --images page.jpg --reader-dir /path/to/reader --out pages.tsv --lines-out lines.tsv + python infer.py --manifest pages.tsv --reader-dir /path/to/reader --out pages.tsv --lines-out lines.tsv --detector-python /path/to/venv-with-ultralytics/bin/python """ import os diff --git a/release/page-pipeline/requirements.txt b/release/page-pipeline/requirements.txt index 1c66c1bb25dbefd28b29a193b54143285d7bfcb5..3678f126fdca74417a146c250a349defb7e62825 100644 --- a/release/page-pipeline/requirements.txt +++ b/release/page-pipeline/requirements.txt @@ -1,7 +1,7 @@ -# The page pipeline runs in the READER's environment (infer.py here and the reader's code): exact package versions of CODE/.venv_vlm, -# Python 3.12.13. The detector needs ultralytics, which this environment does not have: install the requirements.txt of -# turkic-line-detector-yolo11s in a second environment and pass its Python as --detector-python (one environment holding both also works). -# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_vlm.txt). +# The page pipeline runs in the reader's environment (infer.py here and the reader's code): exact package versions of +# that environment, Python 3.12.13, frozen with `uv pip freeze` on 2026-11-25. The detector needs ultralytics, which +# this environment does not have: install the requirements.txt of turkic-line-detector-yolo11s in a second environment +# and pass its Python as --detector-python (one environment holding both also works). # torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same # versions run on the CPU (bfloat16 matrix products are used on CPU as well), or install torch==2.11.0 and torchvision==0.26.0 from PyPI. --extra-index-url https://download.pytorch.org/whl/cu128 diff --git a/release/turkic-line-detector-yolo11s/infer.py b/release/turkic-line-detector-yolo11s/infer.py index fcc3363e7d31b1241898e860d400ef7f4f328db1..523bf163ec88dd1a36eb167894b486829ad078a3 100644 --- a/release/turkic-line-detector-yolo11s/infer.py +++ b/release/turkic-line-detector-yolo11s/infer.py @@ -1,12 +1,12 @@ #!/usr/bin/env python -"""Find text lines on page images with the YOLO11s line detector of Turkic OCR (release candidate 1, stage-2 weights best.pt). +"""Find text lines on page images with the YOLO11s line detector of Turkic OCR (weights best.pt). Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with one row per page image and the columns id, n_lines, boxes, scores where boxes is a JSON list of [x0, y0, x1, y1] in pixels of the input image (rounded to 0.1) and scores a JSON list of the detection confidences (rounded to 0.0001), in the detector's own order. A detector finds boxes, not text, so this TSV replaces the (id, text) table of the readers; the reader of the page-pipeline package turns the boxes into text. -The settings are those of our detection evaluation (CODE/src/linedet/det_eval.py): the image file is passed to ultralytics, image size +The settings are those of our detection evaluation (src/linedet/det_eval.py in treoa/turkic-ocr-code): the image file is passed to ultralytics, image size 1280, confidence threshold 0.25, NMS IoU 0.6, at most 300 boxes, one class "text_line". usage: diff --git a/release/turkic-line-detector-yolo11s/requirements.txt b/release/turkic-line-detector-yolo11s/requirements.txt index 3eca15017baad45dc7c2ea2134eb551cb9535ada..56c6a6ae025ad8f321be7c6a3dea516c7dbf1c3a 100644 --- a/release/turkic-line-detector-yolo11s/requirements.txt +++ b/release/turkic-line-detector-yolo11s/requirements.txt @@ -1,5 +1,5 @@ -# Exact package versions of the environment this detector was trained and evaluated in: CODE/.venv_kraken, Python 3.12.13. -# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_kraken.txt). +# Exact package versions of the environment this detector was trained and evaluated in (Python 3.12.13), +# frozen with `uv pip freeze` on 2026-11-25. # What infer.py imports directly: ultralytics (8.4.216; AGPL-3.0), torch, and through ultralytics numpy, opencv-python, pillow, scipy, pyyaml. # torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same # versions run on the CPU. diff --git a/release/turkic-ocr-paddleocr-vl-1.6/infer.py b/release/turkic-ocr-paddleocr-vl-1.6/infer.py index 642aec7511015427124a3ca527c9f0df9cca3397..1d80dce5e04cf10d5bf8e30647568528e213174e 100644 --- a/release/turkic-ocr-paddleocr-vl-1.6/infer.py +++ b/release/turkic-ocr-paddleocr-vl-1.6/infer.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -"""Read word or line crops with the vision-language model in ./model (Turkic OCR, release candidate 1). +"""Read word or line crops with the vision-language model in ./model (Turkic OCR). Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with the columns id and text. -The decoding is the one of our evaluation (CODE/scripts/r5_vlma/vlm_common.py and eval_vlm.py), copied here so the package stands alone: +The decoding is the one of our evaluation (scripts/r5_vlma/vlm_common.py and eval_vlm.py), copied here so the package stands alone: - the single instruction "Transcribe the text in this image exactly." with one image, the model's own chat template, generation prompt on, chat-template variables and answer-end token read from model/r5_export.json; - greedy decoding, one beam, no repetition penalty, left padding, stop on the generation-config end ids, the tokenizer end id and diff --git a/release/turkic-ocr-paddleocr-vl-1.6/requirements.txt b/release/turkic-ocr-paddleocr-vl-1.6/requirements.txt index 2b539297c5d3d0da2c22c571d10516d3f25c0f3c..83bab482c6ad7125917ff51c844bd115e29fe53d 100644 --- a/release/turkic-ocr-paddleocr-vl-1.6/requirements.txt +++ b/release/turkic-ocr-paddleocr-vl-1.6/requirements.txt @@ -1,5 +1,5 @@ -# Exact package versions of the environment this model was evaluated in: CODE/.venv_vlm, Python 3.12.13. -# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_vlm.txt). +# Exact package versions of the environment this model was evaluated in (Python 3.12.13), +# frozen with `uv pip freeze` on 2026-11-25. # torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same # versions run on the CPU (bfloat16 matrix products are used on CPU as well), or install torch==2.11.0 and torchvision==0.26.0 from PyPI. --extra-index-url https://download.pytorch.org/whl/cu128 diff --git a/release/turkic-ocr-ppocrv6-medium/infer.py b/release/turkic-ocr-ppocrv6-medium/infer.py index 50bbf85d929e378a452a9d5978c5de360967f15e..5e70b80ad5db82eda759e281e9b3781baca9dc76 100644 --- a/release/turkic-ocr-ppocrv6-medium/infer.py +++ b/release/turkic-ocr-ppocrv6-medium/infer.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -"""Read word or line crops with the small recognizer A1 (kraken PP-OCRv6 medium, our checkpoint long2x) - Turkic OCR, release candidate 1. +"""Read word or line crops with the small recognizer A1 (kraken PP-OCRv6 medium, our checkpoint long2x) of Turkic OCR. Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with the columns id and text. -The code path is the one of our evaluation (CODE/src/linedet/data.py, models.py, predict.py, lm_decode.py, lm_gate.py), copied here so +The code path is the one of our evaluation (src/linedet/data.py, models.py, predict.py, lm_decode.py, lm_gate.py), copied here so the package stands alone: - image: RGB, scaled to 96 px height with Lanczos (width keeps the aspect ratio), 16 px white padding left and right, scaled to [0, 1], inverted (ink bright); a batch is padded with zeros on the right to its widest image; @@ -10,8 +10,8 @@ the package stands alone: squeeze-and-excite layers of kraken's backbone average over the whole padded width (kraken/lib/ppocr/backbone.py, SELayer), while only the attention of the neck masks the padded columns (network.py, _lengths_and_mask). The evaluation read batches of 32 sorted by LABEL length, so every batch carried white margin on its narrower crops, and the network was trained that way; without labels that - cannot be repeated. Measured on the 3,678 KOHTD validation crops V1 (greedy, CPU float32, character error rate; jobs 55155 and - 55176): evaluation batches 6.2% (the recorded GPU file: 6.2%); batches sorted by width 14.1%; every crop alone 14.2%; batches in + cannot be repeated. Measured on the 3,678 KOHTD validation crops V1 (greedy, CPU float32, character error rate): + evaluation batches 6.2% (the recorded GPU file: 6.2%); batches sorted by width 14.1%; every crop alone 14.2%; batches in manifest order 7.9%; in a seeded shuffle 7.3%; sorted by width plus 64, 128, 256, 512, 1024 extra zero columns: 10.4%, 8.1%, 6.55%, 6.50%, 7.5%. This script therefore sorts by width and appends --batch-pad (default 256) zero columns to every batch: a label-free approximation chosen on V1 (word crops; the value for line crops is untested), not the evaluation's own condition. To reproduce the @@ -50,7 +50,7 @@ from safetensors.torch import load_file # noqa: E402 HERE = os.path.dirname(os.path.abspath(__file__)) IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") PAD = 16 -BATCH_PAD_DEFAULT = 256 # extra zero columns per batch, chosen on V1 from {0, 64, 128, 256, 512, 1024} (job 55176) +BATCH_PAD_DEFAULT = 256 # extra zero columns per batch, chosen on V1 from {0, 64, 128, 256, 512, 1024} TOPK = 6 BEAM = 16 ALPHA, BETA = 0.40, 1.00 diff --git a/release/turkic-ocr-ppocrv6-medium/requirements.txt b/release/turkic-ocr-ppocrv6-medium/requirements.txt index e4dfbade207eb65a72bcff888442d3acd077ad90..a2eb7d21c19a4ea4598e4784fcfd32a818b26a03 100644 --- a/release/turkic-ocr-ppocrv6-medium/requirements.txt +++ b/release/turkic-ocr-ppocrv6-medium/requirements.txt @@ -1,5 +1,5 @@ -# Exact package versions of the environment this model was trained and evaluated in: CODE/.venv_kraken, Python 3.12.13. -# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_kraken.txt). +# Exact package versions of the environment this model was trained and evaluated in (Python 3.12.13), +# frozen with `uv pip freeze` on 2026-11-25. # What infer.py imports directly: kraken (PPOCRv6Model, PytorchCodec), torch, numpy, pillow, safetensors, and kenlm for --decode lm and lm_gated. # kenlm==0.3.0 is built from source on installation (needs a C++ compiler). torch and torchvision are the CUDA 12.8 builds ("+cu128"); the # index line below lets pip find them. On a machine without a GPU the same versions run on the CPU (float32 there). diff --git a/release/turkic-ocr-qwen3-vl-2b/infer.py b/release/turkic-ocr-qwen3-vl-2b/infer.py index 642aec7511015427124a3ca527c9f0df9cca3397..1d80dce5e04cf10d5bf8e30647568528e213174e 100644 --- a/release/turkic-ocr-qwen3-vl-2b/infer.py +++ b/release/turkic-ocr-qwen3-vl-2b/infer.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -"""Read word or line crops with the vision-language model in ./model (Turkic OCR, release candidate 1). +"""Read word or line crops with the vision-language model in ./model (Turkic OCR). Input: one image, a folder of images, or a TSV manifest (columns id, image). Output: a TSV with the columns id and text. -The decoding is the one of our evaluation (CODE/scripts/r5_vlma/vlm_common.py and eval_vlm.py), copied here so the package stands alone: +The decoding is the one of our evaluation (scripts/r5_vlma/vlm_common.py and eval_vlm.py), copied here so the package stands alone: - the single instruction "Transcribe the text in this image exactly." with one image, the model's own chat template, generation prompt on, chat-template variables and answer-end token read from model/r5_export.json; - greedy decoding, one beam, no repetition penalty, left padding, stop on the generation-config end ids, the tokenizer end id and diff --git a/release/turkic-ocr-qwen3-vl-2b/requirements.txt b/release/turkic-ocr-qwen3-vl-2b/requirements.txt index 2b539297c5d3d0da2c22c571d10516d3f25c0f3c..83bab482c6ad7125917ff51c844bd115e29fe53d 100644 --- a/release/turkic-ocr-qwen3-vl-2b/requirements.txt +++ b/release/turkic-ocr-qwen3-vl-2b/requirements.txt @@ -1,5 +1,5 @@ -# Exact package versions of the environment this model was evaluated in: CODE/.venv_vlm, Python 3.12.13. -# Frozen with `uv pip freeze` on 2026-11-25 (cluster job 55104, file DATA/tmp/rc1_check/freeze_vlm.txt). +# Exact package versions of the environment this model was evaluated in (Python 3.12.13), +# frozen with `uv pip freeze` on 2026-11-25. # torch and torchvision are the CUDA 12.8 builds ("+cu128"); the index line below lets pip find them. On a machine without a GPU the same # versions run on the CPU (bfloat16 matrix products are used on CPU as well), or install torch==2.11.0 and torchvision==0.26.0 from PyPI. --extra-index-url https://download.pytorch.org/whl/cu128 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ec863e92e468e8c89dc89d977d8d3b96ec334541 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,18 @@ +# Python 3.12. Packages for the unit tests, the scorer, the page generator and line detection on one machine. +# Versions match the project environments listed in environments/ (training needs more; see environments/). +numpy==2.5.5 +scipy==1.18.1 +regex==2026.11.19 +shapely==2.1.2 +pyyaml==6.0.3 +pillow==13.0.0 +opencv-python-headless==5.1.0.95 +fonttools==4.68.0 +rdkit==2026.9.2 +pyarrow==26.0.1 +huggingface-hub==2.4.0 +torch==2.11.0 +torchvision==0.26.0 +ultralytics==8.4.216 +pytest==9.2.0 +ruff==0.17.6 diff --git a/results/figures/fig1_overview.png b/results/figures/fig1_overview.png new file mode 100644 index 0000000000000000000000000000000000000000..6ee457b79b8104084522cb9af8b7a268ceac1954 --- /dev/null +++ b/results/figures/fig1_overview.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac5bccf6782a906ad6ffa91e7d88e9bbb3e415f6eb9ea78ab67450912be2faf2 +size 183914 diff --git a/results/figures/fig2_results.png b/results/figures/fig2_results.png new file mode 100644 index 0000000000000000000000000000000000000000..21b436586c7dd04d0feecd7fc4b424c3501de1eb Binary files /dev/null and b/results/figures/fig2_results.png differ diff --git a/results/figures/fig3_forgetting.png b/results/figures/fig3_forgetting.png new file mode 100644 index 0000000000000000000000000000000000000000..7e3b30f7ecb650b79b124e5456bde5dd7843f7af Binary files /dev/null and b/results/figures/fig3_forgetting.png differ diff --git a/results/metrics.csv b/results/metrics.csv new file mode 100644 index 0000000000000000000000000000000000000000..aba5f061f71ac718199f1b1cb8cfd4a0a6540351 --- /dev/null +++ b/results/metrics.csv @@ -0,0 +1,23 @@ +model,set,metric,value,interval +PaddleOCR-VL-1.6 fine-tuned (shipped model),KOHTD sealed test (18615 Kazakh handwritten words),CER %,4.01,3.71 to 4.32 +Qwen3-VL-2B fine-tuned,KOHTD sealed test (18615 Kazakh handwritten words),CER %,4.11, +PP-OCRv6-medium fine-tuned with 6-gram character LM,KOHTD sealed test (18615 Kazakh handwritten words),CER %,4.09, +PP-OCRv6-medium fine-tuned greedy,KOHTD sealed test (18615 Kazakh handwritten words),CER %,5.36, +PaddleOCR-VL-1.6 fine-tuned (shipped model),KOHTD sealed test words unseen in training (2228),CER %,7.63, +PaddleOCR-VL-1.6 fine-tuned (shipped model),real printed test lines (8265),CER %,0.244,0.116 to 0.465 +Qwen3-VL-2B fine-tuned,real printed test lines (8265),CER %,0.154,0.090 to 0.243 +PaddleOCR-VL-1.6 fine-tuned (shipped model),real Azerbaijani handwritten lines (442; descriptive),CER %,63.6,52.0 to 74.4 +PaddleOCR-VL-1.6 untuned base,real Azerbaijani handwritten lines (442; descriptive),CER %,46.6, +PP-OCRv6-medium fine-tuned,real Azerbaijani handwritten lines (442; descriptive),CER %,36.9, +PaddleOCR-VL-1.6 fine-tuned (shipped model),TurkishOCR-Bench handwritten test pages (50),page CER %,49.8, +PaddleOCR-VL-1.6 fine-tuned (shipped model),Russian validation photos with teacher marks (150),page CER % ignoring line order,30.9, +Qwen3-VL-2B fine-tuned,Russian validation photos with teacher marks (150),page CER % ignoring line order,32.9, +PaddleOCR-VL-1.6 fine-tuned (shipped model),empty regions of real notebook validation photos (418),share with text written %,2.15,upper 95% bound 4.05 +Qwen3-VL-2B fine-tuned,empty regions of real notebook validation photos (418),share with text written %,2.39,upper 95% bound 4.36 +PaddleOCR-VL-1.6 continued training (mean of 3 seeds),KOHTD sealed test (18615 Kazakh handwritten words),CER %,4.16, +PaddleOCR-VL-1.6 continued training (3 seeds),real Latin-script validation lines (Portuguese and French; held-out writers),CER %,4.28, +PaddleOCR-VL-1.6 fine-tuned (shipped model),real Latin-script validation lines (Portuguese and French; held-out writers),CER %,63.31, +PaddleOCR-VL-1.6 continued training (3 seeds),IAM English handwritten test lines,CER %,24.18, +PaddleOCR-VL-1.6 fine-tuned (shipped model),IAM English handwritten test lines,CER %,52.65, +PaddleOCR-VL-1.6 continued training (3 seeds),real Azerbaijani handwritten lines (435; descriptive),CER %,31.93, +PaddleOCR-VL-1.6 fine-tuned (shipped model),real Azerbaijani handwritten lines (435; descriptive),CER %,63.20, diff --git a/scripts/r5/r5_build_real.py b/scripts/r5/r5_build_real.py index a847404073aec80905a1853a8f05dd5d7c4493e9..0da1b5f6117e68a7011ea0412a2f2329d00c2f43 100644 --- a/scripts/r5/r5_build_real.py +++ b/scripts/r5/r5_build_real.py @@ -641,7 +641,7 @@ def stage_dedupe(): info["train_dropped_near_only"] = n_near_only info["train_dropped_total"] = len(drop) - # HKR vs KOHTD: any split of KOHTD (the owner's extra check); HKR train rows overlapping any KOHTD image are dropped + # HKR vs KOHTD: any split of KOHTD (the project's extra check); HKR train rows overlapping any KOHTD image are dropped hk_all = [i for i, t in enumerate(meta) if t[1] == "hkr_words" and ok[i]] ko_all = [i for i, t in enumerate(meta) if t[1] == "kohtd" and ok[i]] ko_sha = collections.defaultdict(list) diff --git a/scripts/r5_onemodel/onemodel_gate.sbatch b/scripts/r5_onemodel/onemodel_gate.sbatch index 541f861861fb5015f1e591bda4b6c357d29e9d16..3acf4fc97954d6454643376800f58c1b53295d76 100644 --- a/scripts/r5_onemodel/onemodel_gate.sbatch +++ b/scripts/r5_onemodel/onemodel_gate.sbatch @@ -8,7 +8,7 @@ #SBATCH --time=04:00:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out #SBATCH --dependency=singleton -# Single-model page training (route C), queued early at the owner's request on 25 Nov 2026 so it holds a place in the +# Single-model page training (route C), queued early on 25 Nov 2026 so it holds a place in the # H100 queue while the code is still being reviewed. It runs only reviewed code: READY lists the sha256 of every file the # review approved, and the job refuses to start if READY is missing or any listed file changed since the review. # Self-resubmission by the training code must submit THIS file again, so every segment passes the same check. diff --git a/scripts/r5_testpass2/tp2_a1lf_kohtd.sbatch b/scripts/r5_testpass2/tp2_a1lf_kohtd.sbatch index 269b7e06ad555e14a3ee567ca41bc44338024037..31f27f1b0ff7925f08a3eddd253c89ac760b604e 100644 --- a/scripts/r5_testpass2/tp2_a1lf_kohtd.sbatch +++ b/scripts/r5_testpass2/tp2_a1lf_kohtd.sbatch @@ -5,7 +5,7 @@ #SBATCH --mem=64G #SBATCH --time=06:00:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out -# Test pass 2, amendment 4 (owner-authorized): M2 (A1) label-free re-score on the KOHTD sealed test. V1 gate first (as job 55280), then +# Test pass 2, amendment 4: M2 (A1) label-free re-score on the KOHTD sealed test. V1 gate first (as job 55280), then # kohtd_test (18,615 crops) once, then the R5 scorer and the paired comparison with M1's existing 24 Nov kohtd_test predictions. set -u CODE=/path/to/TURKIC_OCR_CODE diff --git a/scripts/r5_testpass2/tp2_amend2.py b/scripts/r5_testpass2/tp2_amend2.py index 9bc7c28078390c6abe557958ab2332ff350a060d..b9e1e4fd05cc0efdbcacdd461040b87fa37e7e3d 100644 --- a/scripts/r5_testpass2/tp2_amend2.py +++ b/scripts/r5_testpass2/tp2_amend2.py @@ -1,4 +1,4 @@ -"""Appends amendment 2 (Kazakh real-document benchmark, owner-approved 25 Nov 2026) to records/R5/TESTPASS2/plan.json, before the model +"""Appends amendment 2 (Kazakh real-document benchmark, 25 Nov 2026) to records/R5/TESTPASS2/plan.json, before the model reads any of its pages. usage: tp2_amend2.py TESTPASS2_DIR """ diff --git a/scripts/r5_testpass2/tp2_amend4.py b/scripts/r5_testpass2/tp2_amend4.py index 02c526e5c057940fa67e95cff2208d0db74e6f4e..e676fa7b16e3ec1f4f94144f7983295a3c3dbcda 100644 --- a/scripts/r5_testpass2/tp2_amend4.py +++ b/scripts/r5_testpass2/tp2_amend4.py @@ -1,4 +1,4 @@ -"""Appends amendment 4 (owner-authorized label-free re-score of M2 on the KOHTD sealed test) to records/R5/TESTPASS2/plan.json, before any +"""Appends amendment 4 (label-free re-score of M2 on the KOHTD sealed test) to records/R5/TESTPASS2/plan.json, before any prediction on kohtd_test. usage: tp2_amend4.py TESTPASS2_DIR """ diff --git a/scripts/r5_testpass2/tp2_az_latin.py b/scripts/r5_testpass2/tp2_az_latin.py index a40eab79b083a6aad36d97443808c39d1e5c0477..11037a666edf65a95ddda903a6a9aec2a5fabd77 100644 --- a/scripts/r5_testpass2/tp2_az_latin.py +++ b/scripts/r5_testpass2/tp2_az_latin.py @@ -1,4 +1,4 @@ -"""Test pass 2, amendment 6 (26 Nov, owner-requested, descriptive): M1 (PaddleOCR-VL 1.6 R5 leader) on az_localdoc_test with LATIN-ONLY +"""Test pass 2, amendment 6 (26 Nov, descriptive): M1 (PaddleOCR-VL 1.6 R5 leader) on az_localdoc_test with LATIN-ONLY decoding. Identical to the test pass 2 run (eval_vlm_test.py: vlm_common prompt builder and training instruction, greedy, num_beams 1, stop ids incl. the trained answer-end token, max_new_tokens 48/192 by unit, batch 16, left padding, bf16 on CPU, manifest order) except for one logits processor that sets to -inf every vocabulary token whose decoded text contains a Cyrillic character (Unicode Script_Extensions diff --git a/scripts/r5_testpass2/tp2_kzb_card.sbatch b/scripts/r5_testpass2/tp2_kzb_card.sbatch index 9cc16ffd65f249085ac325fcbe8922dcaeaff905..5dab7c4cb7d4953ef468e1dffdf2bab5c4342c38 100644 --- a/scripts/r5_testpass2/tp2_kzb_card.sbatch +++ b/scripts/r5_testpass2/tp2_kzb_card.sbatch @@ -5,7 +5,7 @@ #SBATCH --mem=4G #SBATCH --time=00:20:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out -# Owner-approved (25 Nov 2026): pin the revision of Omar-2002/kz_benchmark_data, list its tree, fetch README.md only (no token). +# 25 Nov 2026: pin the revision of Omar-2002/kz_benchmark_data, list its tree, fetch README.md only (no token). set -u CODE=/path/to/TURKIC_OCR_CODE D=/path/to/TURKIC_OCR_DATA diff --git a/scripts/r5_testpass2/tp2_kzb_fetch.py b/scripts/r5_testpass2/tp2_kzb_fetch.py index bf5e6c101f3ee2ce19388b41bb84395b5427b2bb..c7442a3c6506af92a95daabf06f4f4b35765351a 100644 --- a/scripts/r5_testpass2/tp2_kzb_fetch.py +++ b/scripts/r5_testpass2/tp2_kzb_fetch.py @@ -1,4 +1,4 @@ -"""Test pass 2, owner-approved download (25 Nov 2026): Omar-2002/kz_benchmark_data, handwritten config only, no token. +"""Test pass 2, download (25 Nov 2026): Omar-2002/kz_benchmark_data, handwritten config only, no token. huggingface_hub 2.4.0 (CODE/.venv_dl): HfApi.dataset_info / list_repo_tree (token=False), hf_hub_download, snapshot_download (allow_patterns, local_dir, token=False). Downloaded files are untrusted data: nothing in them is executed. diff --git a/scripts/r5_testpass2/tp2_kzb_fetch.sbatch b/scripts/r5_testpass2/tp2_kzb_fetch.sbatch index 082d8064245116037c04cf4d2c76d106574ff685..2bfc2c4d3c73466200f80869695b8628f111e070 100644 --- a/scripts/r5_testpass2/tp2_kzb_fetch.sbatch +++ b/scripts/r5_testpass2/tp2_kzb_fetch.sbatch @@ -5,7 +5,7 @@ #SBATCH --mem=8G #SBATCH --time=01:00:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out -# Owner-approved (25 Nov 2026): download the handwritten config of Omar-2002/kz_benchmark_data at the pinned revision (no token) into +# 25 Nov 2026: download the handwritten config of Omar-2002/kz_benchmark_data at the pinned revision (no token) into # DATA/data/raw/kz_benchmark_hw, sha256 of every file, checksum file; then the page list and 1280 px detector copies (no model). set -u CODE=/path/to/TURKIC_OCR_CODE diff --git a/scripts/r5_vlma/testpass_runner.py b/scripts/r5_vlma/testpass_runner.py index 21bd510cf1d7af86f12e0e496cd25360add9ca6f..4d704f3872c69ab1734639ab913ad09d20e41bb4 100644 --- a/scripts/r5_vlma/testpass_runner.py +++ b/scripts/r5_vlma/testpass_runner.py @@ -26,7 +26,7 @@ evaluation tasks, the complete sets (rows not complete by 16:55 are "not run by kind vlma -> eval_vlm_test.py (.venv_vlm); kind vlmb -> CODE/scripts/r5_vlmb/vlmb_eval_vlm_testpass.py with the arm's own venv and environment (leader_cmds.py, read-only); kind cmd -> the task's argv (LINEDET's commands through -linedet_ckpt_task.sh, linedet.lm_gate, REF's test_pass_commands.sh), unchanged owner scripts. +linedet_ckpt_task.sh, linedet.lm_gate, REF's test_pass_commands.sh), unchanged scripts of those stages. usage: testpass_runner.py --config testpass_config.json --slot V --worker 0|1 [--nfile N_FILE] [--tasks FIXED_LIST.json] """ diff --git a/scripts/r5_vlmb/vlmb_runner.py b/scripts/r5_vlmb/vlmb_runner.py index b9e1d839af15419c8b4b94a5736cc70118bde407..b438c89bb0abd75c8a728ae4512dc3baff0ea4df 100644 --- a/scripts/r5_vlmb/vlmb_runner.py +++ b/scripts/r5_vlmb/vlmb_runner.py @@ -103,7 +103,7 @@ def mark(tid, **kw): # ---- shared arms across two slots (added by stage VLMC on 2026-11-21 on request) ---------------- # A queue file may name another queue file under "shared_queue": this runner also takes that file's "short" arms, after # its own list. Arms listed there, and with "claim_own": true this runner's own arms, run only once across slots: the -# runner that starts an arm first creates DATA/outputs/r5/vlmb/claims/.json atomically (O_CREAT|O_EXCL, owner = +# runner that starts an arm first creates DATA/outputs/r5/vlmb/claims/.json atomically (O_CREAT|O_EXCL, holder = # slot name, so a restarted job of the same slot keeps its claim); any other slot skips that arm and counts it as # finished for exit_when_done. A queue file without these keys behaves exactly as before. CLAIMS = os.path.join(V, "claims") diff --git a/scripts/release2/decisions.json b/scripts/release2/decisions.json index 46ec5e5087857f4b83a7a80e6ea8a245fcb7192e..664e24319d5392992d81284632c8d8ed3606c15e 100644 --- a/scripts/release2/decisions.json +++ b/scripts/release2/decisions.json @@ -1,21 +1,21 @@ { - "status": "used by job C (rel2_build_data.py); decided 2026-11-25 from records/R5/RELEASE2/work/licence_evidence.json", + "status": "Input of rel2_build_data.py: the text sources the released data may use, their licence labels, and the texts written as LICENSE, attribution/notices.json and the notice of the real-print pointer list.", "text_source_kinds_allowed": { "wiki": true, "fw2": true, "ailab": false }, - "why_ailab_excluded": "The Sakha newspaper sentences (ailabykt/sakha-corpus-mono, sources kyym, eder_saas, sakha_sire, uluus_media) carry CC BY 4.0 on the corpus card, but the newspapers' own sites require a hyperlink to the source for any reuse and Ulus Media requires prior written consent and limits use to personal non-commercial purposes. The corpus rows hold no article links, so the hyperlink condition cannot be met per item, and the consent condition is not met. Conservative default: excluded; the owner may re-include kyym, eder_saas and sakha_sire after deciding that a site-level link satisfies their terms.", + "why_ailab_excluded": "The Sakha newspaper sentences (ailabykt/sakha-corpus-mono, sources kyym, eder_saas, sakha_sire, uluus_media) carry CC BY 4.0 on the corpus card, but the newspapers' own sites require a hyperlink to the source for any reuse and Ulus Media requires prior written consent and limits use to personal non-commercial purposes. The corpus rows hold no article links, so the hyperlink condition cannot be met per item, and the consent condition is not met. These sentences are therefore excluded.", "text_licence_label": { "wiki": "CC-BY-SA-4.0 (Wikipedia text)", "fw2": "ODC-By-1.0 (FineWeb-2; Common Crawl terms of use apply)", "ailab": "CC-BY-4.0 corpus card; newspaper terms apply (not released)" }, "extra_exclusions_json": "/path/to/TURKIC_OCR_DATA/tmp/release2/sakha_check.json", - "why_extra_exclusions": "rel2_sakha_check.py (job 55414) found released Sakha items whose label text occurs exactly (6 items) or as a 3-word window (363 more) in a newspaper sentence drawn for their page, although their line attribution named no newspaper document; all 369 are excluded (conservative; window matches can be coincidences).", + "why_extra_exclusions": "rel2_sakha_check.py found released Sakha items whose label text occurs exactly (6 items) or as a 3-word window (363 more) in a newspaper sentence drawn for their page, although their line attribution named no newspaper document; all 369 are excluded (conservative; window matches can be coincidences).", "build_print_pointers": true, - "pointer_notice_text": "Real-print pointer list (release candidate; publishing it is an owner decision)\n\nWHAT THIS IS\nOne row per real printed text line that the project cut from born-digital PDFs for training (train) and validation (val): our line id, language, script, split, document id, source, the PDF's URL, a fingerprint of the PDF we fetched, the page number, our line box in PDF points (x0,y0,x1,y1), the render DPI and padding we used, a fingerprint of our crop and a fingerprint of the NFC label. No image and no text of any PDF is included. The test documents are not listed.\n\nSOURCES AND TERMS\nContains information from FinePDFs (HuggingFaceFW/finepdfs), which is made available under the Open Data Commons Attribution License (ODC-By) 1.0; use of FinePDFs is also subject to the Common Crawl terms of use. Turkish lines also come from minutes of the Grand National Assembly of Turkey (tbmm.gov.tr).\nEvery PDF remains under its owner's rights; this list grants no right to the PDFs or their content. To rebuild a line, fetch the PDF from its URL, check it against that fingerprint, render the page at the listed DPI and cut the listed box.\nThe line boxes, ids and fingerprints are the project's own work; the licence for them is chosen by the owner before publication.\n", - "licence_file_text": "Turkic OCR generated data, release candidate rc1_data (page generator pagesynth 0.3.0, round R5, frozen 21 Nov 2026)\n\nLICENCE\nThis package is licensed under the Creative Commons Attribution-ShareAlike 4.0 International licence (CC BY-SA 4.0):\nhttps://creativecommons.org/licenses/by-sa/4.0/legalcode\nLicensor: the authors of this release (the owner names them before publication).\n\nWHY SHARE-ALIKE\nThe label texts, and the text drawn in the images, are sentences and words taken from Wikipedia (CC BY-SA) and from FineWeb-2 (ODC-By 1.0, built from Common Crawl).\nMaterial adapted from Wikipedia must be shared under CC BY-SA 4.0 or a compatible licence; one licence is used for the whole package so that every item is covered.\nWikipedia text contributed before 7 June 2023 is under CC BY-SA 3.0, whose ShareAlike clause allows adaptations under a later version with the same licence elements (CC BY-SA 3.0 legal code, section 4(b)(ii)); Wikipedia text is also available under the GFDL.\n\nATTRIBUTION (required by the sources; lists in the folder attribution/)\n- Wikipedia: every article whose text appears in a released label is listed by language and page id with its URL in attribution/wikipedia_articles.tsv. Text of Wikipedia, the free encyclopedia, by its contributors, CC BY-SA.\n- FineWeb-2 (HuggingFaceFW/fineweb-2), ODC-By 1.0: every source document is listed by its FineWeb-2 id in attribution/fineweb2_documents.tsv. The underlying web pages remain under their authors' rights; use of FineWeb-2 is subject to the Common Crawl terms of use.\n- Fonts: the images were rendered with fonts under the SIL Open Font License 1.1 or the Apache License 2.0 only (attribution/fonts_used.tsv); the fonts themselves are not included. No font of a personal-use licence was drawn on any page of a released item.\n- Maps: Natural Earth vector data (public domain).\n- Paper constants were measured on scans of Zenodo record 15479725 (CC BY 4.0); no pixel of those scans is in any image.\n\nCHANGES\nSentences were cleaned and split by source document, wrapped into lines and drawn as synthetic handwriting and print on synthetic pages, then degraded to look scanned or photographed. Every step is described in datasheet.json.\n\nNO WARRANTY\nThe material is provided as is, without warranties of any kind. The images contain no real person's handwriting; the texts are unfiltered web and encyclopedia sentences and can contain names of real people.\n", + "pointer_notice_text": "Real-print pointer list\n\nWHAT THIS IS\nOne row per real printed text line that the project cut from born-digital PDFs for training (train) and validation (val). The columns include our line id, language, script, split, document id, source, the PDF's URL, the page number, our line box in PDF points (x0,y0,x1,y1), and the render DPI and padding we used. No image and no text of any PDF is included. The test documents are not listed.\n\nSOURCES AND TERMS\nContains information from FinePDFs (HuggingFaceFW/finepdfs), which is made available under the Open Data Commons Attribution License (ODC-By) 1.0; use of FinePDFs is also subject to the Common Crawl terms of use. Turkish lines also come from minutes of the Grand National Assembly of Turkey (tbmm.gov.tr).\nEvery PDF remains under the rights of its rights holders; this list grants no right to the PDFs or their content. To rebuild a line, fetch the PDF from its URL, render the page at the listed DPI and cut the listed box.\nThe line boxes and ids are the project's own work.\n", + "licence_file_text": "Turkic OCR generated data (page generator pagesynth 0.3.0, frozen 21 Nov 2026)\n\nLICENCE\nThis package is licensed under the Creative Commons Attribution-ShareAlike 4.0 International licence (CC BY-SA 4.0):\nhttps://creativecommons.org/licenses/by-sa/4.0/legalcode\nLicensor: the authors of the project report.\nCopyright 2026 the authors of the project report.\nCite as: A Handwriting Recognition Model for Turkic Languages in Latin and Cyrillic Script. Project report, Nazarbayev University, 2026.\n\nWHY SHARE-ALIKE\nThe label texts, and the text drawn in the images, are sentences and words taken from Wikipedia (CC BY-SA) and from FineWeb-2 (ODC-By 1.0, built from Common Crawl).\nMaterial adapted from Wikipedia must be shared under CC BY-SA 4.0 or a compatible licence; one licence is used for the whole package so that every item is covered.\nWikipedia text contributed before 7 June 2023 is under CC BY-SA 3.0, whose ShareAlike clause allows adaptations under a later version with the same licence elements (CC BY-SA 3.0 legal code, section 4(b)(ii)); Wikipedia text is also available under the GFDL.\n\nATTRIBUTION (required by the sources; lists in the folder attribution/)\n- Wikipedia: every article whose text appears in a released label is listed by language and page id with its URL in attribution/wikipedia_articles.tsv. Text of Wikipedia, the free encyclopedia, by its contributors, CC BY-SA.\n- FineWeb-2 (HuggingFaceFW/fineweb-2), ODC-By 1.0: every source document is listed by its FineWeb-2 id in attribution/fineweb2_documents.tsv. The underlying web pages remain under their authors' rights; use of FineWeb-2 is subject to the Common Crawl terms of use.\n- Fonts: the images were rendered with fonts under the SIL Open Font License 1.1 or the Apache License 2.0 only (attribution/fonts_used.tsv); the fonts themselves are not included. No font of a personal-use licence was drawn on any page of a released item.\n- Maps: Natural Earth vector data (public domain).\n- Paper constants were measured on scans of Zenodo record 15479725 (CC BY 4.0); no pixel of those scans is in any image.\n\nCHANGES\nSentences were cleaned and split by source document, wrapped into lines and drawn as synthetic handwriting and print on synthetic pages, then degraded to look scanned or photographed. Every step is described in datasheet.json.\n\nNO WARRANTY\nThe material is provided as is, without warranties of any kind. The images contain no real person's handwriting; the texts are unfiltered web and encyclopedia sentences and can contain names of real people.\n", "notices": { "wikipedia": "Text from Wikipedia (dump 20231101 of the kk, ky, uz, tt, ba, sah, tr, az and tk editions, read through the Hugging Face dataset wikimedia/wikipedia), CC BY-SA; article list with URLs in wikipedia_articles.tsv.", "fineweb2": "Text from FineWeb-2 (HuggingFaceFW/fineweb-2, configs kaz_Cyrl, kir_Cyrl, uzn_Cyrl, uzn_Latn, tat_Cyrl, bak_Cyrl, sah_Cyrl, tur_Latn, azj_Latn, tuk_Latn), Open Data Commons Attribution License (ODC-By) 1.0; subject to the Common Crawl terms of use; document ids in fineweb2_documents.tsv.", diff --git a/scripts/release2/rel2_build_data.py b/scripts/release2/rel2_build_data.py index 6b5958eb5cdd1796a6eb2fac00302e4101da272a..beb684e92d86ceb1de824b3d5ddd1452e4c3edd3 100644 --- a/scripts/release2/rel2_build_data.py +++ b/scripts/release2/rel2_build_data.py @@ -16,7 +16,7 @@ Rules applied per item (all must pass, otherwise the item is excluded and counte Outputs hand|typed|clutter////.jpg, pages///.{jpg,json,xml} (PageXML 2019-07-15) labels/_.jsonl and .tsv, excluded/excluded_items.tsv, excluded/exclusion_counts.json, - attribution/*.tsv, LICENSE, real_print_pointers/*.tsv (owner decides whether to publish), build_report.json, SHA256SUMS + attribution/*.tsv, LICENSE, real_print_pointers/*.tsv (whether to publish them is decided separately), build_report.json, SHA256SUMS usage: CODE/.venv_gen/bin/python -I rel2_build_data.py --decisions decisions.json --out DATA/release/rc1_data --threads 8 """ import argparse @@ -506,7 +506,7 @@ def main(): r.get("page", ""), r.get("dpi", ""), r.get("pad", ""), ",".join(str(v) for v in r.get("bbox_pt", [])), r.get("size_pt", ""), r.get("sha256", ""), lab))) pointer_counts[sp] += 1 - # separate package (owner decision D7): its own notice and checksums, outside the CC BY-SA data package + # separate package (project decision D7): its own notice and checksums, outside the CC BY-SA data package PO = OUT.rstrip("/") + "_print_pointers" if not dec.get("pointer_dir") else dec["pointer_dir"] os.makedirs(PO, exist_ok=True) psums = {} diff --git a/scripts/release2/rel2_d5_data.sbatch b/scripts/release2/rel2_d5_data.sbatch index d55949e6c659b4e08682bcbf52dc8c74a4c03352..c7d06b819082c2b4616972659e6e1fa63e66972d 100644 --- a/scripts/release2/rel2_d5_data.sbatch +++ b/scripts/release2/rel2_d5_data.sbatch @@ -7,7 +7,7 @@ #SBATCH --mem=8G #SBATCH --time=01:00:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out -# RELEASE2 D5 finish, data packages: owner decisions of 26 Nov 2026 (D1/D2: real data sets cited with where to obtain them; D8: licensor, +# RELEASE2 D5 finish, data packages: project decisions of 26 Nov 2026 (D1/D2: real data sets cited with where to obtain them; D8: licensor, # copyright line and citation). Replaces datasheet.json and LICENSE in DATA/release/rc1_data and DATA/release/rc1_data_parquet, updates # their two SHA256SUMS lines the way rel2_decide (job 55668) did, verifies every file in full and checks that no file is outside the sums. # Preconditions (abort with nothing changed): the installed datasheet and LICENSE are the expected files; the staged files have the diff --git a/scripts/release2/rel2_d5_detector_retrain.sbatch b/scripts/release2/rel2_d5_detector_retrain.sbatch index 4a5a0e6b940387a8dd977114a6c9c19118a1df84..8bcbc4aae6bf48d903d66dcb2a507f06c42247cf 100644 --- a/scripts/release2/rel2_d5_detector_retrain.sbatch +++ b/scripts/release2/rel2_d5_detector_retrain.sbatch @@ -7,7 +7,7 @@ #SBATCH --mem=96G #SBATCH --time=04:00:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out -# RELEASE2, owner decision D5 (25 Nov 2026): retrain the stage-2 line detector WITHOUT the 83 generated train pages that carry a +# RELEASE2, project decision D5 (25 Nov 2026): retrain the stage-2 line detector WITHOUT the 83 generated train pages that carry a # personal-use font, then release it under AGPL-3.0. NOT SUBMITTED by RELEASE2; it queues after the current GPU work. # Spec: records/R5/RELEASE2/d5/d5_retrain_spec.json. Same recipe as the released stage 2 (yolo_s2, args.yaml): start from our stage-1 # weights yolo_s1c/weights/best.pt (trained on School Notebooks pages only, no generated page), image size 1280, batch 16, 200 epochs diff --git a/scripts/release2/rel2_d5_prep.py b/scripts/release2/rel2_d5_prep.py index 7cf22299e73aa7d17e88ec0463270367f66e6460..eb9d0fe2af324dd11f60161213b065a8d8d15c1c 100644 --- a/scripts/release2/rel2_d5_prep.py +++ b/scripts/release2/rel2_d5_prep.py @@ -1,4 +1,4 @@ -"""RELEASE2 owner decisions D4 and D5 (25 Nov 2026), CPU part. Nothing is trained here. +"""RELEASE2 project decisions D4 and D5 (25 Nov 2026), CPU part. Nothing is trained here. D5: build the stage-2 detector training set without the 83 generated train pages that carry a personal-use font: DATA/data/processed/r5_linedet_det/gen_d5/train/{images,labels} copies of the 3,916 remaining generated train pages (image + YOLO label) diff --git a/scripts/release2/rel2_d5_prep.sbatch b/scripts/release2/rel2_d5_prep.sbatch index f8751c74bd0c4311333e31480c885d1eb6edf720..287d7b5c5422d20619e412bcbc0a1434b4119d60 100644 --- a/scripts/release2/rel2_d5_prep.sbatch +++ b/scripts/release2/rel2_d5_prep.sbatch @@ -7,7 +7,7 @@ #SBATCH --mem=16G #SBATCH --time=00:40:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out -# RELEASE2 owner decisions (25 Nov 2026): D5 data preparation and D4 page counts (rel2_d5_prep.py), and the licence texts the packages +# RELEASE2 project decisions (25 Nov 2026): D5 data preparation and D4 page counts (rel2_d5_prep.py), and the licence texts the packages # must ship (downloaded as plain text into DATA/tmp/release2/licence_texts/, never executed; sha256 recorded). set -u D=/path/to/TURKIC_OCR_DATA diff --git a/scripts/release2/rel2_decisions_install.sbatch b/scripts/release2/rel2_decisions_install.sbatch index 14914afada0c2e32f36eb42bc10fa551ec5de57b..83b95971174a71a1d1faed0f8b5dcd59f3024c6c 100644 --- a/scripts/release2/rel2_decisions_install.sbatch +++ b/scripts/release2/rel2_decisions_install.sbatch @@ -7,7 +7,7 @@ #SBATCH --mem=8G #SBATCH --time=01:00:00 #SBATCH --output=/path/to/TURKIC_OCR_DATA/logs/%x_%j.out -# RELEASE2: install the owner decisions of 25 Nov 2026 into the release folders. No weight changes. +# RELEASE2: install the project decisions of 25 Nov 2026 into the release folders. No weight changes. # packages: new model_card.json; LICENSE / NOTICE; licence texts (LICENSE.Apache-2.0 for the readers, LICENSE.base-model for PaddleOCR-VL, # LICENSE = AGPL-3.0 text for detector and page pipeline); SHA256SUMS rewritten and verified; weights hashed before and after. # data: the updated datasheet.json into rc1_data and rc1_data_parquet; their SHA256SUMS updated and verified in full. diff --git a/scripts/release2/rel2_parquet.py b/scripts/release2/rel2_parquet.py index 9a535c0c2c6ba48995cdc0a32e00db139a79eac2..eb4e5fa33f78d482c4cc8fe14eaff01d38f0c6ea 100644 --- a/scripts/release2/rel2_parquet.py +++ b/scripts/release2/rel2_parquet.py @@ -1,4 +1,4 @@ -"""RELEASE2 owner decision D9 (25 Nov 2026): the generated-data package as Parquet shards with embedded images. +"""RELEASE2 project decision D9 (25 Nov 2026): the generated-data package as Parquet shards with embedded images. Input : DATA/release/rc1_data (labels/_.jsonl, the images, SHA256SUMS, LICENSE, attribution/, excluded/, build_report.json) Output: DATA/release/rc1_data_parquet/ diff --git a/src/pagesynth/pagesynth/fonts.py b/src/pagesynth/pagesynth/fonts.py index d524263b387b0566aba5bdbf357c69f2746c0188..c3e30debd4c5f2bac496443561c606675b091c2d 100644 --- a/src/pagesynth/pagesynth/fonts.py +++ b/src/pagesynth/pagesynth/fonts.py @@ -20,13 +20,13 @@ apostrophe (U+02BC): the font's own U+2018/U+2019 or the ASCII apostrophe is drawn and the LABEL is changed to the drawn mark (orig text is kept in the page JSON). -Licence classes: ofl, apache2 (open), personal_use_only (the owner's Latin signature fonts: -"personal use only" or "demo"). R5 (20 Nov 2026): the owner allows these eight for TRAINING data; +Licence classes: ofl, apache2 (open), personal_use_only (the project's Latin signature fonts: +"personal use only" or "demo"). R5 (20 Nov 2026): these eight are allowed for TRAINING data; they are never shown on the pages or shipped (display mode drops them: include_personal=False). FONT WEIGHTS (R5, generator 0.3.0): every handwriting font gets the same weight (w = 1.0 for each script it may be used for). The older comment "Caveat and Bad Script highest, Pacifico low, Shantell Sans lowest" is -superseded by the owner's instruction of 21 Nov 2026 (Caveat and Bad Script had 81 percent of the Cyrillic +superseded by the decision of 21 Nov 2026 (Caveat and Bad Script had 81 percent of the Cyrillic handwriting lines in pilot v0.2.0). A font is still drawn only for sentences that it fully covers (layouts.choose_writer rejects a font that draws fewer than 35 percent of the language's sentences), so the share of a font in a language is its weight divided by the weights of the fonts that cover that diff --git a/src/pagesynth/pagesynth/langtext.py b/src/pagesynth/pagesynth/langtext.py index 0037caf8f12eca3cbb5d7479310a63d65bd0ae7c..d46fad4699fa08c629e8accd3656a05a7c0ae5a6 100644 --- a/src/pagesynth/pagesynth/langtext.py +++ b/src/pagesynth/pagesynth/langtext.py @@ -1,6 +1,6 @@ """Counting words of the page language in drawn lines (shared by the h_language_text gate and the audit). -Why a shared module: the owner's complaint (20 Nov 2026) was that figures carried only numbers and +Why a shared module: figures must carry words of the page language, not only numbers and symbols. The audit and the gate must therefore count the same thing, otherwise "before" and "after" numbers are not comparable. diff --git a/src/pagesynth/pagesynth/scenes.py b/src/pagesynth/pagesynth/scenes.py index 34872ddf9c396cba1496a910fb53832a9b122026..56794097d6a16b639e373a8ba2663b5a4a546ff1 100644 --- a/src/pagesynth/pagesynth/scenes.py +++ b/src/pagesynth/pagesynth/scenes.py @@ -661,7 +661,7 @@ def scene_worksheet(page, paper, layout, rng, bank, lang, include_personal, tabl def _table(page, paper, layout, rng, bank, lang, pw, hw, y, x0, x1, big=False): """Ruled table with a printed header row of words and hand-filled cells. Column 0 holds words (row labels, one or two vocabulary words per cell, never empty); every other column holds words or numbers. A table of only numbers is not - drawn: it would carry no text of the language (owner, 20 Nov 2026).""" + drawn: it would carry no text of the language.""" Wf, Hf = page.Wf, page.Hf n_cols = int(rng.integers(3 if big else 2, 7 if big else 5)) n_rows = int(rng.integers(6 if big else 3, 14 if big else 6)) diff --git a/src/pagesynth/pagesynth/vocab.py b/src/pagesynth/pagesynth/vocab.py index 1cecd75e9f074227028d3a5790779f40c8e11469..70d2b21f6b3d2bba42ce511fa1104dd4bc457f79 100644 --- a/src/pagesynth/pagesynth/vocab.py +++ b/src/pagesynth/pagesynth/vocab.py @@ -1,6 +1,6 @@ """Label vocabulary: lower-case words of the language's own corpus for the word labels of figures, tables and maps. -Why: a figure needs words in the page language (owner, 20 Nov 2026), and no word may be invented or +Why: a figure needs words in the page language, and no word may be invented or translated here. The words are the frequency-ranked lower-case words of the corpus (scripts/build_label_vocab.py): * 3 to 12 letters, every letter in the language's own alphabet, no digits, no hyphen, no Russian function word; * lower-case only: a word counts only if it is (almost) never written with a capital in the middle of a diff --git a/src/rq2/aug.py b/src/rq2/aug.py index de170605034442ff947658825119ff01071cb144..d99e335fc41004c68307dc7dbd96c4f60e741dc0 100644 --- a/src/rq2/aug.py +++ b/src/rq2/aug.py @@ -7,10 +7,10 @@ Random numbers: one generator per training sample, numpy default_rng([seed, 4242 fixed and the same in both policies: slot u = integers(0, 7), then z1 = random(), z2 = random(); each policy maps (z1, z2) to its own parameter range, so the same sample gets the same slot and the same relative magnitude in all four arms of a seed. -Typical = TrOCR build_data_aug(mode='train') (microsoft/unilm trocr/data_aug.py @ 581af18, torchvision 0.8.2 defaults); the -constants and their line numbers are in records/R5/RQ2/trocr_policy.json. +Typical = TrOCR build_data_aug(mode='train') (microsoft/unilm trocr/data_aug.py, torchvision 0.8.2 defaults); the +constants below are copied from that file. Safe = proposal section 5 as read by the design: rotation within +-2 deg (and never forcing a downscale below 0.75x), blur -sigma <= H/64, shear +-0.5 DEGREES (owner decision 2026-11-26), 2x2 thickening at 64 px only, downscale >= 0.75x, translation +sigma <= H/64, shear +-0.5 DEGREES, 2x2 thickening at 64 px only, downscale >= 0.75x, translation by padding; it never thins strokes. """ import math diff --git a/tests/data/sample_eval/evalsets.json b/tests/data/sample_eval/evalsets.json new file mode 100644 index 0000000000000000000000000000000000000000..0e339794e674bf7dfd53b028387a688dd0b813f2 --- /dev/null +++ b/tests/data/sample_eval/evalsets.json @@ -0,0 +1,7 @@ +{ + "registry_version": "sample", + "sets": [ + {"name": "sample_lines", "manifest": "tests/data/sample_eval/manifests/sample_lines.tsv", "split": "val", "locked": false, + "group_unit": "page"} + ] +} diff --git a/tests/data/sample_eval/manifests/sample_lines.tsv b/tests/data/sample_eval/manifests/sample_lines.tsv new file mode 100644 index 0000000000000000000000000000000000000000..c1a17aff328f3d8570cc0f8cefe37b5543ba0dc4 --- /dev/null +++ b/tests/data/sample_eval/manifests/sample_lines.tsv @@ -0,0 +1,11 @@ +id image text lang script kind source split group unit +sample:01 images/sample_01.png Мектеп ауласында бәйтерек өседі kk Cyrl hand_synth sample val page_1 line +sample:02 images/sample_02.png Қазақ тілі сабағы басталды kk Cyrl hand_synth sample val page_1 line +sample:03 images/sample_03.png Біз кітапханаға бардық kk Cyrl hand_synth sample val page_2 line +sample:04 images/sample_04.png Бүгүн аба ырайы жакшы ky Cyrl hand_synth sample val page_2 line +sample:05 images/sample_05.png Казан шәһәре зур tt Cyrl hand_synth sample val page_3 line +sample:06 images/sample_06.png Öğrenciler bahçede oynuyor tr Latn hand_synth sample val page_3 line +sample:07 images/sample_07.png Bakı dənizin sahilindədir az Latn hand_synth sample val page_4 line +sample:08 images/sample_08.png Toshkent katta shahar uz Latn hand_synth sample val page_4 line +sample:09 images/sample_09.png Aşgabat ak mermerden gurlan tk Latn hand_synth sample val page_5 line +sample:10 images/sample_10.png Саха сирэ кэрэ sah Cyrl hand_synth sample val page_5 line diff --git a/tests/data/sample_eval/preds/demo/final/sample_lines.tsv b/tests/data/sample_eval/preds/demo/final/sample_lines.tsv new file mode 100644 index 0000000000000000000000000000000000000000..c17b7dcc31fb9dcf4401e19e34642945b6a93076 --- /dev/null +++ b/tests/data/sample_eval/preds/demo/final/sample_lines.tsv @@ -0,0 +1,11 @@ +id ref hyp +sample:01 Мектеп ауласында бәйтерек өседі Мектеп ауласында байтерек өседі +sample:02 Қазақ тілі сабағы басталды Казак тілі сабағы басталды +sample:03 Біз кітапханаға бардық Біз кітапханаға бардық +sample:04 Бүгүн аба ырайы жакшы Бүгүн аба ырайы жакшы +sample:05 Казан шәһәре зур Казан шэһэре зур +sample:06 Öğrenciler bahçede oynuyor Ogrenciler bahçede oynuyor +sample:07 Bakı dənizin sahilindədir Baki dənizin sahilindədir +sample:08 Toshkent katta shahar Toshkent kata shahar +sample:09 Aşgabat ak mermerden gurlan Aşgabat ak mermerden gurlan. +sample:10 Саха сирэ кэрэ Саха сирэ кэрэ diff --git a/tests/test_edit_distance.py b/tests/test_edit_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..91e5e387dfe60901f783e8128f46b208d3c41d5b --- /dev/null +++ b/tests/test_edit_distance.py @@ -0,0 +1,57 @@ +"""Edit distance: the scorer's alignment (r5eval.align) against the reference implementation in r5eval/frozen.""" +import random + +import pytest + +from r5eval import align +from r5eval.frozen import j2 + + +def counts(ref: str, hyp: str) -> tuple[int, int, int, int]: + """Distance, substitutions, deletions and insertions from align_ops.""" + dist, ops = align.align_ops(ref, hyp) + return (dist, *align.op_counts(ops)) + + +@pytest.mark.parametrize( + "ref, hyp, expected", + [ + ("kitten", "sitting", (3, 2, 0, 1)), + ("қазақ", "казак", (2, 2, 0, 0)), + ("Toshkent katta", "Toshkent kata", (1, 0, 1, 0)), + ("abc", "abc", (0, 0, 0, 0)), + ("", "ab", (2, 0, 0, 2)), + ("ab", "", (2, 0, 2, 0)), + ], +) +def test_align_ops_counts(ref, hyp, expected): + assert counts(ref, hyp) == expected + assert j2.align(ref, hyp) == expected + + +def test_align_ops_lists_every_character(): + dist, ops = align.align_ops("бала", "бала!") + assert dist == 1 + assert [o for o, _, _ in ops] == ["M", "M", "M", "M", "I"] + + +def test_fast_distance_matches_alignment_on_random_pairs(): + rnd = random.Random(7) + letters = "аәбғқңөұүһіклмнопрс" + for _ in range(300): + a = "".join(rnd.choice(letters) for _ in range(rnd.randint(0, 20))) + b = "".join(rnd.choice(letters) for _ in range(rnd.randint(0, 20))) + assert align.lev_fast(a, b) == align.align_ops(a, b)[0] == j2.align(a, b)[0] + + +def test_line_assignment_pairs_lines_in_any_order(): + total, pairs = align.min_cost_line_assignment(["abc", "de"], ["de", "abd"]) + assert total == 1 + assert sorted(pairs) == [(0, 1), (1, 0)] + + +def test_crop_cer_is_distance_over_reference_length(): + s = j2.score_crop("Сәлем әлем", "Сэлем әлем") + assert s["ref"] == "Сәлем әлем" + assert s["dist"] == 1 + assert s["cer"] == pytest.approx(1 / 10) diff --git a/tests/test_lookalike.py b/tests/test_lookalike.py new file mode 100644 index 0000000000000000000000000000000000000000..74f938f3b3789ddecad0cba2179d32808acfabfb --- /dev/null +++ b/tests/test_lookalike.py @@ -0,0 +1,31 @@ +"""Look-alike repair of references (r5eval.lookalike): Latin and Cyrillic letters that look the same.""" +from r5eval import lookalike + + +def test_cyrillic_reference_with_one_latin_letter_is_repaired(): + text, changes = lookalike.repair_label("мектeп бала", "Cyrl") + assert text == "мектеп бала" + assert changes == [("мектeп", "мектеп")] + + +def test_latin_reference_with_one_cyrillic_letter_is_repaired(): + text, _ = lookalike.repair_label("Toshkеnt", "Latn") + assert text == "Toshkent" + + +def test_token_of_the_other_script_is_left_alone(): + text, changes = lookalike.repair_label("Toshkеnt", "Cyrl") + assert text == "Toshkеnt" + assert changes == [] + + +def test_whitespace_is_kept(): + text, _ = lookalike.repair_label("a b\tc", "Cyrl") + assert text == "a b\tc" + + +def test_shipped_table_matches_the_code(): + with open(lookalike.table_path(), encoding="utf-8") as f: + assert f.read() == lookalike.table_tsv() + assert lookalike.PARTNER["ə"] == "ә" + assert lookalike.PARTNER["ә"] == "ə" diff --git a/tests/test_sample_eval.py b/tests/test_sample_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..79f434b46a43574b673a243a51bb928c8a12b614 --- /dev/null +++ b/tests/test_sample_eval.py @@ -0,0 +1,31 @@ +"""Runs the scorer on the bundled sample, as `make sample-eval` does, and checks the character error rate.""" +import json +import os +import subprocess +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SAMPLE = os.path.join("tests", "data", "sample_eval") + + +def run_scorer(out_dir: str) -> subprocess.CompletedProcess: + """Score the sample predictions into out_dir from the repository root.""" + cmd = [sys.executable, os.path.join("scripts", "r5eval", "score.py"), + "--preds", os.path.join(SAMPLE, "preds"), "--registry", os.path.join(SAMPLE, "evalsets.json"), + "--out", out_dir, "--B", "1000", "--settle", "0"] + return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True) + + +def test_sample_cer(tmp_path): + p = run_scorer(str(tmp_path)) + assert p.returncode == 0, p.stdout + p.stderr + with open(tmp_path / "demo" / "final" / "sample_lines.json", encoding="utf-8") as f: + score = json.load(f) + cer = score["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"] + # 10 edits over 229 reference characters (see the prediction file) + assert (cer["num"], cer["den"]) == (10, 229) + assert cer["value"] == pytest.approx(10 / 229) + assert cer["lo"] <= cer["value"] <= cer["hi"] + assert (tmp_path / "summary.tsv").exists() diff --git a/tests/test_textnorm.py b/tests/test_textnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..4f0f7195623232c05a14c1042181c73e4df14584 --- /dev/null +++ b/tests/test_textnorm.py @@ -0,0 +1,35 @@ +"""Text normalisation and script tests used by the scorer (r5eval.textnorm).""" +from r5eval import textnorm as tn + + +def test_norm_composes_and_collapses_whitespace(): + assert tn.norm(" Сәлем\n\t әлем ") == "Сәлем әлем" + assert tn.norm("é") == "é" + + +def test_turkish_and_azerbaijani_case_fold(): + assert tn.fold_lower("ISTANBUL", "tr") == "ıstanbul" + assert tn.fold_lower("İzmir", "az") == "izmir" + assert tn.fold_lower("ISTANBUL") == "istanbul" + + +def test_key_keeps_only_letters_and_digits(): + assert tn.n1_key("Қазақстан, 2026!", "kk") == "қазақстан2026" + + +def test_other_script_flags_letters_outside_latin_and_cyrillic(): + assert not tn.other_script("Привет, world") + assert tn.other_script("Ελλάδα") + assert not tn.other_script("Oʻzbekiston") + + +def test_mixed_script_token(): + mixed = "мектeп" # Latin e inside a Cyrillic word + assert tn.is_mixed_script(mixed) + assert not tn.is_mixed_script("мектеп") + assert tn.latin_cyrillic_counts(mixed) == (1, 5) + + +def test_base_letter_strips_marks(): + assert tn.base_letter("ç") == "c" + assert tn.base_letter("ı") == "ı"