113 lines
7.0 KiB
Python
113 lines
7.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only Gate1 plus production Kotlin admission; never imports or approves assets."""
|
|
import argparse
|
|
from decimal import Decimal
|
|
from fractions import Fraction
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
from PIL import Image
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
SUPPORTED_SHAPES={(480,848),(720,1280)}
|
|
|
|
def require(value,reason):
|
|
if not value: raise ValueError(reason)
|
|
|
|
def check_runtime(manifest_path, expected_sha, kotlin=True):
|
|
source=Path(manifest_path).resolve(strict=True);directory=source.parent
|
|
require(source.stat().st_size<=2_000_000,'manifest byte bound')
|
|
raw=source.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
|
require(re.fullmatch('[0-9a-f]{64}',expected_sha) and digest==expected_sha,'candidate manifest drift')
|
|
def unique(pairs):
|
|
result={}
|
|
for key,value in pairs:
|
|
require(key not in result,'duplicate manifest key');result[key]=value
|
|
return result
|
|
manifest=json.loads(raw,object_pairs_hook=unique)
|
|
body=manifest['body'];count=body['frameCount']
|
|
require(type(count) is int and 2<=count<=720,'body frame bound')
|
|
dynamic=manifest['schemaVersion']==2
|
|
require(dynamic or manifest['packId'] in ('a01-neutral-graph-v1-runtime-03','a01-neutral-graph-v1-runtime-04'),'new bodies require schema2')
|
|
if dynamic:
|
|
require(manifest['patchFormat']['bodySha256']==body['sha256'],'own-mouth body binding')
|
|
verified={}
|
|
def file(row,pattern,bound):
|
|
name=row['path'];require(re.fullmatch(pattern,name),'asset path shape')
|
|
path=(directory/name).resolve(strict=True)
|
|
require(path.is_relative_to(directory),'asset path escape')
|
|
require(path.stat().st_size<=bound,'asset file byte bound')
|
|
sha=hashlib.sha256(path.read_bytes()).hexdigest()
|
|
require(sha==row['sha256'],'asset file hash mismatch')
|
|
verified[name]=sha
|
|
return path
|
|
video=file(body,r'body/[A-Za-z0-9_.-]+\.mp4',64_000_000)
|
|
probe=subprocess.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',str(video)],capture_output=True,check=True,timeout=60)
|
|
decoded=json.loads(probe.stdout);streams=decoded['streams'];frames=decoded['frames']
|
|
require(len(streams)==1 and streams[0]['codec_type']=='video' and body['hasAudio'] is False,'conversation must be silent video')
|
|
stream=streams[0]
|
|
require(stream['codec_name']=='h264' and (stream['width'],stream['height'])==(body['width'],body['height']) and (body['width'],body['height']) in (SUPPORTED_SHAPES if dynamic else {(480,848)}),'codec/shape mismatch')
|
|
require(Fraction(stream['r_frame_rate'])==Fraction(body['fpsNumerator'],body['fpsDenominator']),'measured nominal fps mismatch')
|
|
require(len(frames)==count,'decoded actual N mismatch')
|
|
pts=[int((Decimal(frame['best_effort_timestamp_time'])*1_000_000).to_integral_value()) for frame in frames]
|
|
expected=body['ptsUs'] if dynamic else [i*1_000_000//24 for i in range(count)]
|
|
require(len(expected)==count and all(abs(a-b)<=2 for a,b in zip(pts,expected)),'decoded actual PTS mismatch')
|
|
duration=int((Decimal(stream['duration'])*1_000_000).to_integral_value())
|
|
require(abs(duration-body['durationUs'])<=2,'decoded duration mismatch')
|
|
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(video),'-map','0:v:0','-f','null','-'],capture_output=True,check=True,timeout=60)
|
|
patches=manifest['patches'];require(len(patches)==count,'N patches required')
|
|
rgba=0;paths=[];aperture=manifest['packId'].endswith('runtime-04')
|
|
for i,patch in enumerate(patches):
|
|
require(patch['frameIndex']==i and abs(patch['ptsUs']-pts[i])<=2,'own-frame patch binding')
|
|
if dynamic: require(patch['ptsUs']==expected[i],'schema2 exact patch PTS binding')
|
|
width,height=patch['width'],patch['height']
|
|
require(type(width) is int and type(height) is int and 1<=width<=128 and 1<=height<=128,'patch shape bound')
|
|
require(all(isinstance(patch[k],(int,float)) and not isinstance(patch[k],bool) for k in ('x','y')) and
|
|
0<=patch['x']<=body['width']-width and 0<=patch['y']<=body['height']-height,'patch pixel bounds')
|
|
levels=patch['levels'] if aperture else [patch]
|
|
require(len(levels)==(5 if aperture else 1),'five own levels required')
|
|
for level in levels:
|
|
image=file(level,r'patches/[A-Za-z0-9_.-]+\.png',256_000);paths.append(level['path'])
|
|
with Image.open(image) as bitmap:
|
|
require(bitmap.format=='PNG' and bitmap.mode=='RGBA' and bitmap.size==(width,height),'decoded PNG RGBA/shape mismatch')
|
|
bitmap.load()
|
|
rgba+=width*height*4
|
|
require(len(set(paths))==len(paths) and rgba<=8_000_000,'unique N levels/cache bound')
|
|
if kotlin:
|
|
result=subprocess.run([sys.executable,str(ROOT/'scripts/check-reply-regressions.py'),'--suite','avatar','--runtime-manifest',str(source)],capture_output=True,text=True,timeout=120)
|
|
require(result.returncode==0,'production Kotlin admission failed (candidate format or metadata)')
|
|
require('PASS: actual exported runtime manifest parsed' in result.stdout,'actual parser evidence absent')
|
|
require(source.read_bytes()==raw,'manifest changed during gate')
|
|
for name,sha in verified.items():
|
|
require(hashlib.sha256((directory/name).read_bytes()).hexdigest()==sha,'asset changed during gate')
|
|
evidence={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':digest,
|
|
'body_sha256':body['sha256'],'schema_version':manifest['schemaVersion'],'body_shape':[body['width'],body['height']],'actual_frame_count':count,
|
|
'actual_pts_count':len(pts),'actual_duration_us':duration,'patch_images':len(paths),'rgba_cache_bytes':rgba,
|
|
'verified_files':len(verified),'full_decode':'passed','production_kotlin_parser':'passed' if kotlin else 'checked_by_bundle_parser','naturalness':'pending','real_device':'not_run'}
|
|
return evidence, verified
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--manifest',type=Path,required=True)
|
|
parser.add_argument('--sha256',required=True,help='Exact candidate hash; not a publication approval')
|
|
parser.add_argument('--output',type=Path,required=True,help='New evidence outside owner directory')
|
|
args=parser.parse_args()
|
|
output=args.output.resolve();source=args.manifest.resolve(strict=True)
|
|
require(not output.exists() and not output.is_relative_to(source.parent),'evidence must be new and outside owner directory')
|
|
evidence,_=check_runtime(source,args.sha256)
|
|
output.parent.mkdir(parents=True,exist_ok=True)
|
|
with output.open('x') as target: json.dump(evidence,target,indent=2);target.write('\n')
|
|
print(json.dumps(evidence))
|
|
|
|
|
|
if __name__=='__main__':
|
|
try: main()
|
|
except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError) as error:
|
|
print('FAIL: runtime gate: '+str(error),file=sys.stderr)
|
|
raise SystemExit(1)
|