"""Single evaluation module used by EVERY experiment. Metrics (the guide's evaluation section): * token-level precision / recall / F1 of predicted words vs gold words * sentence-level exact match * split-location accuracy: were boundaries placed in the right positions, regardless of the sandhi form produced * compound-internal vs between-word splits reported separately Token P/R/F1 use MULTISET matching: a word repeated twice in gold must be predicted twice to count twice. Set matching would silently inflate scores on verses with repeated particles (ca, na, kaḥ), which are everywhere in the epics. Split-location accuracy works on the SANDHIED string. Each gold word is matched left-to-right to a character offset in the sandhied text, giving a set of boundary offsets; the same is done for the prediction and the two sets are compared. This is what isolates "knew where to cut" from "produced the right sandhi form". """ from __future__ import annotations import collections from dataclasses import dataclass from rapidfuzz.distance import Levenshtein def words(s: str) -> list[str]: return s.split() # ---------------------------------------------------------------- token level def token_counts(pred: str, gold: str) -> tuple[int, int, int]: """(matched, n_pred, n_gold) under multiset matching.""" p = collections.Counter(words(pred)) g = collections.Counter(words(gold)) matched = sum((p & g).values()) return matched, sum(p.values()), sum(g.values()) def prf(matched: int, n_pred: int, n_gold: int) -> tuple[float, float, float]: prec = matched / n_pred if n_pred else 0.0 rec = matched / n_gold if n_gold else 0.0 f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0 return prec, rec, f1 # ------------------------------------------------------------ split locations def _position_map(src: str, dest: str) -> list[int]: """Map every character position of `src` onto a position of `dest`. Uses a Levenshtein alignment rather than a greedy character scan: sandhi deletes, inserts and substitutes characters, and a greedy scan silently mis-aligns when a character recurs later in the string (which it does constantly in Sanskrit). Returns a list of length len(src)+1. """ pos = [0] * (len(src) + 1) for tag, s1, s2, d1, d2 in Levenshtein.opcodes(src, dest): span_s = s2 - s1 span_d = d2 - d1 for k in range(span_s): if span_s == 0: continue # proportional placement inside the aligned block pos[s1 + k] = d1 + (k * span_d) // span_s if span_s else d1 pos[len(src)] = len(dest) # enforce monotonicity: alignment positions must not go backwards run = 0 for i in range(len(pos)): run = max(run, pos[i]) pos[i] = run return pos def boundary_offsets(split: str, sandhied: str) -> set[int] | None: """Character offsets in `sandhied` where `split`'s word boundaries fall. The split's words are concatenated (spaces removed) and aligned to the sandhied string; each internal word boundary is then expressed as an offset in the sandhied string. This is what lets split-location accuracy ignore which sandhi form the model produced and ask only "did it cut here". """ ws = words(split) if not ws: return None dest = sandhied.replace(" ", "") src = "".join(ws) if not src or not dest: return None pos = _position_map(src, dest) offsets, run = set(), 0 for w in ws[:-1]: run += len(w) offsets.add(pos[run]) return offsets @dataclass class Metrics: n: int = 0 tok_matched: int = 0 tok_pred: int = 0 tok_gold: int = 0 exact: int = 0 loc_matched: int = 0 loc_pred: int = 0 loc_gold: int = 0 loc_failed: int = 0 def add(self, pred: str, gold: str, sandhied: str | None = None) -> None: self.n += 1 m, np_, ng = token_counts(pred, gold) self.tok_matched += m self.tok_pred += np_ self.tok_gold += ng if words(pred) == words(gold): self.exact += 1 if sandhied: bp = boundary_offsets(pred, sandhied) bg = boundary_offsets(gold, sandhied) if bp is None or bg is None: self.loc_failed += 1 else: self.loc_matched += len(bp & bg) self.loc_pred += len(bp) self.loc_gold += len(bg) def report(self) -> dict: p, r, f = prf(self.tok_matched, self.tok_pred, self.tok_gold) lp, lr, lf = prf(self.loc_matched, self.loc_pred, self.loc_gold) return { "n": self.n, "token_precision": 100 * p, "token_recall": 100 * r, "token_f1": 100 * f, "sentence_exact_match": 100 * self.exact / self.n if self.n else 0.0, "split_location_precision": 100 * lp, "split_location_recall": 100 * lr, "split_location_f1": 100 * lf, "split_location_align_failures": self.loc_failed, } def evaluate(pairs) -> dict: """pairs: iterable of (pred, gold) or (pred, gold, sandhied).""" m = Metrics() for item in pairs: if len(item) == 3: m.add(item[0], item[1], item[2]) else: m.add(item[0], item[1]) return m.report()