Files
baji-vc/scripts/check-square540-framing.py
T

65 lines
5.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Finite real GLES preview of the immutable Liam media at the controlled square preset.
No generated media, source mutation, Android OES/device/performance claim.
"""
import argparse, hashlib, importlib.util, json, os, re, subprocess, tempfile
from pathlib import Path
import cv2
import numpy as np
from PIL import Image, ImageDraw
ROOT=Path(__file__).resolve().parents[1]
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
a.output.mkdir(parents=True,exist_ok=False)
catalog=json.loads((ROOT/'manifests/character-build-profiles.json').read_bytes());preset=catalog['framingPresets']['square540-headchest'];media=catalog['mediaBundles'][preset['mediaBundle']]
root=ROOT/'app/src/main/assets'/media['assetRoot'];raw=(root/'manifest.json').read_bytes();assert hashlib.sha256(raw).hexdigest()==preset['indexSha256'];index=json.loads(raw)
source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_text()
vertex=re.search(r'const val VERTEX="""([\s\S]*?)"""',source)[1]
fragment=re.search(r'const val FRAGMENT="""([\s\S]*?)"""',source)[1].replace('#extension GL_OES_EGL_image_external : require','').replace('samplerExternalOES','sampler2D')
spec=importlib.util.spec_from_file_location('golden',ROOT/'scripts/check-avatar-shader.py');golden=importlib.util.module_from_spec(spec);spec.loader.exec_module(golden)
refs=[r['runtimeManifest'] for r in index['conversationPackages']]+[e['mouthRuntimeManifest'] for e in index['edges'] if 'mouthRuntimeManifest' in e]
runtimes={}
for ref in refs:
m=json.loads((root/ref['path']).read_bytes());runtimes[(Path(ref['path']).parent/m['body']['path']).as_posix()]=(m,root/Path(ref['path']).parent)
rows=[];measurements=[];tiles=[]
with tempfile.TemporaryDirectory(prefix='square540-gles-') as td:
t=Path(td);(t/'vertex').write_text(vertex);(t/'fragment').write_text(fragment)
subprocess.run(['cc','-O2',str(ROOT/'tests/avatar-pixels/gles-golden.c'),'-lEGL','-lGLESv2','-lm','-o',str(t/'golden')],check=True)
env=dict(os.environ,EGL_PLATFORM='surfaceless',LIBGL_ALWAYS_SOFTWARE='1')
for n,clip in enumerate(sorted(root.rglob('*.mp4'))):
rel=clip.relative_to(root).as_posix();cap=cv2.VideoCapture(str(clip));total=int(cap.get(cv2.CAP_PROP_FRAME_COUNT));selected={0,total//3,2*total//3,total-1};bounds=[];i=0
while True:
ok,bgr=cap.read()
if not ok:break
# Conservative head + raised-hand upper silhouette, not a face landmark detector.
ys,xs=np.where(np.max(bgr[:180,170:550],axis=2)<150)
if len(ys):bounds.append([int(xs.min())+170,int(ys.min()),int(xs.max())+170,int(ys.max())])
if i in selected:
body=cv2.cvtColor(bgr,cv2.COLOR_BGR2RGBA);(t/'body').write_bytes(body.tobytes())
levels=[0,4] if rel in runtimes else [0]
for level in levels:
if level:
runtime,base=runtimes[rel];row=runtime['patches'][i];patch=np.asarray(Image.open(base/row['levels'][level]['path']).convert('RGBA'));x,y=row['x'],row['y'];opacity=1
else:patch=np.array([[[255,0,255,255]]],dtype=np.uint8);x=y=0;opacity=0
(t/'patch').write_bytes(patch.tobytes())
r=subprocess.run([str(t/'golden'),str(t/'vertex'),str(t/'fragment'),str(t/'body'),str(t/'patch'),str(t/'out'),str(patch.shape[1]),str(patch.shape[0]),str(x),str(y),str(opacity),'540','540','0','720','1280',str(preset['zoom']),str(preset['centerY'])],env=env,capture_output=True,text=True,check=True)
actual=np.frombuffer((t/'out').read_bytes(),np.uint8).reshape(540,540,4)[::-1,:,:3]
expected=golden.golden(body,patch,x,y,opacity,540,540,0,preset['zoom'],preset['centerY']);diff=np.abs(actual.astype(int)-expected.astype(int));assert diff.max()<=2,(rel,i,level,diff.max())
name=f'{n:02d}-{clip.stem}-f{i:03d}-L{level}.png';Image.fromarray(actual).save(a.output/name)
rows.append({'clip':rel,'frame':i,'mouthLevel':level,'viewport':[540,540],'maxAbsRGB':int(diff.max()),'image':name})
if not level:tiles.append((name,Image.fromarray(actual)))
i+=1
cap.release();assert i==total
measurements.append({'clip':rel,'frames':total,'upperDarkEnvelope':[min(b[0] for b in bounds),min(b[1] for b in bounds),max(b[2] for b in bounds),max(b[3] for b in bounds)],'method':'all decoded frames; RGB<150; search x170:550 y0:180; silhouette includes raised hands; representative head/chin visually reviewed'})
sheet=Image.new('RGB',(7*270,8*294),'white');draw=ImageDraw.Draw(sheet)
for i,(name,im) in enumerate(tiles):sheet.paste(im.resize((270,270)),((i%7)*270,(i//7)*294));draw.text(((i%7)*270,(i//7)*294+272),name[:40],fill='black')
sheet.save(a.output/'contact.jpg',quality=94)
report={'status':'passed','preset':preset,'indexSha256':media['indexSha256'],'decodedFrames':sum(r['frames'] for r in measurements),'clipMeasurements':measurements,'glesCases':rows,'device':'not_run','scope':'Production shader strings + decoded 2D texture surrogate on host EGL; original media unchanged; no Android OES/codec/device claim.'}
(a.output/'report.json').write_text(json.dumps(report,indent=2)+'\n')
html='<!doctype html><meta charset="utf-8"><title>Liam square540 code42 preview</title><style>body{font:16px sans-serif;background:#eee}img{max-width:100%}figure{display:inline-block;margin:8px;width:270px}figure img{width:270px}figcaption{overflow-wrap:anywhere}</style><h1>Liam 540×540 head + upper chest</h1><p>Source ROI (180,-16)–(540,344), zoom=32/9, centerY=.128125. Real offline GLES; device not tested. No media bytes changed.</p><a href="report.json">Measurement / GLES report</a><p><a href="contact.jpg"><img src="contact.jpg"></a></p>'
for row in rows:html+=f'<figure><a href="{row["image"]}"><img loading="lazy" src="{row["image"]}"></a><figcaption>{row["image"]}</figcaption></figure>'
(a.output/'index.html').write_text(html)
print(json.dumps({'status':'passed','clips':len(measurements),'decoded_frames':report['decodedFrames'],'gles_cases':len(rows),'output':str(a.output)}))
if __name__=='__main__':main()