#!/usr/bin/env python3
"""contrast.py <source.mp4> <logo-grey 0-255> <opacity-percent> [<opacity-percent> ...]
Takes the frame 1 s in, cuts the bottom-right corner (the 25% x 15% of the frame where a default-position logo lands), and prints the
WCAG contrast ratio between the blended logo colour and the average colour of that corner, for each opacity. The blend is the plain
alpha blend the tool applies (checked on a flat clip: grey = 255 x (1 - opacity) for a black logo). The logo colour is grey, so R=G=B.
This is arithmetic on one frame, not a legibility test. Standard library plus ffmpeg only. Exit 2 on a bad input, 3 when ffmpeg fails."""
import subprocess, sys, os

def lin(c):
    c /= 255
    return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4

def lum(r, g, b):
    return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)

if len(sys.argv) < 4: print(__doc__, file=sys.stderr); sys.exit(2)
src = sys.argv[1]
if not os.path.isfile(src) or os.path.getsize(src) == 0: print("missing or empty file: " + src, file=sys.stderr); sys.exit(2)
try:
    logo = float(sys.argv[2]); ops = [float(x) for x in sys.argv[3:]]
except ValueError:
    print("logo grey and opacities must be numbers", file=sys.stderr); sys.exit(2)
if not 0 <= logo <= 255 or any(not 0 < o <= 100 for o in ops): print("logo grey 0-255, opacity 1-100", file=sys.stderr); sys.exit(2)
r = subprocess.run(["ffmpeg", "-v", "error", "-ss", "1", "-i", src, "-frames:v", "1", "-vf", "crop=iw*0.25:ih*0.15:iw*0.75:ih*0.85",
                    "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], capture_output=True)
if r.returncode or not r.stdout: print("no frame read at 1 s (clip shorter than 1 s, or no video stream): " + r.stderr.decode()[:120], file=sys.stderr); sys.exit(3)
d = r.stdout; n = len(d) // 3
bg = [sum(d[i::3]) / n for i in range(3)]
Lb = lum(*bg)
print("corner mean colour = (%.0f, %.0f, %.0f), relative luminance %.3f" % (bg[0], bg[1], bg[2], Lb))
for o in ops:
    a = o / 100
    c = [a * logo + (1 - a) * x for x in bg]
    L = lum(*c)
    hi, lo = max(L, Lb), min(L, Lb)
    print("logo grey %d at opacity %d%%: contrast ratio %.2f : 1" % (logo, o, (hi + 0.05) / (lo + 0.05)))
