File size: 14,128 Bytes
726fc64 | 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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | """Statistics from the attributable diagnostics of the OGA rerun (grc-macronizer
diagnostics-logging, job 5715083), restricted to exactly the sentences in
Urdatorn/oga-macronized-no-norma (revision 5d737f8), with all-OGA figures alongside.
Sentence identity: the rerun's output line i of a work is sentence i of that work
(checked: per chunk, the number of output lines equals the number of sentences sent),
i.e. chunk i // 500, sentence i % 500, which is what the per-token traces record.
A line belongs to the HF data if its text occurs there (multiset matching).
Usage: python analyze_rerun.py DIAG_DIR RERUN_OUT HF_DATA_DIR OUT_DIR WORKERS
"""
import collections, glob, json, os, re, sys, unicodedata
from multiprocessing import Pool
import pyarrow.parquet as pq
from grc_utils import count_dichrona_in_open_syllables
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from analyze_diagnostics import unresolved_syllables, word_shape # noqa: E402
C = collections.Counter
CHUNK = 500
MODULES = ["custom", "wiktionary", "lsj", "nominal_forms", "verbal_forms", "accent_rules", "prefix",
"double_accent_recursion", "reversed_elision_recursion", "case_ending_recursion",
"oxytonization", "decapitalization", "hypotactic", "accent_rules_final"]
HF_KEEP = None # stem -> set of (chunk, sentence) in the HF data (set in the parent, inherited by fork)
def new_acc():
return dict(tokens=0, before=0, after=0, credit_tok=C(), credit_dich=C(), credit_pos=C(),
solo_tok=C(), solo_short=C(), solo_long=C(), n_modules=C(), first_module=C(),
sent_pos=C(), sent_feat=C(), sent_shape=C(), sent_form=C(), sent_lemma=C(),
amb_tok=0, amb_dich=0, amb_partial=0, amb_pos=C(), amb_feat=C(), amb_shape=C(),
amb_form=C(), amb_tokform=C(), amb_form_info={}, amb_lemma=C(), amb_syl=C(), amb_nunres=C(),
resolved_short=0, resolved_long=0, unresolved_vowel=C())
def add_row(a, c):
sent, token, lemma, pos, morph, before, after, result, credits = c
before, after = int(before), int(after)
a["tokens"] += 1; a["before"] += before; a["after"] += after
a["sent_pos"][pos] += 1; a["sent_form"][token] += 1; a["sent_lemma"][(lemma, pos)] += 1
feats = [kv for kv in morph.split("|") if "=" in kv]
for kv in feats:
a["sent_feat"][(pos, kv)] += 1
shape = word_shape(token)
for k, v in shape.items():
if v: a["sent_shape"][k] += 1
cr = [(kv.split("=")[0], int(kv.split("=")[1])) for kv in credits.split(",") if kv]
a["n_modules"][len(cr)] += 1
if cr: a["first_module"][cr[0][0]] += 1
added_short = max(0, result.count("^") - token.count("^"))
added_long = max(0, result.count("_") - token.count("_"))
a["resolved_short"] += added_short; a["resolved_long"] += added_long
for m, n in cr:
a["credit_tok"][m] += 1; a["credit_dich"][m] += n; a["credit_pos"][(m, pos)] += n
if len(cr) == 1:
m = cr[0][0]
a["solo_tok"][m] += 1; a["solo_short"][m] += added_short; a["solo_long"][m] += added_long
if after > 0:
a["amb_tok"] += 1; a["amb_dich"] += after
if "^" in result or "_" in result: a["amb_partial"] += 1
a["amb_pos"][pos] += 1; a["amb_form"][result] += 1; a["amb_tokform"][token] += 1; a["amb_lemma"][(lemma, pos)] += 1
a["amb_form_info"].setdefault(result, (lemma, pos, morph))
for kv in feats:
a["amb_feat"][(pos, kv)] += 1
for k, v in shape.items():
if v: a["amb_shape"][k] += 1
us = unresolved_syllables(result)
a["amb_nunres"][min(len(us), 3)] += 1
for v, where, acc in us:
a["amb_syl"][(v, where, acc)] += 1
a["unresolved_vowel"][v] += 1
def merge(a, b):
for k, v in b.items():
if isinstance(v, C): a[k].update(v)
elif isinstance(v, dict):
for kk, vv in v.items(): a[k].setdefault(kk, vv)
else: a[k] += v
return a
def do_trace(path):
tag = os.path.basename(path)[:-4]
stem, chunk = tag.rsplit(".", 1)
chunk = int(chunk)
keep = HF_KEEP.get(stem, set())
hf, allo = new_acc(), new_acc()
with open(path, encoding="utf-8") as fh:
next(fh)
for line in fh:
c = line.rstrip("\n").split("\t")
if len(c) != 9:
continue
add_row(allo, c)
if (chunk, int(c[0])) in keep:
add_row(hf, c)
return hf, allo
def do_lines(args):
stem, lines, flags = args
out = C()
for line, in_hf in zip(lines, flags):
b = count_dichrona_in_open_syllables(line.replace("^", "").replace("_", ""))
a = count_dichrona_in_open_syllables(line)
out[("all", "before")] += b; out[("all", "after")] += a; out[("all", "lines")] += 1
if in_hf:
out[("hf", "before")] += b; out[("hf", "after")] += a; out[("hf", "lines")] += 1
return stem, out
def do_log(path):
out = dict(skips=C(), considered_pos=C(), odycy_fail=0, chunk_sentences={}, lines=0)
skip_needles = [("no dichrona", "has no dichrona"), ("not in diagnostic word list", "not in diagnostic word list"),
("Greek numeral", "is a Greek numeral"), ("stop word", "stop word"),
("final sigma mid-word", "final sigma mid-word"), ("pathological accents/breathings", "Pathological word")]
r_cons = re.compile(r"^Considering token: .*?\tPOS: (.*?)\tMorph: ")
r_start = re.compile(r"^=== CHUNK START (\S+) sentences=(\d+) ===")
with open(path, encoding="utf-8", errors="replace") as fh:
for line in fh:
out["lines"] += 1
p = line.rstrip("\n").split(" - ", 2)
if len(p) < 3:
continue
msg = p[2]
m = r_cons.match(msg)
if m:
out["considered_pos"][m.group(1)] += 1; continue
m = r_start.match(msg)
if m:
out["chunk_sentences"][m.group(1)] = int(m.group(2)); continue
if msg.startswith("odyCy fail count:"):
out["odycy_fail"] += int(msg.split(":")[1]); continue
for name, needle in skip_needles:
if needle in msg:
out["skips"][name] += 1; break
return out
def summarize(a, label):
tot_dich = sum(a["credit_dich"].values())
mods = []
for m in MODULES:
mods.append(dict(module=m, tokens=a["credit_tok"][m], dichrona=a["credit_dich"][m],
share_of_resolved=a["credit_dich"][m] / tot_dich if tot_dich else 0,
solo_tokens=a["solo_tok"][m], solo_short_marks=a["solo_short"][m], solo_long_marks=a["solo_long"][m],
first_in_cascade=a["first_module"][m]))
sp = a["sent_pos"]
amb_by_pos = [(p, n, sp[p], n / sp[p]) for p, n in a["amb_pos"].most_common()]
feat = sorted([(pos, kv, n, a["sent_feat"][(pos, kv)], n / a["sent_feat"][(pos, kv)])
for (pos, kv), n in a["amb_feat"].items() if a["sent_feat"][(pos, kv)] >= 20000],
key=lambda x: -x[4])
cum, curve, tot_amb = 0, [], a["amb_tok"]
for i, (f, n) in enumerate(a["amb_form"].most_common(), 1):
cum += n
if i in (10, 100, 1000, 10000, 100000):
curve.append((i, cum, cum / tot_amb if tot_amb else 0))
freq_rate = sorted([(f, a["amb_tokform"][f], a["sent_form"][f], a["amb_tokform"][f] / a["sent_form"][f])
for f in a["sent_form"] if a["sent_form"][f] >= 1000 and a["amb_tokform"][f]],
key=lambda x: (-x[3], -x[2]))[:60]
lem_rate = sorted([(l, p, a["amb_lemma"][(l, p)], a["sent_lemma"][(l, p)], a["amb_lemma"][(l, p)] / a["sent_lemma"][(l, p)])
for (l, p) in a["sent_lemma"] if a["sent_lemma"][(l, p)] >= 2000 and a["amb_lemma"][(l, p)]],
key=lambda x: -x[4])[:60]
return dict(
label=label, tokens_sent=a["tokens"], dichrona_in_tokens_sent=a["before"], resolved=a["before"] - a["after"],
unresolved=a["after"], credited=tot_dich, marks_added_short=a["resolved_short"], marks_added_long=a["resolved_long"],
modules=mods, modules_per_token=sorted(a["n_modules"].items()),
credit_by_module_pos=[(m, p, n) for (m, p), n in a["credit_pos"].most_common(80)],
abstentions=dict(tokens=a["amb_tok"], unresolved_dichrona=a["amb_dich"], partially_marked=a["amb_partial"],
rate=a["amb_tok"] / a["tokens"] if a["tokens"] else 0,
unique_forms=len(a["amb_form"]), unique_lemmas=len(a["amb_lemma"]),
hapax_forms=sum(1 for n in a["amb_form"].values() if n == 1),
by_pos=amb_by_pos, by_feature=feat,
by_shape={k: (a["amb_shape"][k], a["sent_shape"][k]) for k in ("lunate", "capitalized", "elided")},
unresolved_syllables_per_token=sorted(a["amb_nunres"].items()),
by_vowel=a["unresolved_vowel"].most_common(),
by_vowel_position_accent=[(*k, n) for k, n in a["amb_syl"].most_common()],
top_forms=[(f, n, *a["amb_form_info"][f], a["sent_form"].get(f.replace("^", "").replace("_", ""), 0)) for f, n in a["amb_form"].most_common(150)],
top_lemmas=[(l, p, n, a["sent_lemma"][(l, p)]) for (l, p), n in a["amb_lemma"].most_common(150)],
coverage_curve=curve, frequent_forms_highest_rate=freq_rate, frequent_lemmas_highest_rate=lem_rate))
def main():
global HF_KEEP
diag, rerun, hf_dir, out_dir, workers = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5])
os.makedirs(out_dir, exist_ok=True)
R = {}
# 1. logs: funnel and sentences per chunk
logs = sorted(glob.glob(os.path.join(diag, "logs", "*.log")))
with Pool(workers) as pool:
L = None
for r in pool.imap_unordered(do_log, logs):
if L is None: L = r; continue
L["skips"].update(r["skips"]); L["considered_pos"].update(r["considered_pos"])
L["odycy_fail"] += r["odycy_fail"]; L["chunk_sentences"].update(r["chunk_sentences"]); L["lines"] += r["lines"]
print(f"logs: {len(logs)} files, {L['lines']:,} lines, {len(L['chunk_sentences'])} chunks", flush=True)
# 2. HF membership per output line
hf = C()
for f in sorted(glob.glob(os.path.join(hf_dir, "*.parquet"))):
hf.update(pq.read_table(f, columns=["macronized"]).column(0).to_pylist())
n_hf = sum(hf.values())
keep, line_jobs, mism = {}, [], []
for f in sorted(glob.glob(os.path.join(rerun, "parts", "*.txt"))):
stem = os.path.basename(f)[:-4]
lines = open(f, encoding="utf-8").read().splitlines()
rows = [r.split("\t") for r in open(os.path.join(rerun, "parts", stem + ".progress"), encoding="utf-8").read().splitlines()]
for r in rows:
exp = L["chunk_sentences"].get(f"{stem}.{int(r[0]):05d}")
if exp is not None and exp != int(r[2]):
mism.append((stem, int(r[0]), exp, int(r[2])))
flags = []
s = set()
for i, line in enumerate(lines):
ok = hf[line] > 0
if ok:
hf[line] -= 1
s.add((i // CHUNK, i % CHUNK))
flags.append(ok)
keep[stem] = s
line_jobs.append((stem, lines, flags))
unmatched = sum(v for v in hf.values() if v > 0)
R["membership"] = dict(hf_sentences=n_hf, matched=n_hf - unmatched, unmatched_hf_lines=unmatched,
chunks_with_line_count_mismatch=mism[:50], n_mismatch=len(mism))
print("membership:", R["membership"], flush=True)
HF_KEEP = keep
# 3. dichrona ratios per line (HF and all), per work
per_work = {}
with Pool(workers) as pool:
tot = C()
for stem, c in pool.imap_unordered(do_lines, line_jobs, chunksize=4):
per_work[stem] = c; tot.update(c)
R["ratio"] = {k: dict(lines=tot[(k, "lines")], dichrona=tot[(k, "before")], unmarked=tot[(k, "after")],
marked=tot[(k, "before")] - tot[(k, "after")],
ratio=(tot[(k, "before")] - tot[(k, "after")]) / tot[(k, "before")]) for k in ("all", "hf")}
R["works"] = {s: dict(lines=c[("hf", "lines")], dichrona=c[("hf", "before")], unmarked=c[("hf", "after")],
all_lines=c[("all", "lines")]) for s, c in per_work.items()}
print("ratio:", R["ratio"], flush=True)
del line_jobs
# 4. traces
traces = sorted(glob.glob(os.path.join(diag, "traces", "*.tsv")))
with Pool(workers) as pool:
H = A = None
for i, (h, a) in enumerate(pool.imap_unordered(do_trace, traces, chunksize=8)):
H = h if H is None else merge(H, h); A = a if A is None else merge(A, a)
if i % 500 == 0: print(f" traces {i}/{len(traces)}", flush=True)
R["hf"] = summarize(H, "Urdatorn/oga-macronized-no-norma (5d737f8)")
R["all"] = summarize(A, "all OGA sentences")
R["funnel_all_oga"] = dict(considered=sum(L["considered_pos"].values()), considered_pos=L["considered_pos"].most_common(),
skips=L["skips"].most_common(), odycy_fail=L["odycy_fail"], sent=A["tokens"])
mods_tsv = os.path.join(rerun, "oga_macronized_modules.tsv")
R["module_events_all_oga"] = open(mods_tsv, encoding="utf-8").read() if os.path.exists(mods_tsv) else None
with open(os.path.join(out_dir, "stats.json"), "w", encoding="utf-8") as f:
json.dump(R, f, ensure_ascii=False, indent=1, default=str)
with open(os.path.join(out_dir, "abstained_forms_hf.tsv"), "w", encoding="utf-8") as f:
f.write("abstained\tsent_to_modules\tform\tlemma\tpos\tmorph\n")
for form, n in H["amb_form"].most_common():
plain = form.replace("^", "").replace("_", "")
f.write(f"{n}\t{H['sent_form'].get(plain, 0)}\t{form}\t" + "\t".join(H["amb_form_info"][form]) + "\n")
print("done", flush=True)
if __name__ == "__main__":
main()
|