turkic-ocr-code / src /linedet /seed_vote.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
7.36 kB
"""Voting between the two seeds of one arm (amendment 3.3 D7, idea SR1-H03). Descriptive only; validation sets only.
Inputs: the prediction files and the saved top-6 frame log-probabilities of both seeds (written by predict.py) for one checkpoint name.
Three combinations are scored on the same lines, beside the two single seeds:
- line select: per line, keep the hypothesis with the higher confidence column (conf);
- character vote: the two greedy label sequences are aligned (edit-distance opcodes); equal parts are kept; where they differ the part with the
higher mean character confidence (frame maximum at emission) wins; a part present in one sequence only is kept when its mean confidence
is at least 0.5. With two voters there is no majority, so confidence breaks every tie (ASSUMPTION of this script);
- soft vote: the two frame posteriors (top-6 entries, missing mass ignored) are averaged frame by frame and decoded greedily; needs equal frame
counts (same architecture and same input, true for two seeds of one arm).
Usage: python -m linedet.seed_vote --label_a A1 --label_b A1_s2 --ckpt short --out <json>
"""
import argparse
import csv
import json
import os
import unicodedata
import numpy as np
from .common import LD_OUT, LOGIT_DIR, PRED_DIR, cer_wer, load_json, save_json, to_report_text, utcnow, write_tsv
csv.field_size_limit(10 ** 9)
def read_pred(path):
with open(path, newline="", encoding="utf-8") as f:
return {r["id"]: r for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)}
def load_npz(path):
z = np.load(path, allow_pickle=False)
idx, lp, lens, ids = z["idx"], z["lp"], z["lens"], z["ids"] # each array is read and decompressed ONCE (the first version indexed z["idx"] inside the
off = np.concatenate([[0], np.cumsum(lens)]) # loop, which re-read the whole array per line and kept every copy alive through the slices:
return {str(i): (idx[off[k]:off[k + 1]], lp[off[k]:off[k + 1]]) for k, i in enumerate(ids)} # memory grew with lines x set size; job 51129 died of it
def greedy(idx, lp):
"""label sequence and the confidence of each emitted label"""
if len(idx) == 0:
return [], []
j = lp.argmax(1)
best = idx[np.arange(len(idx)), j]
p = np.exp(lp.astype(np.float32)[np.arange(len(idx)), j])
labs, conf, prev = [], [], 0
for t in range(len(best)):
k = int(best[t])
if k != prev and k != 0:
labs.append(k)
conf.append(float(p[t]))
prev = k
return labs, conf
def char_vote(la, ca, lb, cb):
from rapidfuzz.distance import Levenshtein
out = []
for op in Levenshtein.opcodes(la, lb):
a0, a1, b0, b1 = op.src_start, op.src_end, op.dest_start, op.dest_end
if op.tag == "equal":
out += la[a0:a1]
elif op.tag == "replace":
ma, mb = np.mean(ca[a0:a1]), np.mean(cb[b0:b1])
out += la[a0:a1] if ma >= mb else lb[b0:b1]
elif op.tag == "delete": # only in a
if np.mean(ca[a0:a1]) >= 0.5:
out += la[a0:a1]
elif op.tag == "insert": # only in b
if np.mean(cb[b0:b1]) >= 0.5:
out += lb[b0:b1]
return out
def soft_vote(ia, la_, ib, lb_):
if len(ia) != len(ib):
return None
labs, prev = [], 0
for t in range(len(ia)):
d = {}
for k, v in zip(ia[t].tolist(), la_[t].astype(np.float32).tolist()):
d[k] = d.get(k, 0.0) + float(np.exp(v)) / 2
for k, v in zip(ib[t].tolist(), lb_[t].astype(np.float32).tolist()):
d[k] = d.get(k, 0.0) + float(np.exp(v)) / 2
k = max(d, key=d.get)
if k != prev and k != 0:
labs.append(k)
prev = k
return labs
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--label_a", required=True)
ap.add_argument("--label_b", required=True)
ap.add_argument("--ckpt", required=True)
ap.add_argument("--pred_dir_a", default=PRED_DIR)
ap.add_argument("--pred_dir_b", default=PRED_DIR)
ap.add_argument("--logit_dir_a", default=LOGIT_DIR)
ap.add_argument("--logit_dir_b", default=LOGIT_DIR)
ap.add_argument("--codec", default=LD_OUT + "/codec_union.json")
ap.add_argument("--max_lines", type=int, default=5000)
ap.add_argument("--out", required=True)
ap.add_argument("--vote_pred_dir", default="")
a = ap.parse_args()
c2l = load_json(a.codec)["c2l"]
l2c = {v[0]: k for k, v in c2l.items() if len(v) == 1}
da = os.path.join(a.pred_dir_a, a.label_a, a.ckpt)
db = os.path.join(a.pred_dir_b, a.label_b, a.ckpt)
sets = sorted(f[:-4] for f in os.listdir(da) if f.endswith(".tsv") and os.path.exists(os.path.join(db, f)))
res = {"label_a": a.label_a, "label_b": a.label_b, "checkpoint": a.ckpt, "created": utcnow(), "max_lines": a.max_lines, "sets": {},
"note": "descriptive; validation sets only; same lines for every column"}
for s in sets:
pa, pb = read_pred(os.path.join(da, s + ".tsv")), read_pred(os.path.join(db, s + ".tsv"))
ids = [i for i in pa if i in pb]
if len(ids) > a.max_lines:
ids = sorted(np.random.default_rng(20261122).choice(ids, a.max_lines, replace=False).tolist())
na = os.path.join(a.logit_dir_a, a.label_a, a.ckpt, s + ".npz")
nb = os.path.join(a.logit_dir_b, a.label_b, a.ckpt, s + ".npz")
if not (os.path.exists(na) and os.path.exists(nb)):
res["sets"][s] = {"skipped": "frame probabilities missing"}
continue
za, zb = load_npz(na), load_npz(nb)
refs, ha, hb, hsel, hchar, hsoft = [], [], [], [], [], []
n_soft_skipped = 0
for i in ids:
refs.append(pa[i]["ref"])
ha.append(pa[i]["hyp"])
hb.append(pb[i]["hyp"])
try:
ca_ = float(pa[i]["conf"])
cb_ = float(pb[i]["conf"])
except Exception:
ca_ = cb_ = 0.0
hsel.append(pa[i]["hyp"] if ca_ >= cb_ else pb[i]["hyp"])
ia, la_ = za[i]
ib, lb_ = zb[i]
labs_a, conf_a = greedy(ia, la_)
labs_b, conf_b = greedy(ib, lb_)
cv = char_vote(labs_a, conf_a, labs_b, conf_b)
hchar.append(to_report_text("".join(l2c.get(k, "") for k in cv)))
sv = soft_vote(ia, la_, ib, lb_)
if sv is None:
n_soft_skipped += 1
hsoft.append(pa[i]["hyp"])
else:
hsoft.append(to_report_text("".join(l2c.get(k, "") for k in sv)))
row = {"n": len(ids)}
for nm, hyp in (("seed_a", ha), ("seed_b", hb), ("line_select", hsel), ("char_vote", hchar), ("soft_vote", hsoft)):
cer, wer, *_ = cer_wer(refs, hyp)
row["cer_" + nm] = cer
row["wer_" + nm] = wer
row["soft_vote_lines_with_unequal_frames"] = n_soft_skipped
res["sets"][s] = row
print(s, json.dumps(row), flush=True)
if a.vote_pred_dir:
write_tsv(os.path.join(a.vote_pred_dir, a.label_a + "_vote", a.ckpt, s + ".tsv"), ["id", "ref", "hyp", "conf", "conf_min", "hit_cap"],
[(i, r, h, "", "", 0) for i, r, h in zip(ids, refs, hchar)])
save_json(a.out, res)
if __name__ == "__main__":
main()