#!/usr/bin/env bash
# Koldflux test: subtitles (SRT/VTT) to a clean transcript, 2026-11-20.
# Inputs: Sintel (CC BY 3.0, Blender Foundation, durian.blender.org) en/de SRT, Tears of Steel (CC BY 3.0, mango.blender.org) en SRT,
# a VTT made from Tears of Steel with ffmpeg, and 14 edge-case files whose correct transcript is written by hand below (known answers).
# Methods: 1) live https://koldflux.com/tools/subtitles/subtitle-to-transcript via Playwright, 2) ffmpeg -c:s text,
# 3) a common sed one-liner, 4) our independent Python reference. Usage: bash test-run.sh  (needs python3, ffmpeg, node + playwright)
set -euo pipefail
cd "$(dirname "$0")"; mkdir -p files edge out
D=files
[ -s $D/sintel_en.srt ] || curl -sL -o $D/sintel_en.srt https://durian.blender.org/wp-content/content/subtitles/sintel_en.srt
[ -s $D/sintel_de.srt ] || curl -sL -o $D/sintel_de.srt https://durian.blender.org/wp-content/content/subtitles/sintel_de.srt
[ -s $D/TOS-en.srt ] || curl -sL -o $D/TOS-en.srt https://download.blender.org/demo/movies/ToS/subtitles/TOS-en.srt
ffmpeg -loglevel error -y -i $D/TOS-en.srt $D/TOS-en.vtt
sha256sum $D/sintel_en.srt $D/sintel_de.srt $D/TOS-en.srt $D/TOS-en.vtt

# ---------- edge cases with hand-written expected transcripts ----------
python3 - <<'PY'
import json, os
E = {}
def add(name, ext, body, expected, note):
    E[name] = {"ext": ext, "expected": expected, "note": note}
    open(f"edge/{name}.{ext}", "w", encoding="utf-8", newline="").write(body)
add("e01-bom-crlf", "srt", "﻿1\r\n00:00:01,000 --> 00:00:02,500\r\nFirst line.\r\n\r\n2\r\n00:00:03,000 --> 00:00:04,000\r\nSecond line.\r\n", ["First line.", "Second line."], "UTF-8 BOM and Windows line endings")
add("e02-two-line-cue", "srt", "1\n00:00:01,000 --> 00:00:03,000\nThis sentence is split\nacross two lines.\n", ["This sentence is split across two lines."], "a cue on two lines")
add("e03-html-tags", "srt", "1\n00:00:01,000 --> 00:00:03,000\n<i>Quietly,</i> <b>now</b> <font color=\"#ffff00\">listen.</font>\n", ["Quietly, now listen."], "italic, bold and font tags")
add("e04-ass-position", "srt", "1\n00:00:01,000 --> 00:00:03,000\n{\\an8}Top of the screen.\n", ["Top of the screen."], "ASS position code {\\an8}")
add("e05-vtt-blocks", "vtt", "WEBVTT - demo\n\nNOTE written by the editor\nnot part of the speech\n\nSTYLE\n::cue { color: yellow }\n\nintro-1\n00:00:01.000 --> 00:00:03.000 align:start position:10%\nWelcome back.\n\n00:03.500 --> 00:05.000\nShort timestamps work too.\n", ["Welcome back.", "Short timestamps work too."], "VTT header, NOTE, STYLE, cue id, cue settings, mm:ss timestamps")
add("e06-vtt-voice", "vtt", "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\n<v Anna>Did you hear that?</v>\n\n00:00:03.500 --> 00:00:05.000\n<v.loud Ben>Yes!</v>\n", ["Did you hear that?", "Yes!"], "VTT voice tags (speaker names are markup)")
add("e07-vtt-entities", "vtt", "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nTom &amp; Jerry &lt;3 &gt; the rest&nbsp;of it\n", ["Tom & Jerry <3 > the rest of it"], "VTT escapes & < > as entities, readers expect the characters")
add("e08-rollup", "vtt", "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nso the first thing\n\n00:00:03.000 --> 00:00:05.000\nso the first thing\nyou want to check\n\n00:00:05.000 --> 00:00:07.000\nyou want to check\nis the audio level\n", ["so the first thing", "you want to check", "is the audio level"], "roll-up captions: each cue repeats the line before")
add("e09-word-timing", "vtt", "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nhello<00:00:01.500><c> everyone</c><00:00:02.000><c> and</c><00:00:02.400><c> welcome</c>\n", ["hello everyone and welcome"], "karaoke-style inline word timestamps")
add("e10-zero-duration", "srt", "1\n00:00:01,000 --> 00:00:02,000\nBefore.\n\n2\n00:00:05,000 --> 00:00:05,000\nA cue with no duration.\n\n3\n00:00:06,000 --> 00:00:07,000\nAfter.\n", ["Before.", "A cue with no duration.", "After."], "a zero-length cue (broken timing, real words)")
add("e11-missing-blank", "srt", "1\n00:00:01,000 --> 00:00:02,000\nNo blank line follows.\n2\n00:00:03,000 --> 00:00:04,000\nSecond cue.\n", ["No blank line follows.", "Second cue."], "a missing blank line between cues")
add("e12-dialogue-dashes", "srt", "1\n00:00:01,000 --> 00:00:03,000\n- Ready?\n- Always.\n", ["- Ready? - Always."], "two speakers in one cue with dashes")
add("e13-number-line", "srt", "1\n00:00:01,000 --> 00:00:03,000\nThe year was\n\n2\n00:00:03,000 --> 00:00:04,000\n1984\n\n3\n00:00:04,000 --> 00:00:05,000\n42\n", ["The year was", "1984", "42"], "caption text that is only a number")
add("e14-sdh-cues", "srt", "1\n00:00:01,000 --> 00:00:02,000\n[door slams]\n\n2\n00:00:02,500 --> 00:00:04,000\nWho's there?\n\n3\n00:00:04,500 --> 00:00:05,500\n(SIGHS)\n", ["[door slams]", "Who's there?", "(SIGHS)"], "sound descriptions kept as written (wording is untouched)")
json.dump(E, open("edge/expected.json", "w"), indent=1)
print("edge files", len(E))
PY

