#!/usr/bin/env python3 """Check a published KolWrite Oracle Max benchmark (any language) from its per-clip file. Usage: python3 check_wer.py [--decimals N] [--clean arabic] (with no file, the Hebrew file beside this script is read; the Hebrew page uses one decimal, the other pages two: --decimals 2) Python 3.8 or newer, standard library only. No network, no key, nothing is sent anywhere. What it does, in order: 1. Prints the SHA-256 of the file, to compare with the one on the benchmark page. 2. Recounts the word errors of every clip from the cleaned texts in the file (word by word edit distance between norm_reference_text and norm_predicted_text) and compares the total with the counts stored in the file's substitutions, deletions and insertions columns. 3. Prints the corpus word error rate: all errors divided by all reference words, over all clips. 4. Prints the 95% interval by bootstrap: the 792 clips are resampled 10,000 times, each resample gives a word error rate, and the interval is the 2.5th and 97.5th percentile of those rates. The random numbers are numpy's Generator(PCG64(seed 20261121)).integers(0, 792), written out here in pure Python, so the interval is the same as the one computed with numpy, digit for digit. What it does not do: it does not clean the text. The cleaning is the leaderboard's own code, listed on each page; the file holds both the raw and the cleaned text so you can apply that code yourself and compare. The one exception is Arabic: the leaderboard states its cleaning rules in prose and publishes no code, so the rules as we read them are written out below (aura_clean), and `--clean arabic` applies them to the raw columns and checks that the file's cleaned columns are exactly that. Word errors are counted by plain edit distance. The leaderboards' own scorers (used for the other languages) also merge compound splits, so on a few clips this recount can differ from the stored counts by a word; the script says how many clips differ. The word error rate it prints always uses the stored counts, which are the scorer's. """ import csv import hashlib import os import re import sys import unicodedata RESAMPLES = 10000 SEED = 20261121 M32 = 0xFFFFFFFF M64 = (1 << 64) - 1 M128 = (1 << 128) - 1 PCG_MULT = 47026247687942121848144207491837523525 def seed_words(entropy): """numpy SeedSequence(entropy).generate_state(4, uint64), for an entropy that fits in 32 bits.""" def hashmix(value, const): value ^= const const = (const * 0x931E8875) & M32 value = (value * const) & M32 value ^= value >> 16 return value, const def mix(x, y): result = (0xCA01F9DD * x - 0x4973F715 * y) & M32 return result ^ (result >> 16) pool = [0, 0, 0, 0] const = 0x43B0D7E5 for i in range(4): pool[i], const = hashmix(entropy & M32 if i == 0 else 0, const) for src in range(4): for dst in range(4): if src != dst: value, const = hashmix(pool[src], const) pool[dst] = mix(pool[dst], value) const = 0x8B51F9DD state = [] for i in range(8): value = pool[i % 4] ^ const const = (const * 0x58F38DED) & M32 value = (value * const) & M32 state.append(value ^ (value >> 16)) return [state[2 * j] | (state[2 * j + 1] << 32) for j in range(4)] class Pcg64: """numpy's PCG64 bit generator, and the way Generator.integers(0, n) draws from it.""" def __init__(self, seed): words = seed_words(seed) init_state = (words[0] << 64) | words[1] init_seq = (words[2] << 64) | words[3] self.inc = ((init_seq << 1) | 1) & M128 self.state = 0 self.state = (self.state * PCG_MULT + self.inc) & M128 self.state = (self.state + init_state) & M128 self.state = (self.state * PCG_MULT + self.inc) & M128 self.spare = None def next64(self): self.state = (self.state * PCG_MULT + self.inc) & M128 state = self.state value = ((state >> 64) ^ state) & M64 rot = state >> 122 return ((value >> rot) | (value << ((-rot) & 63))) & M64 def next32(self): if self.spare is not None: value, self.spare = self.spare, None return value value = self.next64() self.spare = value >> 32 return value & M32 def below(self, n): """Uniform integer in [0, n), Lemire's method as numpy does it.""" product = self.next32() * n low = product & M32 if low < n: threshold = (M32 - (n - 1)) % n while low < threshold: product = self.next32() * n low = product & M32 return product >> 32 _AR_MARKS = re.compile("[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06ED]") def aura_clean(text): """The QCRI AURA leaderboard's text cleaning as its page states it (no code is published): drop Arabic diacritics and tatweel; fold the alef variants to bare alef; keep Arabic letters, Latin letters (lower case), digits, @ and %; keep . or , only between two digits and an apostrophe only between two characters; every other character becomes a space; collapse spaces.""" text = _AR_MARKS.sub("", text or "").replace("\u0640", "") text = re.sub("[\u0622\u0623\u0625\u0671\u0672\u0673]", "\u0627", text) out = [] for i, ch in enumerate(text): prev = text[i - 1] if i else "" nxt = text[i + 1] if i + 1 < len(text) else "" if ch in ".," and prev.isdigit() and nxt.isdigit(): out.append(ch) elif ch in "'\u2019" and prev and nxt and not prev.isspace() and not nxt.isspace(): out.append("'") elif ch in "@%" or ch.isspace() or ch.isdigit(): out.append(ch) elif "\u0600" <= ch <= "\u06FF" and unicodedata.category(ch).startswith("L"): out.append(ch) elif ch.isascii() and ch.isalpha(): out.append(ch.lower()) else: out.append(" ") return re.sub(r"\s+", " ", "".join(out)).strip() def edit_distance(ref, hyp): """Smallest number of word substitutions, deletions and insertions that turns ref into hyp.""" previous = list(range(len(hyp) + 1)) for i, r in enumerate(ref, 1): current = [i] for j, h in enumerate(hyp, 1): current.append(min(previous[j - 1] + (r != h), previous[j] + 1, current[j - 1] + 1)) previous = current return previous[-1] def percentile(sorted_values, p): """numpy.percentile with linear interpolation.""" position = p / 100 * (len(sorted_values) - 1) low = int(position) fraction = position - low if low + 1 >= len(sorted_values): return sorted_values[low] return sorted_values[low] + (sorted_values[low + 1] - sorted_values[low]) * fraction def show(label, value): print("%-24s %s" % (label, value)) def main(): here = os.path.dirname(os.path.abspath(__file__)) args = sys.argv[1:] decimals, clean = 1, None if "--decimals" in args: at = args.index("--decimals") decimals = int(args[at + 1]) del args[at:at + 2] if "--clean" in args: at = args.index("--clean") clean = args[at + 1] del args[at:at + 2] path = args[0] if args else os.path.join(here, "oracle-max-hebrew-fleurs-792-2026-11-21.csv") with open(path, "rb") as handle: raw = handle.read() show("file", os.path.basename(path)) show("sha256", hashlib.sha256(raw).hexdigest()) with open(path, newline="", encoding="utf-8") as handle: rows = list(csv.DictReader(handle)) stored = {key: 0 for key in ("substitutions", "deletions", "insertions", "hits")} errors = [] words = [] recount = 0 clips_differing = 0 for row in rows: s, d, i, h = (int(row[key]) for key in ("substitutions", "deletions", "insertions", "hits")) for key, value in zip(stored, (s, d, i, h)): stored[key] += value errors.append(s + d + i) words.append(s + d + h) counted = edit_distance(row["norm_reference_text"].split(), row["norm_predicted_text"].split()) recount += counted if counted != s + d + i: clips_differing += 1 total_errors = sum(errors) total_words = sum(words) clips = len(rows) show("clips", clips) show("reference words", total_words) show("word errors", "%d (substitutions %d, deletions %d, insertions %d)" % (total_errors, stored["substitutions"], stored["deletions"], stored["insertions"])) show("recount from clean text", "%d word errors; %s" % (recount, "every clip matches the file" if clips_differing == 0 else "%d clips differ from the file (the scorer counts a compound split or joined, such as macro financial and " "macrofinancial, as one word; plain edit distance counts it as errors)" % clips_differing)) if clips_differing: show("rate of that plain recount", "%.*f%% (the published figure uses the scorer's stored counts)" % (decimals, 100 * recount / total_words)) if clean == "arabic": differing = sum(1 for row in rows if aura_clean(row.get("reference_text", row.get("reference", ""))) != row["norm_reference_text"] or aura_clean(row["predicted_text"]) != row["norm_predicted_text"]) show("cleaning check", "the cleaned columns equal the rules above on all %d clips" % clips if differing == 0 else "%d clips differ from the rules above" % differing) show("sentences with no error", "%d of %d" % (sum(1 for e in errors if e == 0), clips)) show("word error rate", "%.*f%%" % (decimals, 100 * total_errors / total_words)) rng = Pcg64(SEED) rates = [] for _ in range(RESAMPLES): e = w = 0 for _ in range(clips): k = rng.below(clips) e += errors[k] w += words[k] rates.append(e / w) rates.sort() low, high = percentile(rates, 2.5), percentile(rates, 97.5) show("95% interval", "%.*f%% to %.*f%% (%d resamples of the %d clips, seed %d, percentile; %.4f to %.4f)" % (decimals, 100 * low, decimals, 100 * high, RESAMPLES, clips, SEED, low, high)) if __name__ == "__main__": main()