import numpy as np, cv2, json
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]
ROIS={
 "issue7_bbox_incl_mouth":{"px":[int(0.4157*w),int(0.0117*h),int((0.4157+0.2213)*w),int((0.0117+0.4084)*h)],
   "note":"issue #7 原始 bbox（含嘴部），用於與 Moris 標記對位；嘴部遮罩變動會混入數字"},
 "bangs_only_excl_mouth":{"px":[545,8,835,205],
   "note":"只含頭頂瀏海區、排除嘴部；判斷瀏海跳動請用這組"}
}
def j(seq,i,R):
    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 round(float(d.mean()),3), round(float(d.max()),1)
out={"rois":ROIS,"versions":{}}
for name,seq in (("S04_s31_mother",mo),("S04_s31_mouthfix_v8",fx),("S04_s2026_mother",m26),("S04_s2026_mouthfix_v9",f26)):
    ent={}
    for rk,R in ROIS.items():
        vals=[(i,)+j(seq,i,R["px"]) for i in range(1,len(seq))]
        top=sorted(vals,key=lambda t:-t[1])[:5]
        ent[rk]={"top5":[{"frame":i,"sec":round(i/24.0,3),"mean":m,"max":mx} for i,m,mx in top],
                 "f30":{"mean":j(seq,30,R["px"])[0],"max":j(seq,30,R["px"])[1]},
                 "window_f28_f33":[{"frame":i,"mean":j(seq,i,R["px"])[0]} for i in range(28,34)]}
    out["versions"][name]=ent
json.dump(out,open(OUT+"bangs_metrics_roi.json","w"),ensure_ascii=False,indent=1)
print(json.dumps(out["versions"]["S04_s31_mother"]["bangs_only_excl_mouth"]["top5"][:2],ensure_ascii=False))
print(json.dumps(out["versions"]["S04_s2026_mother"]["bangs_only_excl_mouth"]["top5"][:2],ensure_ascii=False))
print("ROI_JSON_DONE",flush=True)