# ---------- method 4: independent Python reference (written separately from the site code) ----------
cat > out/ref.py <<'PY'
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])))
PY

ALL="$(ls $D/*.srt $D/*.vtt edge/*.srt edge/*.vtt)"
for f in $ALL; do
  b=$(basename "$f"); b=${b%.*}.${f##*.}
  python3 out/ref.py "$f" > "out/$b.ref.txt"
  # method 2: ffmpeg's raw text subtitle encoder
  ffmpeg -loglevel error -y -i "$f" -map 0:s:0 -c:s text -f data "out/$b.ffmpeg.txt" 2>"out/$b.ffmpeg.err" || echo "FFMPEG-FAIL $b: $(head -c 120 out/$b.ffmpeg.err)"
  # method 3: the sed one-liner most forum answers give (delete number-only lines, timestamp lines, blank lines)
  sed -e 's/\r$//' -e '/^[0-9]*$/d' -e '/-->/d' -e '/^WEBVTT/d' "$f" > "out/$b.sed.txt"
done

# ---------- method 1: the live Koldflux tool ----------
node - $ALL <<'JS'
const { chromium } = require(process.env.PW || "/home/ubuntu/agent-tools/node_modules/playwright");
const fs = require("fs"), path = require("path");
(async () => {
  const b = await chromium.launch(); const p = await (await b.newContext({ viewport: { width: 1100, height: 1000 }, acceptDownloads: true })).newPage();
  await p.goto("https://koldflux.com/tools/subtitles/subtitle-to-transcript", { waitUntil: "domcontentloaded", timeout: 60000 }); await p.waitForTimeout(4000);
  const rej = await p.$('button:has-text("Reject analytics")'); if (rej) { await rej.click(); await p.waitForTimeout(400); }
  for (const f of process.argv.slice(2)) {
    const ext = path.extname(f), b2 = path.basename(f, ext) + ext;
    await p.fill("textarea >> nth=0", ""); await p.waitForTimeout(200);
    await p.setInputFiles("input[type=file]", f); await p.waitForTimeout(1200);
    const dl = await p.$("a[download]"); let txt = "";
    if (dl) { const href = await dl.getAttribute("href"); txt = decodeURIComponent(href.replace(/^data:text\/plain;charset=utf-8,/, "")); }
    const warn = await p.$$eval("main [role=alert], main li, main p", e => e.map(x => x.innerText).filter(s => /skipped|overlap|unexpected|missing|no caption|zero|ends before/i.test(s)).slice(0, 4));
    fs.writeFileSync(`out/${b2}.tool.txt`, txt + (txt.endsWith("\n") || !txt ? "" : "\n"));
    fs.writeFileSync(`out/${b2}.tool.warn`, JSON.stringify(warn));
    if (f.includes("TOS-en.srt") && process.env.SHOT) { await p.screenshot({ path: process.env.SHOT, fullPage: false }); }
  }
  await b.close();
})().catch(e => { console.error("TOOL-FAIL", e.message.slice(0, 300)); process.exit(1); });
JS

# ---------- scoring ----------
python3 - <<'PY'
import json, re, glob, os, difflib, sys
sys.path.insert(0, "out")
E = json.load(open("edge/expected.json"))
def words(s): return s.split()
def score(got, exp):
    g, e = words(got), words(exp)
    sm = difflib.SequenceMatcher(a=e, b=g, autojunk=False)
    match = sum(m.size for m in sm.get_matching_blocks())
    return dict(recall=round(100 * match / max(1, len(e)), 1), extra=len(g) - match, exp_words=len(e), got_words=len(g))
def residue(txt):
    return dict(ts=len(re.findall(r"\d{1,2}:\d{2}[.,]\d{3}", txt)), tags=len(re.findall(r"<[^>]+>|\{\\[^}]*\}", txt)),
                ents=len(re.findall(r"&(amp|lt|gt|nbsp);", txt)), arrows=txt.count("-->"))
rows = []
for f in sorted(glob.glob("files/*.*")) + sorted(glob.glob("edge/*.srt")) + sorted(glob.glob("edge/*.vtt")):
    base = os.path.basename(f); stem = os.path.splitext(base)[0]
    if stem in E: exp = "\n".join(E[stem]["expected"]); kind = "known answer"
    else: exp = open(f"out/{base}.ref.txt", encoding="utf-8").read(); kind = "reference"
    for m in ["ref", "tool", "ffmpeg", "sed"]:
        p = f"out/{base}.{m}.txt"
        got = open(p, encoding="utf-8", errors="replace").read() if os.path.exists(p) else ""
        r = dict(file=base, kind=kind, method=m, exact=got.split() == exp.split(), **score(got, exp), **residue(got))
        rows.append(r)
json.dump(rows, open("out/results.json", "w"), indent=0)
print("file\tkind\tmethod\texact\trecall%\textra_words\texp_words\tts\ttags\tentities")
for r in rows: print(f"{r['file']}\t{r['kind']}\t{r['method']}\t{r['exact']}\t{r['recall']}\t{r['extra']}\t{r['exp_words']}\t{r['ts']}\t{r['tags']}\t{r['ents']}")
# controls: (a) reference must reproduce every hand-written edge answer; (b) the scorer must catch one dropped word
ok = [r for r in rows if r["method"] == "ref" and r["kind"] == "known answer"]
print("CONTROL ref vs known answers:", sum(r["exact"] for r in ok), "of", len(ok), "exact")
e = open("out/TOS-en.srt.ref.txt").read(); cut = " ".join(e.split()[:-1])
print("CONTROL scorer, one word removed from TOS:", score(cut, e))
print("CONTROL scorer, identical text:", score(e, e))
for m in ["tool", "ffmpeg", "sed"]:
    ka = [r for r in rows if r["method"] == m and r["kind"] == "known answer"]; real = [r for r in rows if r["method"] == m and r["kind"] == "reference"]
    print(f"SUMMARY {m}: known-answer exact {sum(r['exact'] for r in ka)}/{len(ka)}; real files exact {sum(r['exact'] for r in real)}/{len(real)}; residual timestamps {sum(r['ts'] for r in rows if r['method']==m)}, tags {sum(r['tags'] for r in rows if r['method']==m)}, entities {sum(r['ents'] for r in rows if r['method']==m)}")
PY
for w in out/*.tool.warn; do [ "$(cat $w)" != "[]" ] && echo "TOOL-WARNING $(basename $w .tool.warn): $(cat $w)"; done; true
echo "DONE $(date -u +%FT%TZ)"
