# clean_subs.py: turns an .srt or .vtt file into plain text, one line per cue (Koldflux, 2026-11-20). Usage: python3 clean_subs.py file.srt > file.txt
import sys, re, html
TS = re.compile(r"^\s*(?:\d+:)?\d{1,2}:\d{2}[.,]\d{1,3}\s*-->\s*(?:\d+:)?\d{1,2}:\d{2}[.,]\d{1,3}")
def clean(path):
    raw = open(path, encoding="utf-8-sig").read().replace("\r\n", "\n").replace("\r", "\n")
    vtt = raw.lstrip().startswith("WEBVTT")
    lines = raw.split("\n"); out = []; i = 0; skip = False; cur = None; seen_last = []
    while i < len(lines):
        l = lines[i]
        if TS.match(l):
            if cur is not None: out.append(cur)
            cur = []; skip = False
        elif l.strip() == "":
            if cur is not None: out.append(cur); cur = None
            skip = False
        elif cur is None:
            if re.match(r"^(NOTE|STYLE|REGION)\b", l) or l.startswith("WEBVTT"): skip = True
            # cue numbers / ids before a timestamp line are dropped
        elif not skip:
            nxt = lines[i + 1] if i + 1 < len(lines) else ""
            if re.fullmatch(r"\d+", l.strip()) and TS.match(nxt): pass   # index of the next cue (missing blank line)
            else: cur.append(l)
        i += 1
    if cur is not None: out.append(cur)
    res = []; prev_last = None
    for c in out:
        lines = [x.strip() for x in c if x.strip()]
        # roll-up captions: a multi-line cue whose first line repeats the last line of the cue before
        body = lines[1:] if (prev_last is not None and len(lines) > 1 and lines[0] == prev_last) else lines
        if lines: prev_last = lines[-1]
        t = " ".join(body)
        t = re.sub(r"<[^>]*>", "", t); t = re.sub(r"\{\\[^}]*\}", "", t)
        if vtt: t = html.unescape(t)
        t = re.sub(r"[ \t]+", " ", t).strip()
        if t: res.append(t)
    return res
if __name__ == "__main__":
    print("\n".join(clean(sys.argv[1])))
