Makron-code / analysis /scripts /analyze_diagnostics.py
Urdatorn's picture
OGA macronizer diagnostics: module contributions and abstentions on the HF silver data
726fc64 verified
Raw History Blame Contribute Delete
13.8 kB
"""Statistics from the grc-macronizer diagnostics of the OGA run (job 5709453).
Inputs (an unpacked diagnostics/ directory):
logs/*.log debug log; 32 worker processes wrote into one file, so lines are
interleaved and only line-local facts are used
modules/*_<module>_results.txt per Macronizer() call (one per 500-sentence chunk): every token
form a module helped macronize (a "success event"; recursive
passes re-run the cascade, so events overlap across modules)
still_ambiguous/*.tsv per call: count, form, lemma, POS, morph of every token that kept
an unmarked dichronon in an open syllable (abstentions)
plus the run's parts/*.done files (per-work numerator/denominator).
Usage: python analyze_diagnostics.py DIAG_DIR PARTS_DIR OUT_DIR WORKERS
"""
import collections, glob, json, os, re, sys, unicodedata
from multiprocessing import Pool
from grc_utils import (count_dichrona_in_open_syllables, open_syllable_in_word, syllabifier,
word_with_real_dichrona)
C = collections.Counter
MODULE_ORDER = ["custom", "wiktionary", "lsj", "nominal_forms", "verbal_forms", "accent_rules",
"prefix", "double_accent_recursion", "reversed_elision_recursion",
"case_ending_recursion", "oxytonization", "decapitalization", "hypotactic"]
# names as they appear in the log's ✅/❌ lines -> module
LOG_MODULE = {"Custom": "custom", "Wiktionary": "wiktionary", "LSJ": "lsj",
"Nominal forms": "nominal_forms", "Verbal forms": "verbal_forms",
"Accent rules": "accent_rules", "Prefix macronization": "prefix",
"Double accent macronization": "double_accent_recursion",
"Reversed elision": "reversed_elision_recursion",
"Wrong-case-ending (D2)": "case_ending_recursion",
"Wrong-case-ending (D1)": "case_ending_recursion",
"Oxytonizing": "oxytonization", "Decapitalization": "decapitalization",
"Hypotactic": "hypotactic"}
R_TOKEN = re.compile(r"^(Considering token|\tAppended: \tToken): (.*?)\tLemma: (.*?)\tPOS: (.*?)\tMorph: (.*)$")
R_MOD = re.compile(r"^\t(✅|❌) (.+?)(?: with [αει] helped| with [αει] did not help| helped| did not help|:)")
R_ARROW = re.compile(r" (\S+) => (\S+), with (\d+) left")
R_LEFT = re.compile(r"(\d+) left")
R_PASS = re.compile(r"^🔄 Macronizing(?: \((.*?)\))?: ")
SKIPS = [("no dichrona", "has no dichrona"), ("not in diagnostic word list", "not in diagnostic word list"),
("Greek numeral", "is a Greek numeral"), ("general stop word", "General stop word"),
("epic stop word", "Epic stop word"), ("final sigma mid-word", "final sigma mid-word"),
("pathological accents/breathings", "Pathological word")]
def word_shape(form):
f = form
return dict(lunate="ϲ" in f, capitalized=bool(f) and f[0].isupper(), elided=f.endswith("'"))
def parse_log_range(args):
path, start, end = args
out = dict(considered_pos=C(), sent_pos=C(), sent_feat=C(), sent_shape=C(), sent_form=C(),
sent_lemma=C(), skips=C(), stop_forms=C(), notdiag_forms=C(), passes=C(),
mod_try=C(), mod_ok=C(), mod_full=C(), mod_added=C(), mod_example=collections.defaultdict(C),
odycy_fail=0, sent_total=0, lines=0, other=C())
with open(path, "rb") as fh:
fh.seek(start)
if start:
fh.readline()
while fh.tell() <= end:
raw = fh.readline()
if not raw:
break
out["lines"] += 1
s = raw.decode("utf-8", "replace").rstrip("\n")
parts = s.split(" - ", 1)
if len(parts) < 2:
continue
msg = parts[1]
m = R_TOKEN.match(msg)
if m:
kind, tok, lemma, pos, morph = m.groups()
if kind == "Considering token":
out["considered_pos"][pos] += 1
else:
out["sent_total"] += 1
out["sent_pos"][pos] += 1
out["sent_form"][tok] += 1
out["sent_lemma"][(lemma, pos)] += 1
for kv in morph.split("|"):
if "=" in kv:
out["sent_feat"][(pos, kv)] += 1
for k, v in word_shape(tok).items():
if v:
out["sent_shape"][k] += 1
continue
m = R_MOD.match(msg)
if m:
ok, name = m.group(1) == "✅", m.group(2)
if name.startswith("Reversed elision"):
name = "Reversed elision"
mod = LOG_MODULE.get(name)
if mod is None:
out["other"]["module?" + name[:40]] += 1
continue
out["mod_try"][mod] += 1
if ok:
out["mod_ok"][mod] += 1
a = R_ARROW.search(msg)
if a:
old, new, left = a.group(1), a.group(2), int(a.group(3))
out["mod_added"][(mod, "^")] += max(0, new.count("^") - old.count("^"))
out["mod_added"][(mod, "_")] += max(0, new.count("_") - old.count("_"))
if left == 0:
out["mod_full"][mod] += 1
else:
l = R_LEFT.search(msg)
if l and int(l.group(1)) == 0:
out["mod_full"][mod] += 1
continue
m = R_PASS.match(msg)
if m:
out["passes"][m.group(1) or "top level / double accent"] += 1
continue
if msg.startswith("Sending to macronization_modules"):
continue
if msg.startswith("odyCy fail count:"):
out["odycy_fail"] += int(msg.split(":")[1])
continue
for name, needle in SKIPS:
if needle in msg:
out["skips"][name] += 1
w = re.search(r"'(.*?)'", msg)
if w and name in ("general stop word", "epic stop word"):
out["stop_forms"][w.group(1)] += 1
if w and name == "not in diagnostic word list":
out["notdiag_forms"][w.group(1)] += 1
break
else:
key = re.sub(r"\d+", "N", re.sub(r"[Ͱ-Ͽἀ-῿^_'’ϲ]+", "W", msg))[:60]
out["other"][key] += 1
return out
def merge(a, b):
for k, v in b.items():
if isinstance(v, collections.defaultdict):
for kk, vv in v.items():
a[k][kk].update(vv)
elif isinstance(v, C):
a[k].update(v)
else:
a[k] += v
return a
def unresolved_syllables(form):
"""(vowel, syllable position from the end, accent on it) for every unmarked dichronon in an
open syllable, using the same rule as count_dichrona_in_open_syllables (word in isolation)."""
out = []
w = re.sub(r"[^\w^_']", "", unicodedata.normalize("NFC", form))
if not w:
return out
try:
syls = syllabifier(w)
except Exception:
return out
n = len(syls)
for i, s in enumerate(syls):
if word_with_real_dichrona(s) and open_syllable_in_word(s, syls) and not any(c in "^_" for c in s):
vowel, acc = "?", "none"
for ch in s:
d = unicodedata.normalize("NFD", ch)
if d and d[0].lower() in "αιυ":
vowel = d[0].lower()
if "́" in d: acc = "acute"
elif "̀" in d: acc = "grave"
elif "͂" in d: acc = "circumflex"
pos = n - i
out.append((vowel, "ultima" if pos == 1 else "penult" if pos == 2 else "antepenult+", acc))
return out
def main():
diag, parts_dir, out_dir, workers = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4])
os.makedirs(out_dir, exist_ok=True)
R = {}
# ---- log ----
log = glob.glob(os.path.join(diag, "logs", "*.log"))[0]
size = os.path.getsize(log)
step = size // (workers * 8) + 1
ranges = [(log, s, min(size, s + step)) for s in range(0, size, step)]
print(f"log {log}: {size/1e9:.1f} GB in {len(ranges)} ranges", flush=True)
with Pool(workers) as pool:
L = None
for i, r in enumerate(pool.imap_unordered(parse_log_range, ranges)):
L = r if L is None else merge(L, r)
if i % 32 == 0:
print(f" log ranges done {i+1}/{len(ranges)}", flush=True)
R["log"] = dict(lines=L["lines"], sent_total=L["sent_total"], odycy_fail=L["odycy_fail"],
considered_pos=L["considered_pos"].most_common(), sent_pos=L["sent_pos"].most_common(),
skips=L["skips"].most_common(), passes=L["passes"].most_common(),
sent_shape=dict(L["sent_shape"]),
modules={m: dict(tries=L["mod_try"][m], successes=L["mod_ok"][m], completed=L["mod_full"][m],
added_short=L["mod_added"][(m, "^")], added_long=L["mod_added"][(m, "_")])
for m in MODULE_ORDER},
top_stop_words=L["stop_forms"].most_common(40),
top_not_in_diag=L["notdiag_forms"].most_common(40),
other_messages=L["other"].most_common(40))
# ---- module result files ----
mods = {m: C() for m in MODULE_ORDER}
for f in glob.glob(os.path.join(diag, "modules", "*_results.txt")):
name = re.sub(r"^\d+_\d+_\d+_\d+_", "", os.path.basename(f))[:-len("_results.txt")]
with open(f, encoding="utf-8") as fh:
mods[name].update(l.rstrip("\n") for l in fh if l.strip())
R["module_files"] = {m: dict(events=sum(c.values()), unique_forms=len(c), top=c.most_common(25)) for m, c in mods.items()}
# ---- abstentions ----
amb = C(); amb_info = {}
for f in glob.glob(os.path.join(diag, "still_ambiguous", "*.tsv")):
with open(f, encoding="utf-8") as fh:
for line in fh:
p = line.rstrip("\n").split("\t")
if len(p) < 5:
continue
amb[p[1]] += int(p[0])
amb_info.setdefault(p[1], (p[2], p[3], p[4]))
tot_occ = sum(amb.values())
pos_c, feat_c, lemma_c, shape_c, syl_c, nsyl_c, partial = C(), C(), C(), C(), C(), C(), 0
unresolved_total = 0
for form, n in amb.items():
lemma, pos, morph = amb_info[form]
pos_c[pos] += n
lemma_c[(lemma, pos)] += n
for kv in morph.split("|"):
if "=" in kv:
feat_c[(pos, kv)] += n
for k, v in word_shape(form).items():
if v:
shape_c[k] += n
if "^" in form or "_" in form:
partial += n
us = unresolved_syllables(form)
k = len(us)
nsyl_c[min(k, 3)] += n
unresolved_total += max(k, count_dichrona_in_open_syllables(form)) * n
for v, where, acc in us:
syl_c[(v, where, acc)] += n
sent_pos = L["sent_pos"]
R["abstentions"] = dict(
occurrences=tot_occ, unique_forms=len(amb), unique_lemmas=len(lemma_c),
partially_marked=partial, unresolved_positions=unresolved_total,
by_pos=[(p, n, sent_pos[p], n / sent_pos[p] if sent_pos[p] else None) for p, n in pos_c.most_common()],
by_feature=sorted([(pos, kv, n, L["sent_feat"][(pos, kv)], n / L["sent_feat"][(pos, kv)] if L["sent_feat"][(pos, kv)] else None)
for (pos, kv), n in feat_c.items() if n >= 2000], key=lambda x: -x[2]),
by_shape={k: (shape_c[k], L["sent_shape"][k]) for k in ("lunate", "capitalized", "elided")},
unresolved_per_token=sorted(nsyl_c.items()),
by_vowel_position_accent=[(v, w, a, n) for (v, w, a), n in syl_c.most_common()],
top_forms=[(f, n, *amb_info[f], L["sent_form"][f]) for f, n in amb.most_common(150)],
top_lemmas=[(l, p, n, L["sent_lemma"][(l, p)]) for (l, p), n in lemma_c.most_common(150)],
)
cum, curve = 0, []
marks = [10, 100, 1000, 10000, 100000]
for i, (f, n) in enumerate(amb.most_common(), 1):
cum += n
if i in marks:
curve.append((i, cum, cum / tot_occ))
R["abstentions"]["coverage_curve"] = curve
R["abstentions"]["hapax_forms"] = sum(1 for n in amb.values() if n == 1)
# most frequent forms always vs sometimes abstained
rate = [(f, amb[f], L["sent_form"][f], amb[f] / L["sent_form"][f]) for f in L["sent_form"] if L["sent_form"][f] >= 500 and f in amb]
R["abstentions"]["frequent_forms_highest_rate"] = sorted(rate, key=lambda x: (-x[3], -x[2]))[:60]
# ---- per work ----
works = []
for d in glob.glob(os.path.join(parts_dir, "*.done")):
n_lines, num, den = map(int, open(d).read().split("\t"))
stem = os.path.basename(d)[:-5]
works.append((stem, n_lines, num, den))
R["works"] = works
with open(os.path.join(out_dir, "diagnostics_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.tsv"), "w", encoding="utf-8") as f:
f.write("count\tsent_to_modules\tform\tlemma\tpos\tmorph\n")
for form, n in amb.most_common():
f.write(f"{n}\t{L['sent_form'][form]}\t{form}\t" + "\t".join(amb_info[form]) + "\n")
print("done", flush=True)
if __name__ == "__main__":
main()