#!/usr/bin/env python3
"""Counts how many times each name in the reference text is wrong in a transcript, using the same alignment as wer.py (keep both files in one folder).
Usage: python3 names-wrong.py reference.txt transcript.txt "name1,name2,..."   (names lower-case, no accents)"""
import sys
from wer import words, align

def main(ref_path, hyp_path, names):
    try:
        ref = words(open(ref_path, encoding="utf-8", errors="replace").read())
        hyp = words(open(hyp_path, encoding="utf-8", errors="replace").read())
    except OSError as e:
        sys.exit("cannot read %s: %s" % (e.filename, e.strerror))
    if not ref:
        sys.exit("reference is empty")
    wanted = [n.strip().lower() for n in names.split(",") if n.strip()]
    if not wanted:
        sys.exit("no names given")
    _, ops = align(ref, hyp)
    wrong = {n: 0 for n in wanted}
    for kind, r, h in ops:
        if r in wrong and kind in ("sub", "del"):
            wrong[r] += 1
    tot = tot_wrong = 0
    for n in wanted:
        seen = ref.count(n)
        print("%s: %d of %d wrong" % (n, wrong[n], seen)); tot += seen; tot_wrong += wrong[n]
    print("all names: %d of %d wrong" % (tot_wrong, tot))

if __name__ == "__main__":
    if len(sys.argv) != 4:
        sys.exit('usage: python3 names-wrong.py reference.txt transcript.txt "name1,name2"')
    main(*sys.argv[1:])
