Download tests_r5eval/synth_world.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 4.77 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/tests_r5eval/synth_world.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/tests_r5eval/synth_world.py
-
curl -L -o synth_world.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/tests_r5eval/synth_world.py
4.77 kB
| """Builds small synthetic manifests, prediction files and registries for the tests of the scorer and the verdict script. | |
| Everything is made up (random words from a fixed list); no project data is read.""" | |
| import json | |
| import os | |
| import random | |
| VOCAB = ["қазақ", "тілі", "әдебиет", "өнер", "үй", "ұлы", "жүрек", "сәлем", "мектеп", "ғалам", "құрмет", "көктем", "ұлттық", | |
| "һәм", "кітап", "бала", "қала", "жаз", "қыс", "күз", "дәптер", "1", "12", "3,5", "Қазақстан", "оқушы", "білім", "еңбек"] | |
| HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] | |
| def make_manifest(path, name, n_forms, per_form, split="val", lang="kk", script="Cyrl", kind="hand_real", unit="word", seed=0, | |
| vocab=VOCAB, clutter=False): | |
| rnd = random.Random(seed) | |
| rows = [] | |
| for f in range(n_forms): | |
| for k in range(per_form): | |
| text = "" if clutter else rnd.choice(vocab) | |
| rows.append({"id": "%s:%d_%03d" % (name, f, k), "image": "/nonexistent/%s_%d_%d.jpg" % (name, f, k), "text": text, | |
| "lang": lang, "script": script, "kind": "clutter" if clutter else kind, "source": name, "split": split, | |
| "group": "%s_form_%d" % (name, f), "unit": unit}) | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| with open(path, "w", encoding="utf-8", newline="") as fh: | |
| fh.write("\t".join(HDR) + "\n") | |
| for r in rows: | |
| fh.write("\t".join(r[c] for c in HDR) + "\n") | |
| return rows | |
| def corrupt(text, rnd, rate, collapse=True): | |
| """Each character is damaged with probability `rate`: special letter collapse, deletion, substitution or insertion.""" | |
| out = [] | |
| for ch in text: | |
| if rnd.random() < rate: | |
| r = rnd.random() | |
| if collapse and ch == "қ": | |
| out.append("к") | |
| elif r < 0.4: | |
| continue | |
| elif r < 0.8: | |
| out.append(rnd.choice("абвгдеж")) | |
| else: | |
| out.append(ch + rnd.choice("абв")) | |
| else: | |
| out.append(ch) | |
| return "".join(out) | |
| def write_preds(path, rows, rate, seed=1, with_conf=True, raw_wrap_rate=0.0, clutter_rate=0.0, loop_rate=0.0, ref_override=None, rate_fn=None): | |
| """Writes <set>.tsv (id ref hyp [conf conf_min hit_cap n_tokens]) and, when raw_wrap_rate > 0, <set>.raw.jsonl. | |
| rate_fn(row) -> character damage rate for that row (overrides `rate`).""" | |
| rnd = random.Random(seed) | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| raws = [] | |
| with open(path, "w", encoding="utf-8", newline="") as fh: | |
| cols = ["id", "ref", "hyp"] + (["conf", "conf_min", "hit_cap", "n_tokens"] if with_conf else []) | |
| fh.write("\t".join(cols) + "\n") | |
| for r in rows: | |
| ref = r["text"] | |
| if ref == "": | |
| hyp = "".join(rnd.choice("абвгд") for _ in range(rnd.randint(2, 6))) if rnd.random() < clutter_rate else "" | |
| else: | |
| hyp = corrupt(ref, rnd, rate_fn(r) if rate_fn else rate) | |
| if rnd.random() < loop_rate: | |
| hyp = (ref + " ") * 4 | |
| raw = hyp | |
| if raw_wrap_rate and rnd.random() < raw_wrap_rate: | |
| raw = "```text\n" + hyp + "\n```" | |
| raws.append({"id": r["id"], "raw": raw, "hit_cap": False}) | |
| line = [r["id"], ref_override.get(r["id"], ref) if ref_override else ref, hyp] | |
| if with_conf: | |
| good = hyp == ref | |
| lp = -0.05 - rnd.random() * (0.2 if good else 1.5) | |
| line += ["%.5f" % lp, "%.5f" % (lp - 0.3), "0", str(len(hyp) + 1)] | |
| fh.write("\t".join(line) + "\n") | |
| if raw_wrap_rate: | |
| with open(path[:-4] + ".raw.jsonl", "w", encoding="utf-8") as fh: | |
| for d in raws: | |
| fh.write(json.dumps(d, ensure_ascii=False) + "\n") | |
| def write_meta(path, conf_logprob=True, **kw): | |
| d = {"arm": "x", "checkpoint": "short", "samples_seen": 150000, "learning_rate": 2e-5, "peak_mem_reserved_batch1_GiB": 9.5, | |
| "peak_mem_batch1_GiB": 8.1, "images_per_second_batch16_V1": 55.0} | |
| if conf_logprob: | |
| d["conf_definition"] = "conf = mean natural-log probability of the generated tokens (log-prob)" | |
| d.update(kw) | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| with open(path, "w", encoding="utf-8") as fh: | |
| json.dump(d, fh) | |
| def write_registry(path, sets): | |
| """sets: list of dicts with name, manifest, split, locked.""" | |
| with open(path, "w", encoding="utf-8") as fh: | |
| json.dump({"registry_version": "test", "sets": sets}, fh, ensure_ascii=False) | |