Download scripts/r5_ref/ref_ppocr_predict.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 8.96 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_ref/ref_ppocr_predict.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_ref/ref_ppocr_predict.py
-
curl -L -o ref_ppocr_predict.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_ref/ref_ppocr_predict.py
8.96 kB
| """R5 REF, arm R2 (PaddleOCR PP-OCRv3 recogniser as trained by Bimurat et al. 2024): predictions of the best-validation-accuracy checkpoint. | |
| Every crop of a manifest gets a hypothesis. Pinned code: PaddlePaddle/PaddleOCR@e218c0a (build_model, build_post_process, DecodeImage, RecResizeImg). | |
| Decoding is PaddleOCR's own CTCLabelDecode (greedy argmax, repeats removed); the SAR head is a training-time head only (MultiHead returns the CTC output in eval mode). | |
| Writes DATA/outputs/r5/preds/R2/C/<set>.tsv (+ meta.json), C = "ours" (run i) or "rand" (run ii). | |
| A locked set (evalsets.json locked=true, or a test manifest) is refused unless the scoring pass has started (token file, ref_common.TEST_TOKEN). | |
| Usage: python -I ref_ppocr_predict.py --run i|ii --sets name=manifest[,name=manifest...] [--cpu] | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor | |
| import numpy as np | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| import ref_common as rc # noqa: E402 | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--run", required=True, choices=["i", "ii", "iii"]) | |
| ap.add_argument("--sets", required=True) | |
| ap.add_argument("--train_dir", default=None) | |
| ap.add_argument("--cpu", action="store_true") | |
| ap.add_argument("--batch", type=int, default=128) | |
| ap.add_argument("--threads", type=int, default=4) | |
| ap.add_argument("--limit", type=int, default=0) | |
| ap.add_argument("--pred_root", default=rc.PREDS) | |
| ap.add_argument("--weights", default=None, help="override: path prefix of a .pdparams file (default best_keep/best_accuracy)") | |
| ap.add_argument("--ck_name", default=None, help="override of the checkpoint folder name (default ours / rand / mix)") | |
| a = ap.parse_args() | |
| ck_name = a.ck_name or {"i": "ours", "ii": "rand", "iii": "mix"}[a.run] | |
| train_dir = a.train_dir or (rc.DATA + "/checkpoints/r5/ref/R2_" + a.run) | |
| sets = [s.split("=", 1) for s in a.sets.split(",") if s] | |
| loaded = [] | |
| for name, path in sets: | |
| rows = rc.read_manifest(path) | |
| rc.check_locked(name, path, rows) | |
| loaded.append((name, path, rows[:a.limit] if a.limit else rows)) | |
| summ = json.load(open(os.path.join(train_dir, "train_summary.json"))) | |
| # sample and epoch counts come from progress.json (written at every epoch end with the TOTAL steps of the run); train_summary.json only counts the last session | |
| # and read 0 after a resume session that did no work (22 Nov 2026, found with run ii) | |
| prog_path = os.path.join(train_dir, "progress.json") | |
| prog = json.load(open(prog_path)) if os.path.exists(prog_path) else None | |
| if prog and "steps_total" in prog: | |
| n_samples_seen, n_epochs_done = int(prog["steps_total"]) * int(summ.get("batch", 128)), int(prog.get("epoch", summ["epochs_done"])) | |
| counts_from = "progress.json: steps_total x training batch" | |
| else: | |
| n_samples_seen, n_epochs_done, counts_from = summ["samples_seen"], summ["epochs_done"], "train_summary.json (progress.json missing)" | |
| os.environ.setdefault("FLAGS_allocator_strategy", "auto_growth") | |
| sys.path.insert(0, rc.PPOCR_ROOT) | |
| os.chdir(rc.PPOCR_ROOT) | |
| import paddle | |
| import yaml | |
| import cv2 | |
| if not a.cpu: | |
| if not paddle.is_compiled_with_cuda() or paddle.device.cuda.device_count() < 1: | |
| print("FAIL: PaddlePaddle sees no GPU") | |
| raise SystemExit(3) | |
| paddle.set_device("gpu:0") | |
| else: | |
| paddle.set_device("cpu") | |
| from ppocr.modeling.architectures import build_model | |
| from ppocr.postprocess import build_post_process | |
| from ppocr.data.imaug import RecResizeImg | |
| cfg = yaml.load(open(os.path.join(train_dir, "config_ref.yml"), "rb"), Loader=yaml.Loader) | |
| post = build_post_process(cfg["PostProcess"], cfg["Global"]) | |
| char_num = len(getattr(post, "character")) | |
| cfg["Architecture"]["Head"]["out_channels_list"] = {"CTCLabelDecode": char_num, "SARLabelDecode": char_num + 2} # as tools/train.py does for MultiHead + SARLoss | |
| model = build_model(cfg["Architecture"]) | |
| wprefix = a.weights or (os.path.join(train_dir, "model", "iter_epoch_4") if a.run == "iii" else os.path.join(train_dir, "best_keep", "best_accuracy")) | |
| model.set_state_dict(paddle.load(wprefix + ".pdparams")) | |
| model.eval() | |
| named = [(n, int(np.prod(p.shape))) for n, p in model.named_parameters()] | |
| n_params = int(sum(c for _, c in named)) # whole training network (includes the SAR head) | |
| n_params_ctc = int(sum(c for n, c in named if ".sar_head." not in n and not n.startswith("sar_head"))) # backbone + CTC neck + CTC head: what runs at test time | |
| resize = RecResizeImg(image_shape=cfg["Eval"]["dataset"]["transforms"][2]["RecResizeImg"]["image_shape"] if len(cfg["Eval"]["dataset"]["transforms"]) > 2 else [3, 48, 320]) | |
| def load(path): | |
| try: | |
| buf = np.fromfile(path, dtype=np.uint8) | |
| img = cv2.imdecode(buf, 1) | |
| if img is None: | |
| raise ValueError("decode") | |
| return resize({"image": img})["image"] | |
| except Exception: | |
| return np.zeros((3, 48, 320), dtype=np.float32) | |
| gpu_name = None | |
| try: | |
| gpu_name = paddle.device.cuda.get_device_name() if not a.cpu else "cpu" | |
| except Exception: | |
| pass | |
| # batch-1 memory | |
| peak1 = None | |
| with paddle.no_grad(): | |
| x1 = paddle.to_tensor(np.zeros((1, 3, 48, 320), dtype=np.float32)) | |
| model(x1) | |
| try: | |
| if not a.cpu: | |
| paddle.device.cuda.reset_max_memory_reserved() | |
| model(x1) | |
| peak1 = int(paddle.device.cuda.max_memory_reserved()) | |
| except Exception: | |
| pass | |
| ex = ThreadPoolExecutor(a.threads) | |
| for name, path, rows in loaded: | |
| t0 = time.time() | |
| hyps, confs = [], [] | |
| t_inf, n_img = 0.0, 0 | |
| for s in range(0, len(rows), a.batch): | |
| chunk = rows[s:s + a.batch] | |
| x = np.stack(list(ex.map(load, [r["image"] for r in chunk]))) | |
| t1 = time.time() | |
| with paddle.no_grad(): | |
| out = model(paddle.to_tensor(x)) | |
| res = post(out) | |
| t_inf += time.time() - t1 | |
| n_img += len(chunk) | |
| for text, conf in res: | |
| hyps.append(text) | |
| confs.append(float(conf)) | |
| d = os.path.join(a.pred_root, "R2", ck_name) | |
| rc.write_preds(d, name, rows, hyps, confs) | |
| meta = {"model": "PaddleOCR PP-OCRv3 recogniser (MobileNetV1Enhance 0.5 + SVTR neck + CTC/SAR heads), arm R2, as trained by Bimurat et al. 2024 (called SVTR-Tiny there); reference only", | |
| "model_revision": rc.PPOCR_COMMIT, "config": "configs/rec/PP-OCRv3/en_PP-OCRv3_rec.yml with overrides listed in recipes.json", "checkpoint": ck_name, | |
| "weights": (os.path.basename(wprefix) + " (best exact-match accuracy on the validation list, over the whole run)") if a.run != "iii" and not a.weights else (os.path.basename(wprefix) + (" (weights after the stated epoch of run iii; iter_epoch_4 is the final 150,016-sample point)" if a.run == "iii" else " (the last epoch saved, given with --weights: the run never reached an evaluation step, so no best_accuracy file exists)")), "samples_seen": n_samples_seen, "epochs_done": n_epochs_done, "counts_from": counts_from, "train_summary_samples_seen": summ["samples_seen"], | |
| "epochs_planned": summ["epochs_planned"], "paper_epochs": 100, "compressed_schedule": summ.get("compressed_schedule"), "stopped_because": summ["stopped_because"], | |
| "paper_rule_reached": summ.get("paper_rule_reached"), "parameters": n_params, "parameters_ctc_branch_used_at_test_time": n_params_ctc, "peak_gpu_memory_bytes_batch1": peak1, | |
| "images_per_second_model_only_batch%d" % a.batch: round(n_img / max(t_inf, 1e-9), 1), "gpu": gpu_name, | |
| "decoding": "PaddleOCR CTCLabelDecode, greedy argmax, no lexicon, no language model; conf = mean probability of the emitted characters", | |
| "wall_seconds_this_set": round(time.time() - t0, 1), "written_utc": rc.utc(), "set": name, "rows": len(rows), "data_role": rc.data_role(a.run, name), | |
| "train_data": {"i": "KOHTD train forms of the project split (run i)", "ii": "crop-level random 70% of the KOHTD train+validation pool (run ii, seed 20261121)", | |
| "iii": "mix_v1, the first 150,016 samples of the project's seeded mix stream that the recipe can encode (run iii, data-order seed 20261121)"}[a.run], | |
| "paddle": paddle.__version__} | |
| json.dump(meta, open(os.path.join(d, "meta_%s.json" % name), "w"), indent=1) | |
| json.dump(meta, open(os.path.join(d, "meta.json"), "w"), indent=1) | |
| print(name, len(rows), "rows", round(time.time() - t0, 1), "s", flush=True) | |
| if __name__ == "__main__": | |
| main() | |