#!/usr/bin/env python3"""Score a voicegate run: word error rate and name hit rate, with and without hints. report.py <corpus.json> <heard.json> [--label <engine>]`heard.json` is what the harness wrote: {"engine": str, "runs": {run: [str]}, "trace": {run: [str]},"probes": [{voice, name, plain, hinted}]}, one heard line per corpus utterance, in corpus order. Printswhat the engine was handed, the synthesizer probe, one line per run (and per run with the names thesynthesizer cannot say left out), and the STATUS fragment."""import jsonimport reimport sysUNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()TENS = "_ _ twenty thirty forty fifty sixty seventy eighty ninety".split()ORDINAL = {"one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth"}def spell(n: int) -> str:if n < 20:return UNITS[n]if n < 100:return TENS[n // 10] + (""if n % 10 == 0else" " + UNITS[n % 10])if n < 1000:return UNITS[n // 100] + " hundred" + (""if n % 100 == 0else" " + spell(n % 100))if n < 1_000_000:return spell(n // 1000) + " thousand" + (""if n % 1000 == 0else" " + spell(n % 1000))return str(n)def ordinal(n: int) -> str: words = spell(n).split() last = words[-1]if last in ORDINAL: words[-1] = ORDINAL[last]elif last.endswith("y"): words[-1] = last[:-1] + "ieth"else: words[-1] = last + "th"return" ".join(words)def words(text): text = text.lower().replace("’", "'") text = re.sub(r"(\d),(\d)", r"\1\2", text) text = re.sub(r"\b(\d+)(st|nd|rd|th)\b", lambda m: ordinal(int(m.group(1))), text) text = re.sub(r"\b\d+\b", lambda m: spell(int(m.group(0))), text) text = re.sub(r"'s\b", "s", text) text = re.sub(r"[^a-z0-9' ]+", " ", text)return text.split()def edits(ref, hyp): row = list(range(len(hyp) + 1))for i, r in enumerate(ref, 1): prev, row[0] = row[0], ifor j, h in enumerate(hyp, 1): prev, row[j] = row[j], min(row[j] + 1, row[j - 1] + 1, prev + (r != h))return row[-1]def names_in(text, hints): joined = " " + " ".join(words(text)) + " " found = []for hint in sorted(hints, key=len, reverse=True): key = " " + " ".join(words(hint)) + " "if key in joined: found.append(hint) joined = joined.replace(key, " | ")return founddef hint_list(corpus):"""Every hinted term, and each person's names alone: a person is spoken of by full name or by one of their names.""" hints = [h for group in corpus["hints"].values() for h in group] hints += [part for person in corpus["hints"]["people"] for part in person.split()]return sorted(set(hints))def mangled(heard):"""The (voice, name) pairs the synthesizer cannot say: the name alone, in that voice, is not heard as the name with no hint NOR with the name as the only hint. Those mentions are the synthesizer's failure, not dictation's.""" out = set()for probe in heard.get("probes", []): heard_it = any(probe["name"] in names_in(probe[run], [probe["name"]]) for run in ("plain", "hinted"))ifnot heard_it: out.add((probe["voice"], probe["name"]))return outdef score(corpus, heard, voice=None, skip=frozenset()):"""`voice` overrides each line's own (the second-voice rendering); a mention whose (voice, name) is in `skip` is left out of the name rate.""" hints = hint_list(corpus) total_edits = total_words = name_total = name_hits = 0 misses = []if len(heard) != len(corpus["utterances"]): sys.exit(f"heard {len(heard)} lines for {len(corpus['utterances'])} utterances")for utterance, line in zip(corpus["utterances"], heard): ref = words(utterance["text"]) total_edits += edits(ref, words(line)) total_words += len(ref)for name in names_in(utterance["text"], hints):if (voice or utterance.get("voice"), name) in skip:continue name_total += 1if name in names_in(line, hints): name_hits += 1else: misses.append(name)return {"wer": total_edits / total_words, "names": name_hits, "of": name_total, "misses": misses}def main() -> None: args = sys.argv[1:] corpus = json.load(open(args[0])) heard = json.load(open(args[1])) second = corpus.get("second_voice")for run, lines in sorted(heard.get("trace", {}).items()):for line in lines: print(f"[engine received, {run} u01] {line}") bad = mangled(heard) probes = heard.get("probes", [])if probes:for voice in sorted({p["voice"] for p in probes}): mine = [p for p in probes if p["voice"] == voice] lost = sorted(n for v, n in bad if v == voice) print(f"[synth probe] {voice:9} {len(mine) - len(lost)}/{len(mine)} names sayable; cannot say: {', '.join(lost) or '-'}") out = {}for run in ("plain", "hinted", "model", "general", "rishi-plain", "rishi-hinted", "rishi-model"):if run notin heard["runs"]:continue voice = second if run.startswith("rishi-") elseNone out[run] = s = score(corpus, heard["runs"][run], voice) print(f"{run:13} WER {s['wer']:.1%} names {s['names']}/{s['of']} ({s['names'] / s['of']:.0%}) missed: {', '.join(s['misses']) or '-'}")if bad: out[run + " sayable"] = f = score(corpus, heard["runs"][run], voice, bad) print(f"{run + ' sayable':13} names {f['names']}/{f['of']} ({f['names'] / max(f['of'], 1):.0%}) — names the synthesizer cannot say left out")# The model against the hints alone, name by name on the SAME lines: what# the compiled model gained and what it lost.for prefix in ("", "rishi-"): a, b = prefix + "hinted", prefix + "model"if a notin heard["runs"] or b notin heard["runs"]:continue voice = second if prefix elseNone gained, lost, both = [], [], 0 hints = hint_list(corpus)for n, utterance in enumerate(corpus["utterances"]):for name in names_in(utterance["text"], hints):if (voice or utterance.get("voice"), name) in bad:continue with_hints = name in names_in(heard["runs"][a][n], hints) with_model = name in names_in(heard["runs"][b][n], hints) both += with_hints and with_modelif with_model andnot with_hints: gained.append(f"u{n + 1:02d} {name}")if with_hints andnot with_model: lost.append(f"u{n + 1:02d} {name}") print(f"[{prefix or 'mixed-'}same lines] sayable names with hints {out[a + ' sayable']['names'] if bad else out[a]['names']} " f"-> with model {out[b + ' sayable']['names'] if bad else out[b]['names']}; " f"gained: {', '.join(gained) or '-'}; lost: {', '.join(lost) or '-'}") frag = "; ".join( f"{run} WER {s['wer']:.1%} names {s['names']}/{s['of']}"if"sayable"notin run else f"{run} names {s['names']}/{s['of']}"for run, s in out.items()) print(f"[{heard['engine']}] {len(corpus['utterances'])} utterances — {frag}")if __name__ == "__main__": main()