Files
baji-vc/scripts/package-avatar-mouth.py
T
zenord 7d8ea95f07 feat: add aperture mouth candidate and early foreground permissions
Route runtime04 curve values to five source-frame lip geometries with level0 body bypass and spatial opacity1 for all other levels. Preserve the continuous decoded body clock and clean home. Request normal permissions after foreground host layout independently of network; support offline manual consent without capture or connection. Add strict 97x5 parsing, renderer and permission regressions, offline EGL shader pixel goldens and exact debug-candidate packaging. Naturalness, visible talk, device colors and perceived response remain pending.
2026-10-12 22:55:20 +08:00

130 lines
9.7 KiB
Python

#!/usr/bin/env python3
"""Pinned runtime04 aperture-level Android internal debug candidate; no final quality approval."""
from pathlib import Path
import argparse,hashlib,importlib.util,json,os,re,subprocess,tempfile,urllib.request,zipfile
import numpy as np
from PIL import Image
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('natural_packaging',ROOT/'scripts/package-avatar-natural.py')
natural=importlib.util.module_from_spec(spec);spec.loader.exec_module(natural)
LOG=ROOT/'logs/avatar-mouth-062';natural.LOG=LOG
SOURCE=ROOT/'.runtime/avatar-imports/a01-neutral-graph-v1/runtime-04'
PACK=ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1/runtime-04'
PIN='0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad'
ARTIFACT=ROOT/'artifacts/lan-voice-v062-mouth-candidate-arm64-debug.apk'
CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
UI_SHA='8d18f4b4f46ad1a165901cd794d9407b4b61fc017cafb249a7addf9834d5e029'
sha=lambda data:hashlib.sha256(data).hexdigest()
def import_runtime():
raw=(SOURCE/'manifest.json').read_bytes();assert sha(raw)==PIN and len(raw)<=512000,'runtime04 manifest drift'
m=json.loads(raw);assert m['schemaVersion']==1 and m['packId']=='a01-neutral-graph-v1-runtime-04' and m['identityId']=='a01'
assert m['runtimeReady'] is True and m['publishApproval'] is False and m['deviceTestStatus']=='pending'
assert m['naturalQualityStatus']=='pending_coordinator' and m['safeTransitions']['reviewStatus']=='pending' and m['approvedEdges']==[]
assert m['patchFormat']['alphaEncoding']=='straight_unassociated' and m['patchFormat']['apertureLevels']==[0,.25,.5,.75,1]
b=m['body'];assert b['sha256']=='177dbc0ab809e3c9c684899ffbd9cf3a2c357973c7037134f5d79e4e6cdfc762'
assert (b['frameCount'],b['width'],b['height'],b['fpsNumerator'],b['fpsDenominator'],b['durationUs'],b['hasAudio'])==(97,480,848,24,1,4041667,False)
files={'manifest.json':raw}
def read(row,pattern,limit):
name=row['path'];assert re.fullmatch(pattern,name) and name not in files
p=(SOURCE/name).resolve(strict=True);assert p.is_relative_to(SOURCE.resolve()) and p.stat().st_size<=limit
data=p.read_bytes();assert sha(data)==row['sha256'];files[name]=data
read(b,r'body/[A-Za-z0-9_.-]+\.mp4',16000000)
assert len(m['patches'])==97
size=0
for i,p in enumerate(m['patches']):
assert p['frameIndex']==i and abs(p['ptsUs']-i*1000000//24)<=2
x,y,w,h=(p[k] for k in ('x','y','width','height'))
assert all(isinstance(v,int) for v in (x,y,w,h)) and 1<=w<=128 and 1<=h<=128 and 0<=x<=480-w and 0<=y<=848-h
assert len(p['levels'])==5
for level,l in enumerate(p['levels']):
assert l['levelIndex']==level and l['aperture']==level/4
read(l,r'patches/[A-Za-z0-9_.-]+\.png',256000)
with Image.open(SOURCE/l['path']) as image:assert image.mode=='RGBA' and image.size==(w,h)
size+=w*h*4
assert p['path']==p['levels'][4]['path'] and p['sha256']==p['levels'][4]['sha256']
assert size<=8000000 and len(files)==487
for name,data in files.items():
dest=PACK/name;assert not dest.exists() or dest.read_bytes()==data,'Unknown existing runtime04 byte: '+name
for name,data in files.items():
dest=PACK/name;dest.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
if dest.exists():continue
fd,tmp=tempfile.mkstemp(prefix='.runtime04-',dir=dest.parent)
try:
with os.fdopen(fd,'wb') as f:f.write(data)
os.chmod(tmp,0o600);os.replace(tmp,dest)
finally:
if os.path.exists(tmp):os.unlink(tmp)
assert sha((SOURCE/'manifest.json').read_bytes())==PIN
(LOG/'import.json').write_text(json.dumps({'manifestSha':PIN,'admissionScope':'coordinator_authorized_debug_device_candidate_only','fileCount':len(files),'rgbaBytes':size,'productionApproval':False},indent=2)+'\n')
return m,files
def decode_math(m):
body=PACK/m['body']['path']
probe=json.loads(natural.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',body],'body-probe.json'))
assert len(probe['streams'])==1 and len(probe['frames'])==97
s=probe['streams'][0];assert (s['codec_name'],s['pix_fmt'],s['width'],s['height'],s['r_frame_rate'])==('h264','yuv420p',480,848,'24/1')
assert all(abs(float(f['best_effort_timestamp_time'])-i/24)<1e-5 for i,f in enumerate(probe['frames']))
natural.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',body,'-f','null','-'],'body-full-decode.txt')
pipe=subprocess.Popen(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(body),'-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
metrics=[]
try:
for i,row in enumerate(m['patches']):
data=pipe.stdout.read(480*848*3);assert len(data)==480*848*3
base=np.frombuffer(data,np.uint8).reshape(848,480,3);x,y,w,h=[row[k] for k in ('x','y','width','height')]
region=base[y:y+h,x:x+w].astype(float);previous=region
for level,l in enumerate(row['levels']):
rgba=np.asarray(Image.open(PACK/l['path']),float);a=rgba[:,:,3:4]/255
out=region if level==0 else region*(1-a)+rgba[:,:,:3]*a
if level==0:assert np.array_equal(out,region)
delta=np.abs(out-previous)
metrics.append({'frameIndex':i,'levelIndex':level,'opacity':0 if level==0 else 1,
'adjacentLevelMaxRGB':float(delta.max()),'adjacentLevelMeanRGB':float(delta.mean()),
'perceivedMotion':'unknown','zeroBypassExact':True if level==0 else None})
previous=out
assert pipe.stdout.read(1)==b'' and pipe.wait(timeout=10)==0
finally:
if pipe.poll() is None:pipe.kill();pipe.wait()
(LOG/'level-math.json').write_text(json.dumps({'scope':'CPU selected geometry with spatial mask only; pixel deltas do not certify naturalness, visible talk or ≤1s','frames':metrics},indent=2)+'\n')
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--import-only',action='store_true');parser.add_argument('--verify-existing',action='store_true')
args=parser.parse_args();LOG.mkdir(parents=True,exist_ok=True)
m,files=import_runtime();_,oldfiles=natural.import_runtime()
ui=ROOT/'artifacts/lan-voice-v062-ui-candidate-arm64-debug.apk';assert sha(ui.read_bytes())==UI_SHA
if args.import_only:
decode_math(m);print('PASS: runtime04 pinned debug candidate manifest/body/97x5RGBA, strict dimensions/bounds/hash, CFR/full decode, alpha0 bypass and selected geometry opacity1 math. runtime03/code14 retained.');return
natural.tests_current()
actual=(LOG/'actual-manifest-tests.txt').read_text();assert PIN in actual and 'PASS: actual exported runtime manifest parsed' in actual
assert 'PASS: clean home' in (ROOT/'logs/avatar-safe-061/ui-contract-tests.txt').read_text()
assert 'BUILD SUCCESSFUL' in (LOG/'android-test-compile.txt').read_text()
golden=json.loads((LOG/'shader-golden/shader-golden.json').read_text());assert golden['status']=='passed' and len(golden['cases'])==40
assert golden['shaderSourceSha']==sha((ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_bytes())
if args.verify_existing:assert ARTIFACT.is_file();built=ARTIFACT
else:
assert not ARTIFACT.exists(),'Never overwrite a delivered code15 artifact'
natural.run([ROOT/'scripts/build.sh','assembleDebug','-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+PIN],'assemble.txt')
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk'
extra={'assets/avatar/a01-neutral-graph-v1/runtime-04/'+n:data for n,data in files.items()}
cert=natural.verify(built,oldfiles,15,'0.6.2-mouth-dev',extra);assert cert==CERT
signature=natural.run([natural.TOOLS/'apksigner','verify','--print-certs',ui],'signature-code14.txt');assert CERT in signature
with zipfile.ZipFile(built) as new,zipfile.ZipFile(ui) as old:
for n in old.namelist():
if n.startswith('assets/avatar/') and not n.endswith('/'):assert new.read(n)==old.read(n)
if not args.verify_existing:
with ARTIFACT.open('xb') as f:f.write(built.read_bytes())
digest=sha(ARTIFACT.read_bytes());checksum=f'{digest} {ARTIFACT.name}\n'.encode();side=ARTIFACT.with_suffix('.apk.sha256')
assert not side.exists() or side.read_bytes()==checksum;side.write_bytes(checksum)
url='http://192.168.31.124:8080/'+ARTIFACT.name;opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open(url,timeout=15) as response:
data=response.read();assert response.status==200 and len(data)==ARTIFACT.stat().st_size and sha(data)==digest
with opener.open(url+'.sha256',timeout=15) as response:assert response.status==200 and response.read()==checksum
result={'scope':'coordinator_authorized_runtime04_debug_device_candidate_only','version':'0.6.2-mouth-dev','versionCode':15,
'url':url,'apk':str(ARTIFACT),'sha256':digest,'bytes':ARTIFACT.stat().st_size,'sameCertificateSha256':cert,'manifestSha256':PIN,
'httpBytesVerified':True,'permissionTiming':'foreground_host_layout_before_network','offlinePermissions':'manual_only_no_collection','mouthChanged':True,'mouthDeformationResolved':'not_certified','bodyChanged':False,
'naturalQuality':'device_pending','visibleTalk':'device_pending','stairStepping':'device_pending','compliance1s':'not_certified',
'productionApproval':False,'deviceInstall':'not_attempted','offlineExtra':'avatar_offline_preview'}
(LOG/'delivery.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
if __name__=='__main__':main()