"""Read an LED scoreboard from a video into one text file per field, for an OBS Text source.

From https://brasspage.com/scoreboard-ocr/ (MIT license). Needs Python 3, Pillow, ffmpeg and ssocr.
Run: python3 scoreboard.py boxes.json -i game.mp4   (everything after boxes.json goes to ffmpeg as input options)
boxes.json: {"clock": [x0, y0, x1, y1], "home": [...], ...} in pixels of the frame scaled to 1280x720.
Draw each box tight around its digits. The script prints each read, and writes scores/<field>.txt
once 2 reads in a row agree.
"""

import json
import os
import re
import subprocess
import sys
from io import BytesIO

from PIL import Image, ImageChops, ImageOps

W, H = 1280, 720  # every frame is scaled to this size
PER_SECOND = 2  # reads a second
SAME = 2  # reads in a row that must agree before a change shows
OUT = "scores"


def otsu(im):
    h = im.histogram()
    total, every = sum(h), sum(i * c for i, c in enumerate(h))
    best = t = w0 = s0 = 0
    for i, c in enumerate(h):
        w0, s0 = w0 + c, s0 + i * c
        w1 = total - w0
        if w0 and w1:
            between = (s0 / w0 - (every - s0) / w1) ** 2 * w0 * w1
            if between > best:
                best, t = between, i
    return t


def prep(crop):
    """Dark digits on white, black and white, 140 px tall with the border. Otsu drops the dim unlit segments."""
    r, g, b = crop.convert("RGB").split()
    im = ImageChops.lighter(
        ImageChops.lighter(r, g), b
    )  # the brightest channel: red LEDs stay bright
    if sum(im.getdata()) / (im.width * im.height) < 128:  # light digits on a dark board
        im = ImageOps.invert(im)
    im = im.resize((max(1, round(im.width * 100 / im.height)), 100), Image.LANCZOS)
    t = otsu(im)
    return ImageOps.expand(im.point(lambda v: 255 if v > t else 0), 20, fill=255)


def read(crop):
    buf = BytesIO()
    prep(crop).save(buf, "PNG")
    # -M 1x60: skip marks under 60 px tall, like the clock's colon (prep makes crops 140 px tall)
    cmd = ["ssocr", "-d", "-1", "-M", "1x60", "-"]
    r = subprocess.run(cmd, input=buf.getvalue(), capture_output=True, check=False)
    return r.stdout.decode().strip()


def clean(field, text):
    """The value to show, or None when the read cannot be right."""
    d = re.sub(r"\D", "", text).lstrip("0") or ("0" if re.search(r"\d", text) else "")
    if not d:  # a blank or failed read
        return None
    if field == "clock":
        d = d.zfill(3)
        return f"{int(d[:-2])}:{d[-2:]}" if len(d) <= 4 and int(d[-2:]) < 60 else None
    return d if 0 < len(d) <= 3 else None


class Hold:
    """Show a new value only after SAME reads in a row agree. One bad read never reaches the screen."""

    def __init__(self):
        self.shown, self.last, self.count = None, None, 0

    def push(self, value):
        if value is not None:
            self.count = self.count + 1 if value == self.last else 1
            self.last = value
            if self.count >= SAME:
                self.shown = value
        return self.shown


def write(path, text):
    with open(path + ".tmp", "w") as f:
        f.write(text)
    os.replace(path + ".tmp", path)  # OBS never sees half a file


def main():
    with open(sys.argv[1]) as f:
        boxes = json.load(f)
    os.makedirs(OUT, exist_ok=True)
    holds = {field: Hold() for field in boxes}
    vf = f"fps={PER_SECOND},scale={W}:{H}"
    cmd = [
        "ffmpeg",
        "-v",
        "error",
        *sys.argv[2:],
        "-vf",
        vf,
        "-f",
        "rawvideo",
        "-pix_fmt",
        "rgb24",
        "-",
    ]
    ff = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    n = 0
    while len(raw := ff.stdout.read(W * H * 3)) == W * H * 3:
        frame = Image.frombytes("RGB", (W, H), raw)
        line = [str(n)]
        for field, box in boxes.items():
            text = read(frame.crop(box))
            shown = holds[field].push(clean(field, text))
            if shown is not None:
                write(os.path.join(OUT, field + ".txt"), shown)
            line.append(f"{field}={text!r}>{shown}")
        print("\t".join(line), flush=True)
        n += 1


if __name__ == "__main__":
    main()
