#!/usr/bin/env python3
"""Fix names and jargon in a transcript without touching its timing.
Usage: python3 clean-transcript.py in.(srt|vtt|txt) fixes.tsv out
fixes.tsv: one fix per line, wrong<TAB>right (whole words, case-sensitive; lines starting with # are skipped).
Only text lines are changed: cue numbers, time lines and the WEBVTT header are copied as they are.
Exit 0 = done, 2 = missing or empty input or fixes file, or the output file cannot be written.
It also edits the text of NOTE blocks and of cue identifiers that are not digits; keep your fixes list to words you want changed everywhere."""
import re, sys

TIME = re.compile(r"-->")
def main(argv):
    if len(argv) != 4: print("usage: clean-transcript.py in fixes.tsv out"); return 2
    try:
        src = open(argv[1], "rb").read().decode("utf-8-sig"); fx = open(argv[2], "rb").read().decode("utf-8-sig")
    except OSError as e: print(f"cannot open {e.filename}: {e.strerror}"); return 2
    except UnicodeDecodeError: print("input files must be UTF-8 text"); return 2
    if not src.strip(): print(f"{argv[1]} is empty"); return 2
    fixes = []
    for ln in fx.replace("\r", "").split("\n"):
        if ln.strip() and not ln.startswith("#") and "\t" in ln:
            a, b = ln.split("\t", 1); fixes.append((re.compile(rf"(?<!\w){re.escape(a.strip())}(?!\w)"), b.strip(), a.strip()))
    if not fixes: print("fixes.tsv has no wrong<TAB>right lines"); return 2
    nl = "\r\n" if "\r\n" in src else "\n"
    out, counts = [], {a: 0 for _, _, a in fixes}
    for ln in src.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
        keep = TIME.search(ln) or ln.strip().isdigit() or ln.startswith("WEBVTT") or not ln.strip()
        if not keep:
            for rx, right, a in fixes:
                ln, n = rx.subn(lambda _m, r=right: r, ln); counts[a] += n
        out.append(ln)
    try: open(argv[3], "w", encoding="utf-8", newline="").write(nl.join(out))
    except OSError as e: print(f"cannot write {argv[3]}: {e.strerror}"); return 2
    for a, n in counts.items(): print(f"{a}: {n} replaced")
    return 0

if __name__ == "__main__": sys.exit(main(sys.argv))
