File size: 5,578 Bytes
24aaa76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | """Mark metrics of RQ2: the per-row counting loop of CODE/scripts/tp2_proposal_metrics.py run() (sha256 d4f94254505e3e61...,
read in full), copied unchanged except that the language of the validation sets is looked up by set name here
(tp2's lang_of maps only kohtd_test to kk; V1 and kohtd_val are Kazakh word crops too).
Definitions (as proposal_metrics.json): text NFC with whitespace collapsed; marked letters = pagesynth/text.py
PROFILES[lang]['special'] (both cases; uz_latn: U+02BB and U+02BC); deletion = a reference marked letter aligned by
substitution to its base letter (uz_latn: the mark deleted); alignment r5eval.align.align_ops (unchanged).
"""
import re
import sys
import unicodedata
CODE = "/path/to/TURKIC_OCR_CODE"
if CODE + "/src/pagesynth" not in sys.path:
sys.path.insert(0, CODE + "/src/pagesynth")
from pagesynth import text as ptext # noqa: E402 project alphabet tables
from r5eval.align import align_ops, lev_fast # noqa: E402 scorer alignment, unchanged
LANGS = ptext.LANG_ORDER
LANG_RX = re.compile(r"(?:^|[_:])(uz_cyrl|uz_latn|kk|ky|tt|ba|sah|tr|az|tk)_\d")
KK_SETS = ("V1", "kohtd_val", "kohtd_test")
MANUAL_BASE = {"ә": "а", "ғ": "г", "қ": "к", "ң": "н", "ө": "о", "ұ": "у", "ү": "у", "ҳ": "х", "җ": "ж", "ҙ": "з",
"ҡ": "к", "ҫ": "с", "ҕ": "г", "ҥ": "н", "ə": "e", "ı": "i"}
MANUAL_BASE.update({k.upper(): v.upper() for k, v in list(MANUAL_BASE.items()) if k != "ı"})
MANUAL_BASE["İ"] = "I"
KEYS = ("ce", "rl", "mk_tot", "mk_ok", "mk_del", "mk_oth", "base_tot", "mk_ins")
def n0(x):
return " ".join(unicodedata.normalize("NFC", x).split())
def read_tsv(p):
rows = []
with open(p, encoding="utf-8", newline="\n") as f:
head = f.readline().rstrip("\n").split("\t")
ii, ir, ih = head.index("id"), head.index("ref"), head.index("hyp")
for line in f:
c = line.rstrip("\n").split("\t")
if len(c) <= max(ii, ir):
continue
rows.append((c[ii], c[ir], c[ih] if len(c) > ih else ""))
return rows
def lang_of(set_name, rid):
if set_name in KK_SETS:
return "kk"
m = LANG_RX.search(rid)
return m.group(1) if m else "unknown"
def script_of(ch):
if not unicodedata.category(ch).startswith("L"):
return None
n = unicodedata.name(ch, "")
if n.startswith("LATIN"):
return "Latn"
if n.startswith("CYRILLIC"):
return "Cyrl"
return None
def base_of(ch):
if ch in MANUAL_BASE:
return MANUAL_BASE[ch]
d = unicodedata.normalize("NFD", ch)
b = "".join(c for c in d if not unicodedata.category(c).startswith("M"))
return b if b and b != ch else None # һ, і: no base letter defined
def marked_set(lang):
if lang == "uz_latn":
return {"ʻ", "ʼ"}
if lang in ptext.PROFILES:
return set(ptext.PROFILES[lang]["special"].replace(" ", ""))
return set()
ALPHA = {l: {c for c in ptext.alphabet(l) if unicodedata.category(c).startswith("L")} for l in LANGS}
UNIQUE = {l: ALPHA[l] - set().union(*[ALPHA[o] for o in LANGS if o != l]) for l in LANGS}
def row_counts(set_name, rid, ref, hyp):
"""One row of tp2_proposal_metrics.run(): the loop body, unchanged (lang from lang_of above). Returns a dict."""
r, h = n0(ref), n0(hyp)
lang = lang_of(set_name, rid)
dist, ops = align_ops(r, h)
rwords, hwords = r.split(" ") if r else [], h.split(" ") if h else []
we = lev_fast(rwords, hwords) if rwords or hwords else 0
mk = marked_set(lang)
bases = {base_of(c) for c in mk if base_of(c)}
if lang == "uz_latn":
bases = set()
mt = mo = md = mx = bt = mi = 0
ut = ue = st = se = 0
uq = UNIQUE.get(lang, set()); al = ALPHA.get(lang, set())
for op, i, j in ops:
if i < 0:
if lang == "uz_latn" and h[j] in ("ʻ", "ʼ"):
mi += 1
continue
c = r[i]
if c in mk:
mt += 1
if op == "M":
mo += 1
elif op == "D" and lang == "uz_latn":
md += 1
elif op == "S" and base_of(c) is not None and h[j] == base_of(c):
md += 1
else:
mx += 1
elif c in bases:
bt += 1
if op == "S" and h[j] in mk and base_of(h[j]) == c:
mi += 1
if lang in UNIQUE and unicodedata.category(c).startswith("L"):
if c in uq:
ut += 1; ue += op != "M"
elif c in al:
st += 1; se += op != "M"
if lang == "uz_latn":
bt = sum(1 for k in range(len(r)) if r[k] in "oOgG")
return {"id": rid, "lang": lang, "ce": dist, "rl": len(r), "we": we, "rw": len(rwords), "mk_tot": mt, "mk_ok": mo,
"mk_del": md, "mk_oth": mx, "base_tot": bt, "mk_ins": mi, "uq_tot": ut, "uq_err": ue, "sh_tot": st, "sh_err": se}
def agg(rows):
s = {k: int(sum(r[k] for r in rows)) for k in KEYS}
out = {"rows": len(rows), "ref_chars": s["rl"], "char_errors": s["ce"], "CER": (s["ce"] / s["rl"]) if s["rl"] else None,
"marked_ref_letters": s["mk_tot"], "mark_deleted": s["mk_del"], "mark_other_wrong": s["mk_oth"],
"base_letters": s["base_tot"], "mark_inserted": s["mk_ins"]}
out["mark_deletion_rate"] = s["mk_del"] / s["mk_tot"] if s["mk_tot"] else None
out["mark_error_rate"] = (s["mk_del"] + s["mk_oth"]) / s["mk_tot"] if s["mk_tot"] else None
out["mark_insertion_rate"] = s["mk_ins"] / s["base_tot"] if s["base_tot"] else None
return out
|