import numpy as np, cv2, os
from PIL import Image, ImageDraw, ImageFont
A="/var/aiadultvideo/output/aiadult/s04v7/"
OUT=A+"bangs_check/"
def load(p):
    cap=cv2.VideoCapture(p); fr=[]
    while True:
        ok,f=cap.read()
        if not ok: break
        fr.append(f)
    cap.release(); return fr
mo=load(A+"S04_s31.mp4"); fx=load(A+"mouthfix4/S04_s31_p3fix_acopy90.mp4")
m26=load(A+"S04_s2026.mp4"); f26=load(A+"mouthfix4/S04_s2026_p3fix_acopy90.mp4")
h,w=mo[0].shape[:2]
# bangs-only region: upper head, excludes mouth
R=(545,8,835,205)
def j(seq,i):
    a=seq[i-1][R[1]:R[3],R[0]:R[2]]; b=seq[i][R[1]:R[3],R[0]:R[2]]
    d=np.abs(a.astype(np.float32)-b.astype(np.float32)); return float(d.mean()), float(d.max())
for name,seq in (("31_mother",mo),("31_fixed",fx),("2026_mother",m26),("2026_fixed",f26)):
    vals=[(i, round(j(seq,i)[0],3), round(j(seq,i)[1],1)) for i in range(20,46)]
    vals.sort(key=lambda x:-x[1])
    print(name,"TOP bangs-only jumps (f, mean, max):", vals[:4], flush=True)
    print(name,"f28-33:", [(i, round(j(seq,i)[0],3)) for i in range(28,34)], flush=True)
try: font=ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",14)
except Exception: font=None
def lab(img,txt):
    im=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)).copy(); d=ImageDraw.Draw(im)
    d.rectangle([0,0,170,18],fill=(0,0,0)); d.text((3,2),txt,fill=(255,255,0),font=font); return im
idxs=[28,29,30,31,32]
rows=[("31 mother",mo),("31 mouthfix(v8)",fx),("2026 mother",m26),("2026 mouthfix",f26)]
tw,th=240,240
sh=Image.new("RGB",(len(idxs)*tw, len(rows)*th+20),(10,10,10)); dd=ImageDraw.Draw(sh)
dd.text((4,2),"bangs-only zoom (top head, mouth excluded)  f28-f32",fill=(255,255,0),font=font)
for r,(nm,seq) in enumerate(rows):
    for k,i in enumerate(idxs):
        crop=seq[i][R[1]:R[3],R[0]:R[2]]
        c=cv2.resize(crop,(tw,th),interpolation=cv2.INTER_CUBIC)
        sh.paste(lab(c,"%s f%02d"%(nm,i)),(k*tw,20+r*th))
sh.save(OUT+"bangs_only_4rows_f28_f32.png"); print("SAVED",OUT+"bangs_only_4rows_f28_f32.png",flush=True)
print("TIGHT_DONE",flush=True)
