Add setup, tests and results; update repository text
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- .gitignoreAdded+36
- MakefileAdded+22
- NOTICE+5-5
- READMEDeleted-224
- README.md+194-226
- pyproject.tomlAdded+16
- release/page-pipeline/infer.py+6-6
- release/page-pipeline/requirements.txt+4-4
- release/turkic-line-detector-yolo11s/infer.py+2-2
- release/turkic-line-detector-yolo11s/requirements.txt+2-2
- release/turkic-ocr-paddleocr-vl-1.6/infer.py+2-2
- release/turkic-ocr-paddleocr-vl-1.6/requirements.txt+2-2
- release/turkic-ocr-ppocrv6-medium/infer.py+5-5
- release/turkic-ocr-ppocrv6-medium/requirements.txt+2-2
- release/turkic-ocr-qwen3-vl-2b/infer.py+2-2
- release/turkic-ocr-qwen3-vl-2b/requirements.txt+2-2
- requirements.txtAdded+18
- results/figures/fig1_overview.pngAdded
- results/figures/fig2_results.pngAdded
- results/figures/fig3_forgetting.pngAdded
- results/metrics.csvAdded+23
- scripts/r5/r5_build_real.py+1-1
- scripts/r5_onemodel/onemodel_gate.sbatch+1-1
- scripts/r5_testpass2/tp2_a1lf_kohtd.sbatch+1-1
- scripts/r5_testpass2/tp2_amend2.py+1-1
- scripts/r5_testpass2/tp2_amend4.py+1-1
- scripts/r5_testpass2/tp2_az_latin.py+1-1
- scripts/r5_testpass2/tp2_kzb_card.sbatch+1-1
- scripts/r5_testpass2/tp2_kzb_fetch.py+1-1
- scripts/r5_testpass2/tp2_kzb_fetch.sbatch+1-1
- scripts/r5_vlma/testpass_runner.py+1-1
- scripts/r5_vlmb/vlmb_runner.py+1-1
- scripts/release2/decisions.json+5-5
- scripts/release2/rel2_build_data.py+2-2
- scripts/release2/rel2_d5_data.sbatch+1-1
- scripts/release2/rel2_d5_detector_retrain.sbatch+1-1
- scripts/release2/rel2_d5_prep.py+1-1
- scripts/release2/rel2_d5_prep.sbatch+1-1
- scripts/release2/rel2_decisions_install.sbatch+1-1
- scripts/release2/rel2_parquet.py+1-1
- src/pagesynth/pagesynth/fonts.py+3-3
- src/pagesynth/pagesynth/langtext.py+1-1
- src/pagesynth/pagesynth/scenes.py+1-1
- src/pagesynth/pagesynth/vocab.py+1-1
- src/rq2/aug.py+3-3
- tests/data/sample_eval/evalsets.jsonAdded+7
- tests/data/sample_eval/manifests/sample_lines.tsvAdded+11
- tests/data/sample_eval/preds/demo/final/sample_lines.tsvAdded+11
- tests/test_edit_distance.pyAdded+57
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textresults/figures/fig1_overview.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536# 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/12345678910111213141516171819202122PYTHON ?= python3.12VENV ?= .venvPY = $(VENV)/bin/pythonSAMPLE_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.json112334565678939 unmodified lines4950515252535455Turkic 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 KadirbekovaCopyright 2026 the authors of the project report
Cite as: Suleimenov, A., Bolatov, Z., Baglanova, A., Zhumabay, A., Kadirbekova, A. (2026). A Handwriting RecognitionModel 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, NazarbayevUniversity, 2026.
LICENCES39 unmodified lines
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.0The 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/ thatscripts/r5_ref/ref_common.py sets (PPOCR_ROOT); it is not included.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224TURKIC 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-datamanifests 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, thetest-pass and page-scoring scripts, the inference scripts of the release packages, and the code of the planned RQ2augmentation study. "The paper" below means the report cited above; section numbers refer to it (S1 to S11 are thesections of its supplementary material). Comments in the code name the project's work stages in capitals (for exampleGEN for the generator, DATA for the real-data manifests, PRINT, FREEZE, LINEDET, REF, VLMA, VLMB, EVALCODE) and use theround 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 insrc/ref/ (repository state of 23 June 2021; MIT, its own LICENSE); and the Natural Earth map files insrc/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 thepackage 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 namethe partitions (H100, ZEN4) and quality-of-service names of the original cluster; adapt them to yours. Many scriptsand comments refer to the project's working records (paths that begin with records/, or files under the data foldersuch 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 eachenvironment, 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/<cuda tag>, 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_<model> (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 theenvironment 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.pyscripts/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-safesrc/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'sreference 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 ofpart 3.1; comments and descriptive strings were reworded; the folder scripts/r5_gate was renamed; two output fieldswere renamed (endpoints_confirmed in the verdict written by scripts/r5eval/verdict.py, added_beyond_plan in the setregistry 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.1232345618 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219---# 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.0language:- kk18 unmodified lines- 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-datamanifests 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, thetest-pass and page-scoring scripts, the inference scripts of the release packages, and the code of the planned RQ2augmentation study. "The paper" below means the report cited above; section numbers refer to it (S1 to S11 are thesections of its supplementary material). Comments in the code name the project's work stages in capitals (for exampleGEN for the generator, DATA for the real-data manifests, PRINT, FREEZE, LINEDET, REF, VLMA, VLMB, EVALCODE) and use theround 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 insrc/ref/ (repository state of 23 June 2021; MIT, its own LICENSE); and the Natural Earth map files insrc/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 thepackage 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 namethe partitions (H100, ZEN4) and quality-of-service names of the original cluster; adapt them to yours. Many scriptsand comments refer to the project's working records (paths that begin with records/, or files under the data foldersuch 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 eachenvironment, 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/<cuda tag>, 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_<model> (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 theenvironment 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.pyscripts/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-safesrc/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'sreference 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 ofpart 3.1; comments and descriptive strings were reworded; the folder scripts/r5_gate was renamed; two output fieldswere renamed (endpoints_confirmed in the verdict written by scripts/r5eval/verdict.py, added_beyond_plan in the setregistry 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 YOLO11sdetector finds the text lines on a page, and a fine-tuned PaddleOCR-VL-1.6 reads each line. Of the nine languages onlyKazakh has real handwriting to train on, so a page generator, pagesynth 0.3.0, writes real sentences onto simulatedschool 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:
```bashpython3.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, thegenerator 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 witha `+cu` suffix there come from `https://download.pytorch.org/whl/<cuda tag>`.
The job scripts were written for one Slurm cluster. Absolute paths in them start with two placeholders, which youreplace with your own folders before running a job:
```bashgrep -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 theoriginal 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:
```bashhf download treoa/turkic-ocr-generated-data --repo-type dataset --local-dir data/generated```
```pythonfrom datasets import load_dataset # pip install datasetshand_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 ofhttps://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 fullscoring run.
```bashmake test # pytest, 22 tests, under a minute on a laptopmake lint # ruff on tests/```
Scoring a prediction file (`make sample-eval`). The scorer reads a set registry, a manifest per set, and predictionfiles laid out as `<preds>/<model>/<checkpoint>/<set>.tsv` with the columns `id`, `ref`, `hyp`. The bundled sample hasten made-up lines in eight languages with ten character errors:
```bashpython 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`):
```bashhf download treoa/turkic-line-detector-yolo11s best.pt --local-dir models/detectorpython 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, licenceclass, 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:
```bashpython 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 datacontain no item drawn with them.
Training. The training entry points are `scripts/r5_vlma/train_vlm.py` (full fine-tuning of the vision-languagereaders), `scripts/r5_vlmb/vlmb_train.py` (readers that need their maker's code), `src/linedet/train_arm.py` (CTC linerecognizers), `src/linedet/det_yolo.py` (detector) and `scripts/r5_rq2/rq2_train.py` (augmentation study). The fullruns need H100 GPUs on a Slurm cluster and the licensed real data, KOHTD and HKR above all. The reader weights trained inthe project are not released: the terms of KOHTD and HKR limit their use to the applicant's group and to academicresearch. 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 thesample 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 fixedsequence file; the generator draws each page from `--seed` (default 1) and the page index. The generator reproduces thecontent 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 thefine-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 50handwritten Turkish test pages its page CER is 49.8%. The long version of the report also gives the augmentationstudy, 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-Florcopy 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`.12345678910111213141516[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 = 120target-version = "py312"
[tool.ruff.lint]select = ["E", "F", "W", "I"]12234567678991011126 unmodified lines19202122232223242526#!/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, whichthe 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 of16 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,6 unmodified lines --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
12341234567# 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/cu12812234567899101112#!/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, scoreswhere 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 detectionconfidences (rounded to 0.0001), in the detector's own order. A detector finds boxes, not text, so this TSV replaces the (id, text) tableof 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 sizeThe 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 size1280, confidence threshold 0.25, NMS IoU 0.6, at most 300 boxes, one class "text_line".
usage:1212345# 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.1223455678#!/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 and1212345# 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/cu12812234556781 unmodified line1011121314131415161732 unmodified lines5051525353545556#!/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 soThe code path is the one of our evaluation (src/linedet/data.py, models.py, predict.py, lm_decode.py, lm_gate.py), copied here sothe 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;1 unmodified line 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 the32 unmodified linesHERE = os.path.dirname(os.path.abspath(__file__))IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp")PAD = 16BATCH_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 = 6BEAM = 16ALPHA, BETA = 0.40, 1.001212345# 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).1223455678#!/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 and1212345# 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/cu128123456789101112131415161718# 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.5scipy==1.18.1regex==2026.11.19shapely==2.1.2pyyaml==6.0.3pillow==13.0.0opencv-python-headless==5.1.0.95fonttools==4.68.0rdkit==2026.9.2pyarrow==26.0.1huggingface-hub==2.4.0torch==2.11.0torchvision==0.26.0ultralytics==8.4.216pytest==9.2.0ruff==0.17.61234567891011121314151617181920212223model,set,metric,value,intervalPaddleOCR-VL-1.6 fine-tuned (shipped model),KOHTD sealed test (18615 Kazakh handwritten words),CER %,4.01,3.71 to 4.32Qwen3-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.465Qwen3-VL-2B fine-tuned,real printed test lines (8265),CER %,0.154,0.090 to 0.243PaddleOCR-VL-1.6 fine-tuned (shipped model),real Azerbaijani handwritten lines (442; descriptive),CER %,63.6,52.0 to 74.4PaddleOCR-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.05Qwen3-VL-2B fine-tuned,empty regions of real notebook validation photos (418),share with text written %,2.39,upper 95% bound 4.36PaddleOCR-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,640 unmodified lines641642643644644645646647640 unmodified lines 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)7 unmodified lines891011111213147 unmodified lines#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.4 unmodified lines56788910114 unmodified lines#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 -uCODE=/path/to/TURKIC_OCR_CODE11234"""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 modelreads any of its pages.usage: tp2_amend2.py TESTPASS2_DIR"""11234"""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 anyprediction on kohtd_test.usage: tp2_amend4.py TESTPASS2_DIR"""11234"""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-ONLYdecoding. Identical to the test pass 2 run (eval_vlm_test.py: vlm_common prompt builder and training instruction, greedy, num_beams 1, stopids incl. the trained answer-end token, max_new_tokens 48/192 by unit, batch 16, left padding, bf16 on CPU, manifest order) except for onelogits processor that sets to -inf every vocabulary token whose decoded text contains a Cyrillic character (Unicode Script_Extensions4 unmodified lines56788910114 unmodified lines#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 -uCODE=/path/to/TURKIC_OCR_CODED=/path/to/TURKIC_OCR_DATA11234"""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.
4 unmodified lines56788910114 unmodified lines#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 -uCODE=/path/to/TURKIC_OCR_CODE25 unmodified lines262728292930313225 unmodified lines
kind vlma -> eval_vlm_test.py (.venv_vlm); kind vlmb -> CODE/scripts/r5_vlmb/vlmb_eval_vlm_testpass.py with the arm'sown venv and environment (leader_cmds.py, read-only); kind cmd -> the task's argv (LINEDET's commands throughlinedet_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]"""102 unmodified lines103104105106106107108109102 unmodified lines# ---- 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/<arm>.json atomically (O_CREAT|O_EXCL, owner =# runner that starts an arm first creates DATA/outputs/r5/vlmb/claims/<arm>.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")12234567889101112131415151617181718192021{ "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.",15 unmodified lines1617181919202122483 unmodified lines50650750850950951051151215 unmodified linesOutputs hand|typed|clutter/<split>/<lang>/<bucket>/<id>.jpg, pages/<split>/<lang>/<id>.{jpg,json,xml} (PageXML 2019-07-15) labels/<kind>_<split>.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, SHA256SUMSusage: CODE/.venv_gen/bin/python -I rel2_build_data.py --decisions decisions.json --out DATA/release/rc1_data --threads 8"""import argparse483 unmodified lines 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 = {}6 unmodified lines78910101112136 unmodified lines#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 the6 unmodified lines78910101112136 unmodified lines#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 epochs11234"""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)6 unmodified lines78910101112136 unmodified lines#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 -uD=/path/to/TURKIC_OCR_DATA6 unmodified lines78910101112136 unmodified lines#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.11234"""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/<kind>_<split>.jsonl, the images, SHA256SUMS, LICENSE, attribution/, excluded/, build_report.json)Output: DATA/release/rc1_data_parquet/19 unmodified lines2021222324232425262728292930313219 unmodified linesdrawn and the LABEL is changed to the drawn mark (orig text is kept in thepage 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 itmay be used for). The older comment "Caveat and Bad Script highest, Pacifico low, Shantell Sans lowest" issuperseded by the owner's instruction of 21 Nov 2026 (Caveat and Bad Script had 81 percent of the Cyrillicsuperseded by the decision of 21 Nov 2026 (Caveat and Bad Script had 81 percent of the Cyrillichandwriting 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), sothe share of a font in a language is its weight divided by the weights of the fonts that cover that1233456"""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 andWhy a shared module: figures must carry words of the page language, not only numbers andsymbols. The audit and the gate must therefore count the same thing, otherwise "before" and "after"numbers are not comparable.
660 unmodified lines661662663664664665666667660 unmodified linesdef _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))1233456"""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 orWhy: a figure needs words in the page language, and no word may be invented ortranslated 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 a6 unmodified lines789101110111213131415166 unmodified linesfixed and the same in both policies: slot u = integers(0, 7), then z1 = random(), z2 = random(); each policy maps (z1, z2) toits 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); theconstants 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); theconstants 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), blursigma <= H/64, shear +-0.5 DEGREES (owner decision 2026-11-26), 2x2 thickening at 64 px only, downscale >= 0.75x, translationsigma <= H/64, shear +-0.5 DEGREES, 2x2 thickening at 64 px only, downscale >= 0.75x, translationby padding; it never thins strokes."""import math1234567{ "registry_version": "sample", "sets": [ {"name": "sample_lines", "manifest": "tests/data/sample_eval/manifests/sample_lines.tsv", "split": "val", "locked": false, "group_unit": "page"} ]}1234567891011id image text lang script kind source split group unitsample:01 images/sample_01.png Мектеп ауласында бәйтерек өседі kk Cyrl hand_synth sample val page_1 linesample:02 images/sample_02.png Қазақ тілі сабағы басталды kk Cyrl hand_synth sample val page_1 linesample:03 images/sample_03.png Біз кітапханаға бардық kk Cyrl hand_synth sample val page_2 linesample:04 images/sample_04.png Бүгүн аба ырайы жакшы ky Cyrl hand_synth sample val page_2 linesample:05 images/sample_05.png Казан шәһәре зур tt Cyrl hand_synth sample val page_3 linesample:06 images/sample_06.png Öğrenciler bahçede oynuyor tr Latn hand_synth sample val page_3 linesample:07 images/sample_07.png Bakı dənizin sahilindədir az Latn hand_synth sample val page_4 linesample:08 images/sample_08.png Toshkent katta shahar uz Latn hand_synth sample val page_4 linesample:09 images/sample_09.png Aşgabat ak mermerden gurlan tk Latn hand_synth sample val page_5 linesample:10 images/sample_10.png Саха сирэ кэрэ sah Cyrl hand_synth sample val page_5 line1234567891011id ref hypsample:01 Мектеп ауласында бәйтерек өседі Мектеп ауласында байтерек өседіsample:02 Қазақ тілі сабағы басталды Казак тілі сабағы басталдыsample:03 Біз кітапханаға бардық Біз кітапханаға бардықsample:04 Бүгүн аба ырайы жакшы Бүгүн аба ырайы жакшыsample:05 Казан шәһәре зур Казан шэһэре зурsample:06 Öğrenciler bahçede oynuyor Ogrenciler bahçede oynuyorsample:07 Bakı dənizin sahilindədir Baki dənizin sahilindədirsample:08 Toshkent katta shahar Toshkent kata shaharsample:09 Aşgabat ak mermerden gurlan Aşgabat ak mermerden gurlan.sample:10 Саха сирэ кэрэ Саха сирэ кэрэ123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Edit distance: the scorer's alignment (r5eval.align) against the reference implementation in r5eval/frozen."""import random
import pytest
from r5eval import alignfrom 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).gitattributes+1
.gitignoreAdded+36
MakefileAdded+22
NOTICE+5-5
READMEDeleted-224
README.md+194-226
pyproject.tomlAdded+16
release/page-pipeline/infer.py+6-6
release/page-pipeline/requirements.txt+4-4
release/turkic-line-detector-yolo11s/infer.py+2-2
release/turkic-line-detector-yolo11s/requirements.txt+2-2
release/turkic-ocr-paddleocr-vl-1.6/infer.py+2-2
release/turkic-ocr-paddleocr-vl-1.6/requirements.txt+2-2
release/turkic-ocr-ppocrv6-medium/infer.py+5-5
release/turkic-ocr-ppocrv6-medium/requirements.txt+2-2
release/turkic-ocr-qwen3-vl-2b/infer.py+2-2
release/turkic-ocr-qwen3-vl-2b/requirements.txt+2-2
requirements.txtAdded+18
results/figures/fig1_overview.pngAdded

Large File Pointer Details
- SHA256: ac5bccf6782a906ad6ffa91e7d88e9bbb3e415f6eb9ea78ab67450912be2faf2
- Pointer size: 131 Bytes
- Size of remote file: 184 kB
results/figures/fig2_results.pngAdded

results/figures/fig3_forgetting.pngAdded

results/metrics.csvAdded+23
scripts/r5/r5_build_real.py+1-1
scripts/r5_onemodel/onemodel_gate.sbatch+1-1
scripts/r5_testpass2/tp2_a1lf_kohtd.sbatch+1-1
scripts/r5_testpass2/tp2_amend2.py+1-1
scripts/r5_testpass2/tp2_amend4.py+1-1
scripts/r5_testpass2/tp2_az_latin.py+1-1
scripts/r5_testpass2/tp2_kzb_card.sbatch+1-1
scripts/r5_testpass2/tp2_kzb_fetch.py+1-1
scripts/r5_testpass2/tp2_kzb_fetch.sbatch+1-1
scripts/r5_vlma/testpass_runner.py+1-1
scripts/r5_vlmb/vlmb_runner.py+1-1
scripts/release2/decisions.json+5-5
scripts/release2/rel2_build_data.py+2-2
scripts/release2/rel2_d5_data.sbatch+1-1
scripts/release2/rel2_d5_detector_retrain.sbatch+1-1
scripts/release2/rel2_d5_prep.py+1-1
scripts/release2/rel2_d5_prep.sbatch+1-1
scripts/release2/rel2_decisions_install.sbatch+1-1
scripts/release2/rel2_parquet.py+1-1
src/pagesynth/pagesynth/fonts.py+3-3
src/pagesynth/pagesynth/langtext.py+1-1
src/pagesynth/pagesynth/scenes.py+1-1
src/pagesynth/pagesynth/vocab.py+1-1
src/rq2/aug.py+3-3
tests/data/sample_eval/evalsets.jsonAdded+7
tests/data/sample_eval/manifests/sample_lines.tsvAdded+11
tests/data/sample_eval/preds/demo/final/sample_lines.tsvAdded+11
tests/test_edit_distance.pyAdded+57