9ea5eb31c1
Keep the avatar mounted while all connection, permission, privacy and diagnostic controls live in a settings sheet. Save the tested continuous-body renderer, safe transition driver and foreground HELLO/permission workflow from this session. Pin runtime03 for the code14 UI-only candidate; mouth deformation remains unresolved. Add source UI contracts, an optional sensor-free device probe, exact asset import and candidate packaging checks. Portrait binaries and diagnostics remain private and untracked.
163 lines
11 KiB
Python
163 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Pinned runtime03 natural engineering candidate; no final approval, overwrite or device action."""
|
|
from pathlib import Path
|
|
import argparse, hashlib, importlib.util, json, os, re, subprocess, tempfile, urllib.request, zipfile
|
|
from PIL import Image
|
|
import numpy as np
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
SOURCE=ROOT/'.runtime/avatar-imports/a01-neutral-graph-v1/runtime-03'
|
|
PACK=ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1/runtime-03'
|
|
LOG=ROOT/'logs/avatar-natural-061'
|
|
ARTIFACT=ROOT/'artifacts/lan-voice-v061-natural-engineering-arm64-debug.apk'
|
|
PIN='87ad2b2ad0e96fe64943692da363c856939ad4aad57073c589d53130c2f2073c'
|
|
BASELINE='9fcfd258a214be0fbe4a3ebd8141221f078ba0e6af0aaf6955437d725eecf814'
|
|
TOOLS=Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
|
|
sha=lambda data:hashlib.sha256(data).hexdigest()
|
|
|
|
def run(args,name):
|
|
result=subprocess.run(list(map(str,args)),cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
|
(LOG/name).write_text(result.stdout)
|
|
assert result.returncode==0,f'{args[0]} failed: {LOG/name}'
|
|
return result.stdout
|
|
|
|
def import_runtime():
|
|
raw=(SOURCE/'manifest.json').read_bytes();assert sha(raw)==PIN,'Runtime manifest drift; stop admission'
|
|
m=json.loads(raw)
|
|
assert m['runtimeReady'] is True and m['publishApproval'] is False
|
|
assert m['safeTransitions']['reviewStatus']=='pending' and not m['approvedEdges']
|
|
assert m['naturalQualityStatus']=='pending' and m['deviceTestStatus']=='pending'
|
|
body=m['body'];assert body['frameCount']==97 and body['durationUs']==4041667 and body['hasAudio'] is False
|
|
assert body['width']==480 and body['height']==848 and body['fpsNumerator']==24 and body['fpsDenominator']==1
|
|
assert m['patchFormat']['alphaEncoding']=='straight_unassociated'
|
|
files={'manifest.json':raw};patches=m['patches'];assert len(patches)==97
|
|
size=0
|
|
for index,row in enumerate([body]+patches):
|
|
name=row['path']
|
|
assert re.fullmatch(r'body/[A-Za-z0-9_.-]+\.mp4' if index==0 else r'patches/[A-Za-z0-9_.-]+\.png',name)
|
|
path=(SOURCE/name).resolve(strict=True);assert path.is_relative_to(SOURCE.resolve())
|
|
assert path.stat().st_size<16_000_000 if index==0 else path.stat().st_size<256_000
|
|
data=path.read_bytes();assert sha(data)==row['sha256']
|
|
assert name not in files;files[name]=data
|
|
if index:
|
|
assert row['frameIndex']==index-1 and abs(row['ptsUs']-(index-1)*1000000//24)<=2
|
|
assert 0<=row['x'] and 0<=row['y'] and row['x']+row['width']<=480 and row['y']+row['height']<=848
|
|
with Image.open(path) as im:
|
|
assert im.mode=='RGBA' and im.size==(row['width'],row['height'])
|
|
size+=row['width']*row['height']*4
|
|
assert size<=8_000_000
|
|
for name,data in files.items():
|
|
dest=PACK/name;assert not dest.exists() or dest.read_bytes()==data,f'Unknown destination: {dest}'
|
|
for name,data in files.items():
|
|
dest=PACK/name;dest.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
if not dest.exists():
|
|
fd,tmp=tempfile.mkstemp(prefix='.runtime03-',dir=dest.parent)
|
|
try:
|
|
with os.fdopen(fd,'wb') as stream:stream.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
|
|
return m,files
|
|
|
|
def verify_decode(m):
|
|
body=m['body'];path=PACK/body['path']
|
|
probe=json.loads(run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',path],'body-probe.json'))
|
|
assert len(probe['streams'])==1 and len(probe['frames'])==97
|
|
stream=probe['streams'][0];assert stream['codec_type']=='video' and stream['codec_name']=='h264' and stream['pix_fmt']=='yuv420p'
|
|
assert stream['width']==480 and stream['height']==848 and stream['r_frame_rate']=='24/1'
|
|
assert all(abs(float(f['best_effort_timestamp_time'])-i/24)<1e-5 for i,f in enumerate(probe['frames']))
|
|
run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',path,'-map','0:v:0','-f','null','-'],'body-full-decode.txt')
|
|
# Stream frames without keeping wholebody frame stacks in memory. Independently
|
|
# validate exact alpha-zero identity and straight vs premul source-over algebra.
|
|
process=subprocess.Popen(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-i',str(path),'-map','0:v:0','-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
|
checks=[]
|
|
try:
|
|
for index,p in enumerate(m['patches']):
|
|
data=process.stdout.read(480*848*3);assert len(data)==480*848*3
|
|
bodypixels=np.frombuffer(data,np.uint8).reshape(848,480,3)
|
|
patch=np.asarray(Image.open(PACK/p['path']).convert('RGBA'),np.float32)/255
|
|
x,y=p['x'],p['y'];assert isinstance(x,int) and isinstance(y,int)
|
|
base=bodypixels[y:y+p['height'],x:x+p['width']].astype(np.float32)/255
|
|
a=patch[:,:,3:4];rgb=patch[:,:,:3]
|
|
for g in (0,.5,1):
|
|
straight=base*(1-g*a)+rgb*(g*a)
|
|
premul=base*(1-g*a)+(rgb*a)*g
|
|
assert np.max(np.abs(straight-premul))<1e-6
|
|
if g==0:assert np.array_equal(straight,base)
|
|
if index in (0,17,34,43,52,78,96):
|
|
checks.append({'frame':index,'globalAlpha':g,'alphaZeroExactBody':True if g==0 else None,
|
|
'straightVsPremulMaxDiff':float(np.max(np.abs(straight-premul))),
|
|
'scope':'CPU algebra only; Android GPU/Bitmap colors and perceived naturalness pending'})
|
|
assert process.stdout.read(1)==b'';assert process.wait(timeout=20)==0
|
|
finally:
|
|
if process.poll() is None:process.kill();process.wait()
|
|
(LOG/'independent-alpha-checks.json').write_text(json.dumps(checks,indent=2)+'\n')
|
|
|
|
def tests_current():
|
|
tests=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
|
assert tests['status']=='passed' and tests['jvm_entry_points']==9
|
|
for name,h in tests['hashes'].items():assert sha((ROOT/name).read_bytes())==h,f'Untested source: {name}'
|
|
assert re.search(r'Ran 74 tests .*\n\nOK\s*$',(ROOT/'logs/avatar-safe-061/gateway-tests.txt').read_text())
|
|
assert PIN in (LOG/'actual-manifest-tests.txt').read_text() and 'PASS: actual exported runtime manifest parsed' in (LOG/'actual-manifest-tests.txt').read_text()
|
|
assert sha((ROOT/'artifacts/lan-voice-v061-engineering-arm64-debug.apk').read_bytes())==BASELINE
|
|
assert sha((ROOT/'artifacts/lan-voice-v060-arm64-debug.apk').read_bytes())=='37f789820e86ac1656bda546f47ece3e4533ff8fc54614b171fd8a42accaa52e'
|
|
assert 'APPROVED_MOTION_HASHES = emptySet<String>()' in (ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/AvatarPack.kt').read_text()
|
|
|
|
def verify(apk,files,version_code=13,version_name='0.6.1-natural-dev'):
|
|
badge=run([TOOLS/'aapt','dump','badging',apk],'badging.txt')
|
|
for value in ("name='com.gorios.lanvoice'",f"versionCode='{version_code}'",f"versionName='{version_name}'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
|
assert value in badge,value
|
|
assert re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'"
|
|
signature=run([TOOLS/'apksigner','verify','--verbose','--print-certs',apk],'signature.txt')
|
|
pattern=r'Signer #1 certificate SHA-256 digest: (\w+)';cert=re.search(pattern,signature)[1]
|
|
for suffix in ('051','052','060','061-engineering'):
|
|
other=run([TOOLS/'apksigner','verify','--print-certs',ROOT/f'artifacts/lan-voice-v{suffix}-arm64-debug.apk'],f'signature-{suffix}.txt')
|
|
assert re.search(pattern,other)[1]==cert
|
|
# Keep controlled01 code/data as the existing engineering baseline; verify every
|
|
# byte without admitting any natural02/03 review demo as a runtime substitute.
|
|
base=ROOT/'app/src/main/assets/avatar/a01-neutral-graph-v1'
|
|
oldraw=(base/'manifest.json').read_bytes();assert sha(oldraw)=='e6b6e9a6e555cafb3ca7e0878600c23c4d76f13fb15d98d5f0cd8e5b192a3a09'
|
|
old=json.loads(oldraw)
|
|
expected={'assets/avatar/a01-neutral-graph-v1/runtime-03/'+n:d for n,d in files.items()}
|
|
expected['assets/avatar/a01-neutral-graph-v1/manifest.json']=oldraw
|
|
for row in old['assets']+[old['anchorImages'][0]]:
|
|
data=(base/row['path']).read_bytes();assert sha(data)==row['sha256']
|
|
expected['assets/avatar/a01-neutral-graph-v1/'+row['path']]=data
|
|
still='assets/avatar/a01-standing-arms-reference/frames/reference.png';data=(ROOT/'app/src/main'/still).read_bytes()
|
|
assert sha(data)=='36a078ad9e1d2929612e9baa2af524bda90dafceddc4515dd448fc08121d7dd2';expected[still]=data
|
|
with zipfile.ZipFile(apk) as z:
|
|
actual={n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')}
|
|
assert actual==set(expected),f'Unexpected/missing avatar files: {actual^set(expected)}'
|
|
for name,data in expected.items():
|
|
assert z.read(name)==data,name
|
|
if name.endswith('.mp4'):assert z.getinfo(name).compress_type==zipfile.ZIP_STORED
|
|
return cert
|
|
|
|
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()
|
|
if args.import_only:
|
|
verify_decode(m);print('PASS: runtime03 exact candidate manifest, body/97 RGBA patch bytes, complete CFR decode, independent alpha-zero/straight-premul algebra');return
|
|
tests_current()
|
|
if args.verify_existing:assert ARTIFACT.is_file();cert=verify(ARTIFACT,files)
|
|
else:
|
|
assert not ARTIFACT.exists(),'Preserve existing natural engineering artifact; no overwrite'
|
|
run([ROOT/'scripts/build.sh','assembleDebug','-PavatarNatural=true','-PnaturalManifestSha='+PIN],'assemble.txt')
|
|
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';cert=verify(built,files)
|
|
with ARTIFACT.open('xb') as stream:stream.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':'natural_engineering_candidate_only','version':'0.6.1-natural-dev','versionCode':13,'apk':str(ARTIFACT),'url':url,
|
|
'bytes':ARTIFACT.stat().st_size,'sha256':digest,'sameCertificateSha256':cert,'manifestSha256':PIN,'httpBytesVerified':True,
|
|
'productionApproval':False,'naturalQuality':'pending_device_visual_review','bodyLoopSeam':'pending_device_visual_review','actualPerceivedMouthLatencyMs':None,
|
|
'devicePerf':'not_tested','compliance1s':'not_certified','gitCommitPush':False,'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()
|