"""Real procedural H264/PNG gates: no portrait, provider, network or activation.""" import copy import hashlib import importlib.util import json from pathlib import Path import subprocess import tempfile import unittest ROOT=Path(__file__).resolve().parents[2] spec=importlib.util.spec_from_file_location('shape_packager',ROOT/'scripts/package-avatar-emotion.py') packager=importlib.util.module_from_spec(spec);spec.loader.exec_module(packager) gate=packager.runtime_gate class AvatarShapeTest(unittest.TestCase): @classmethod def setUpClass(cls): from PIL import Image cls.tmp=tempfile.TemporaryDirectory(prefix='avatar-shape-fixtures-') cls.root=Path(cls.tmp.name) cls.runtimes={} for w,h in [(480,848),(720,1280)]: folder=cls.root/f'{w}x{h}'/'runtime';(folder/'body').mkdir(parents=True);(folder/'patches').mkdir() movie=folder/'body/idle.mp4' subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-f','lavfi','-i', f'testsrc2=size={w}x{h}:rate=24','-frames:v','12','-an','-c:v','libx264','-pix_fmt','yuv420p', '-threads','1',str(movie)],check=True,capture_output=True,timeout=30) measured=packager.probe_clip(movie);digest=packager.file_sha(movie) body=dict(path='body/idle.mp4',sha256=digest,width=w,height=h,hasAudio=False,frameCount=12, ptsUs=measured['ptsUs'],durationUs=measured['durationUs'],fpsNumerator=24,fpsDenominator=1) patches=[] for i,t in enumerate(body['ptsUs']): levels=[] for l in range(5): name=f'patches/f{i}-l{l}.png' Image.new('RGBA',(40,22),(200,80,50,l*60)).save(folder/name) levels.append(dict(levelIndex=l,aperture=l/4,path=name,sha256=packager.file_sha(folder/name))) patches.append(dict(frameIndex=i,ptsUs=t,path=levels[4]['path'],sha256=levels[4]['sha256'], x=w-40,y=h-22,width=40,height=22,levels=levels)) states=[] curves={'idle':[0]*12,'opening':[0,.2,.4,.6,.8,1], 'talk1':[1,.75,.5,.25,0,.25,.5,.75,1,.75,.5,1], 'talk2':[1,.5,.25,0,.25,.5,.75,1,.75,.5,.75,1], 'end-talk':[1,.8,.6,.4,.2,0]} for name,alpha in curves.items(): n=len(alpha) states.append(dict(id=name,frameCount=n,ptsUs=[i*1000000//24 for i in range(n)], durationMs=n*1000//24,fpsNumerator=24,fpsDenominator=1,globalAlphaByFrame=alpha, entryMouthAnchor='A' if name in ('idle','opening') else 'B', exitMouthAnchor='A' if name in ('idle','end-talk') else 'B')) runtime=dict(schemaVersion=2,packId='a01-expression-action-v1-test-runtime-04',identityId='a01', publishApproval=False,runtimeReady=True,body=body,patches=patches,mouthStates=states, patchFormat=dict(bodySha256=digest,format='PNG RGBA 8bit',alphaEncoding='straight_unassociated', apertureLevels=[0,.25,.5,.75,1],requiresRendererExtension=True), stateRouting=dict(idle=['idle','opening'],opening=['talk1','talk2','end-talk'], talk1=['talk1','talk2','end-talk'],talk2=['talk1','talk2','end-talk'],**{'end-talk':['idle']})) cls.write(folder/'manifest.json',runtime);cls.runtimes[(w,h)]=(folder,runtime) cls.music=cls.root/'music.mp4' subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-f','lavfi','-i', 'testsrc2=size=720x1280:rate=24','-f','lavfi','-i','sine=frequency=440:sample_rate=48000', '-t','1','-c:v','libx264','-pix_fmt','yuv420p','-c:a','aac','-threads','1',str(cls.music)], check=True,capture_output=True,timeout=30) @classmethod def tearDownClass(cls): cls.tmp.cleanup() @staticmethod def write(path,data): path.write_text(json.dumps(data)+'\n') def test_actual_body_shapes_and_own_pixel_bounds(self): for shape,(folder,_) in self.runtimes.items(): path=folder/'manifest.json' result,_=gate.check_runtime(path,packager.file_sha(path),kotlin=False) self.assertEqual(result['body_shape'],list(shape));self.assertEqual(result['patch_images'],60) self.assertEqual(result['rgba_cache_bytes'],12*40*22*4*5) def test_declared_shape_must_match_actual_codec(self): folder,runtime=self.runtimes[(720,1280)] invalid=copy.deepcopy(runtime);invalid['body'].update(width=480,height=848) path=folder/'wrong-shape.json';self.write(path,invalid) with self.assertRaisesRegex(ValueError,'codec/shape mismatch'): gate.check_runtime(path,packager.file_sha(path),kotlin=False) def test_legacy_schema_does_not_inherit_larger_shape(self): folder,runtime=self.runtimes[(720,1280)] invalid=copy.deepcopy(runtime);invalid.update(schemaVersion=1,packId='a01-neutral-graph-v1-runtime-04') path=folder/'wrong-schema.json';self.write(path,invalid) with self.assertRaisesRegex(ValueError,'codec/shape mismatch'): gate.check_runtime(path,packager.file_sha(path),kotlin=False) def test_large_patch_bounds_remain_strict(self): folder,runtime=self.runtimes[(720,1280)] invalid=copy.deepcopy(runtime);invalid['patches'][0]['x']=681 path=folder/'wrong-patch.json';self.write(path,invalid) with self.assertRaisesRegex(ValueError,'patch pixel bounds'): gate.check_runtime(path,packager.file_sha(path),kotlin=False) def test_actual_720_music_decode_shape(self): result=packager.probe_music_clip(self.music) self.assertEqual(result['shape'],(720,1280));self.assertEqual(len(result['ptsUs']),24) self.assertEqual(result['humanListening'],'not_run') def test_full_720_bundle_uses_production_kotlin_parser(self): folder,runtime=self.runtimes[(720,1280)];root=folder.parent;body=runtime['body'] def index(clip): return dict(schemaVersion=2,identityId='a01',packId='a01-expression-action-v1',fallbackPackageId='neutral', conversationPackages=[dict(id='neutral',emotion='neutral',visualIntensity=0,mouthBodySha256=body['sha256'], runtimeManifest=dict(path='runtime/manifest.json',sha256=packager.file_sha(folder/'manifest.json')), entryAnchor='A',exitAnchor='A',legalExitFrames=[11],loopEdge='neutral-loop')], edges=[dict(id='neutral-loop',**{'from':'neutral','to':'neutral'},fromFrame=11,toFrame=0, fromPtsUs=body['ptsUs'][-1],toPtsUs=0,fromAnchor='A',toAnchor='A',nativeLoop=True,clip=clip)], actions=[],files=[dict(path=str(p.relative_to(root)),sha256=packager.file_sha(p),bytes=p.stat().st_size) for p in folder.rglob('*') if p.is_file() and p.name not in ('wrong-patch.json','wrong-schema.json','wrong-shape.json')]) clip=body|dict(path='runtime/body/idle.mp4') path=root/'manifest.json';self.write(path,index(clip));output=self.root/'gate';output.mkdir() result=packager.check_bundle(path,packager.file_sha(path),output) self.assertEqual(result['production_kotlin_index'],'passed');self.assertEqual(result['referenced_files'],63) self.assertFalse(result['dance_available']) self.write(path,index(clip|dict(width=480,height=848)));output=self.root/'bad-gate';output.mkdir() with self.assertRaisesRegex(ValueError,'decoded clip shape mismatch'): packager.check_bundle(path,packager.file_sha(path),output) if __name__=='__main__': unittest.main()