"""Classify P2 recording frames (2 fps) as doc / loading-or-blank / pdf by the content region's colour stats."""
import sys, subprocess, io
from PIL import Image, ImageStat
path = sys.argv[1]
raw = subprocess.run(["ffmpeg","-v","error","-i",path,"-vf","fps=4,scale=201:-1","-f","image2pipe","-vcodec","png","-"],capture_output=True).stdout
frames=[]; i=0
while True:
    j = raw.find(b"IEND", i)
    if j < 0: break
    frames.append(Image.open(io.BytesIO(raw[i:j+8])).convert("RGB")); i = j+8
prev=None; out=[]
for k,f in enumerate(frames):
    reg = f.crop((0, 60, f.width, 400))
    m = ImageStat.Stat(reg).mean; sd = ImageStat.Stat(reg.convert("L")).stddev[0]
    if sum(m)/3 > 120: c = "pdf"
    elif sd < 6: c = "loading/blank"
    else: c = "document"
    if c != prev: out.append(f"{k/4:5.2f}s {c}")
    prev = c
print(path.rsplit('/',1)[1], "|", "; ".join(out))
