#!/usr/bin/env python3
"""Turns the plain TXT from the Video to text tool into a transcript file for ONE speaker: a title line, the speaker's name at the start of every paragraph, and a short paragraph every four sentences.
Usage: python3 make-transcript.py tool-output.txt "Title of the video" "Speaker name" transcript.txt
The output file is written only when the check passes, so a failed run leaves no file (and does not touch an existing one). Without the fourth argument the transcript goes to the screen.
Use the .txt download with the "Add a timestamp to every paragraph" box unticked: .srt, .vtt and timestamped text are refused.
It adds no words: the script prints a check line to stderr that compares the spoken words in and out. With several speakers, add each person's name by hand."""
import re, sys

def words(t):
    return re.findall(r"[\w']+", t.lower())

def fail(msg):
    sys.exit("FAIL " + msg)

def main(path, title, speaker, outpath=None):
    if not speaker.strip():
        fail("the speaker name is empty")
    try:
        raw = open(path, encoding="utf-8-sig").read()
    except OSError as e:
        fail("cannot read %s: %s" % (path, e.strerror))
    except UnicodeDecodeError:
        fail("%s is not UTF-8 text" % path)
    lines = raw.replace("\r", "\n").split("\n")
    if "-->" in raw or raw.lstrip().startswith("WEBVTT") or any(re.match(r"\s*\[\d{1,2}:\d\d", l) for l in lines):
        fail("%s looks like .srt, .vtt or text with timestamps; use the .txt download with the timestamp box unticked" % path)
    text = " ".join(raw.replace("\r", "\n").split())
    if not text:
        fail("%s has no text (the tool gives no file at all for a clip with no speech or no audio)" % path)
    sentences = re.split(r"(?<=[.!?])\s+", text)
    out = ["Transcript: " + title, ""]
    for i in range(0, len(sentences), 4):
        out.append(speaker + ": " + " ".join(sentences[i:i + 4]))
        out.append("")
    body = "\n".join(out)
    spoken_in = words(text)
    spoken_out = words(body)[len(words("Transcript: " + title)):]
    extra = len(spoken_out) - len(spoken_in)
    n_par = (len(sentences) + 3) // 4
    label_words = len(words(speaker)) * n_par
    ok = extra == label_words
    sys.stderr.write("words in %d, speaker label words %d, words out minus label %d: %s\n" % (len(spoken_in), label_words, len(spoken_out) - label_words, "TRANSCRIPT-OK" if ok else "FAIL"))
    if not ok:
        sys.exit(1)
    if outpath:
        try:
            open(outpath, "w", encoding="utf-8").write(body)
        except OSError as e:
            fail("cannot write %s: %s" % (outpath, e.strerror))
    else:
        sys.stdout.write(body)

if __name__ == "__main__":
    if len(sys.argv) not in (4, 5):
        sys.exit('usage: python3 make-transcript.py tool-output.txt "Title" "Speaker name" [transcript.txt]')
    main(*sys.argv[1:])
