Add bounded avatar rejection fields and task music ASR audit

This commit is contained in:
zenord
2026-10-13 06:19:54 +08:00
parent 33b552473a
commit c4ddf8964f
10 changed files with 386 additions and 13 deletions
+27 -5
View File
@@ -35,8 +35,12 @@ parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--suite', choices=[name for name, _, _ in suites])
parser.add_argument('--runtime-manifest',type=Path,help='Additionally exercise real continuous parser with actual offline manifest metadata')
parser.add_argument('--index-manifest',type=Path,help='Additionally admit an exact offline v2 index and each referenced runtime through production parsers; no activation')
parser.add_argument('--metadata-only',action='store_true',help='Only the actual manifest admission, without repeating fixtures')
parser.add_argument('--rejection-report',type=Path,help='New bounded structural field report; no raw values')
args = parser.parse_args()
if args.index_manifest and args.runtime_manifest: parser.error('Choose runtime or index manifest, not both')
if args.metadata_only and not (args.index_manifest or args.runtime_manifest): parser.error('Actual manifest required')
if args.rejection_report and (not args.index_manifest or args.rejection_report.exists()): parser.error('Index and new rejection report required')
for name, main, real in suites:
if args.suite and name != args.suite: continue
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out:
@@ -86,17 +90,35 @@ for name, main, real in suites:
extra=Path(out)/'ActualIndexCheck.kt'
extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+
'fun main() {\nval root='+index_literal+'\nval runtimes='+runtime_literal+'\nval hashes='+hash_literal+'\n'+
'val index=checkNotNull(EmotionActionManifest.read(root,"'+digest+'","'+digest+'","fixture/") { path,hash ->\n'+
'check(hashes[path]==hash)\n@Suppress("UNCHECKED_CAST")\n'+
'ContinuousAvatarManifest.read(runtimes[path] as Map<String,Any?>,hash,hash,true,"fixture/"+path.substringBeforeLast(47.toChar())+"/")\n})\n'+
'val parsed=runtimes.mapValues { (path,value) ->\nval hash=hashes.getValue(path) as String\n'+
'@Suppress("UNCHECKED_CAST")\nContinuousAvatarManifest.read(value as Map<String,Any?>,hash,hash,true,"fixture/"+path.substringBeforeLast(47.toChar())+"/",'+
'onReject={ field -> println("REJECT_FIELD|"+path+"|"+field) })\n}\n'+
'val index=checkNotNull(EmotionActionManifest.read(root,"'+digest+'","'+digest+'","fixture/",'+
'onReject={ field -> println("REJECT_FIELD|manifest.json|"+field) }) { path,hash ->\n'+
'check(hashes[path]==hash)\nparsed[path]\n})\n'+
'check(index.packages.values.all { it.textureImages.size==it.body.frameCount*5 })\n'+
('check(index.actionPack==null)\n' if not data['actions'] else 'check(index.actionPack?.assets?.size==2)\n')+
'println("PASS: actual exported v2 index parsed by production Kotlin, exact hash '+digest+'; packages="+index.packages.size+" rgbaBytes="+index.packages.values.sumOf { it.rgbaBytes }+" danceAvailable="+(index.actionPack!=null))\n}\n')
files.append(extra)
subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib',
'-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',out, *map(str,files)],check=True,cwd=ROOT)
subprocess.run([JAVA,'-cp',out+':'+cp,main],check=True,cwd=ROOT,timeout=30)
if not args.metadata_only:
subprocess.run([JAVA,'-cp',out+':'+cp,main],check=True,cwd=ROOT,timeout=30)
if name == 'avatar' and args.runtime_manifest:
subprocess.run([JAVA,'-cp',out+':'+cp,'ActualRuntimeCheckKt'],check=True,cwd=ROOT,timeout=30)
if name == 'avatar' and args.index_manifest:
subprocess.run([JAVA,'-cp',out+':'+cp,'ActualIndexCheckKt'],check=True,cwd=ROOT,timeout=30)
result=subprocess.run([JAVA,'-cp',out+':'+cp,'ActualIndexCheckKt'],capture_output=True,text=True,cwd=ROOT,timeout=30)
if args.rejection_report:
rejects=[]
for line in result.stdout.splitlines():
if line.startswith('REJECT_FIELD|'):
_,path,field=line.split('|',2)
if len(rejects)<128: rejects.append({'file':path,'field':field,'code':'production_metadata_rejected'})
args.rejection_report.parent.mkdir(parents=True,exist_ok=True)
with args.rejection_report.open('x') as f:
json.dump({'status':'passed' if result.returncode==0 else 'rejected','manifest_sha256':digest,
'scope':'production_metadata_only_no_media_admission_no_activation','rejects':rejects},f,indent=2)
f.write('\n')
print(result.stdout,end='')
if result.returncode: print('FAIL: production index admission; structural fields above, no raw metadata output',file=__import__('sys').stderr)
result.check_returncode()
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Bounded read-only rejection fields; does not import, approve, or replace the full gate."""
from pathlib import Path
import argparse
import importlib.util
import json
import subprocess
import sys
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('pack',ROOT/'scripts/package-avatar-emotion.py')
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
def diagnose(manifest,expected,output):
manifest=Path(manifest).resolve(strict=True);output=Path(output).resolve()
pack.require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner directory required')
pack.require(pack.file_sha(manifest)==expected,'candidate index drift')
index=pack.read_json(manifest);root=manifest.parent
pack.require(1<=len(index['conversationPackages'])<=12 and len(index['edges'])<=100 and len(index['actions'])<=2,'diagnostic graph bounds')
output.mkdir(parents=True)
rejects=[];streams=[]
def reject(file,field,code,**counts):
if len(rejects)<128: rejects.append({'file':file,'field':field,'code':code,**counts})
references=[row['runtimeManifest'] for row in index['conversationPackages']]
references += [edge['mouthRuntimeManifest'] for edge in index['edges'] if 'mouthRuntimeManifest' in edge]
for ref in references:
try:
path=pack.locate(root,ref['path'])
pack.require(pack.file_sha(path)==ref['sha256'],'runtime hash drift')
data=pack.read_json(path)
for i,state in enumerate(data['mouthStates']):
alpha=len(state['globalAlphaByFrame']);pts=len(state.get('ptsUs',[]))
if state['frameCount']!=alpha:
reject(ref['path'],f'mouthStates[{i}].frameCount','curve_frame_count_mismatch',declared=state['frameCount'],expected=alpha)
if data['schemaVersion']==2 and pts!=alpha:
reject(ref['path'],f'mouthStates[{i}].ptsUs','curve_pts_count_mismatch',declared=pts,expected=alpha)
except (ValueError,KeyError,TypeError,OSError):
reject('manifest.json','runtimeManifest','runtime_reference_invalid')
for i,action in enumerate(index['actions']):
field=f'actions[{i}].clip'
try:
clip=action['clip'];path=pack.locate(root,clip['path'])
pack.require(pack.file_sha(path)==clip['sha256'],'action hash drift')
run=subprocess.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-of','json',str(path)],capture_output=True,check=True,timeout=30)
observed=json.loads(run.stdout)['streams']
# No tags, lyrics, filenames beyond validated task-relative paths, or raw model output.
rows=[{k:s[k] for k in ('index','codec_type','codec_name','duration','sample_rate','channels') if k in s} |
{'attached_pic':s.get('disposition',{}).get('attached_pic',0)} for s in observed]
streams.append({'field':field,'file':clip['path'],'streams':rows})
if len(rows)!=2 or sorted(s['codec_type'] for s in rows)!=['audio','video'] or any(s['attached_pic'] for s in rows):
reject('manifest.json',field+'.path','dance_stream_layout_requires_video_audio_without_cover',clip_path=clip['path'])
except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError):
reject('manifest.json',field,'action_probe_failed')
parser_report=output/'production-parser.json'
run=subprocess.run([sys.executable,str(ROOT/'scripts/check-reply-regressions.py'),'--suite','avatar',
'--index-manifest',str(manifest),'--metadata-only','--rejection-report',str(parser_report)],capture_output=True,timeout=180)
if parser_report.exists():
parsed=json.loads(parser_report.read_bytes());rejects.extend(parsed['rejects'][:128-len(rejects)])
else:
parsed={'status':'not_completed'}
reject('manifest.json','$','production_parser_execution_failed')
pack.require(pack.file_sha(manifest)==expected,'candidate drift during diagnostics')
report={'status':'rejected' if rejects or run.returncode else 'no_reject_found',
'manifest_sha256':expected,'scope':'read_only_rejection_diagnostics_not_full_media_gate',
'production_metadata':parsed['status'],'rejects':rejects,'action_streams':streams,
'dance_available':False,'naturalness':'not_certified','human_listening':'not_run','device':'not_run',
'source_hashes':{name:pack.file_sha(ROOT/name) for name in ('scripts/diagnose-avatar-candidate.py',
'scripts/check-reply-regressions.py','app/src/main/java/com/gorios/lanvoice/avatar/ContinuousAvatarManifest.kt',
'app/src/main/java/com/gorios/lanvoice/avatar/EmotionActionManifest.kt')}}
with (output/'reject-details.json').open('x') as f:json.dump(report,f,indent=2);f.write('\n')
return report
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--sha256',required=True)
parser.add_argument('--output',type=Path,required=True);args=parser.parse_args()
report=diagnose(args.manifest,args.sha256,args.output)
print(json.dumps({'status':report['status'],'reject_count':len(report['rejects']),'report':str(args.output/'reject-details.json')}))
return 1 if report['status']=='rejected' else 0
if __name__=='__main__':raise SystemExit(main())
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Exactly one existing local ASR request per task dance; no transcript persistence or verdict."""
import argparse
import base64
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import subprocess
import wave
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location('pack',ROOT/'scripts/package-avatar-emotion.py')
pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
REMOTE=r'''
import base64,json,ssl,urllib.request
from pathlib import Path
import httpx
report={'status':'failed','asr_requests':0,'http_attempts':0,'paid_calls':0,'results':[],
'scope':'task-generated music auxiliary ASR only; no actor attribution',
'human_listening':'not_run','actor_no_speech':'not_certified','device':'not_run'}
def health():
context=ssl.create_default_context(cafile='/home/gorios-spark-2/lan-voice/.runtime/gateway-cert.pem')
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=context))
with opener.open('https://192.168.31.61:5011/health',timeout=5) as response:return json.load(response)
try:
assert len(inputs)==2
with httpx.Client(timeout=60,trust_env=False) as client:
for item in inputs:
if health().get('busy'):raise RuntimeError('busy_no_probe')
report['http_attempts']+=1
response=client.post('http://192.168.31.61:5001/v1/audio/transcriptions',
files={'file':('task-music.wav',base64.b64decode(item['wav']),'audio/wav')})
report['asr_requests']+=1
row={'id':item['id'],'http_status':response.status_code}
report['results'].append(row)
if response.status_code!=200:raise RuntimeError('asr_http_error')
data=response.json();text=data.get('text')
if not isinstance(text,str):raise TypeError('asr_text_shape')
row.update(text_nonempty=bool(text.strip()),text_length=len(text),model_is_unknown=not bool(data.get('model')))
del text,data,response
report['status']='passed_auxiliary_only'
except Exception as error:
report['error_type']=type(error).__name__
report['reason']='busy_no_probe' if isinstance(error,RuntimeError) and str(error)=='busy_no_probe' else 'auxiliary_probe_failed_no_retry'
print(json.dumps(report))
raise SystemExit(0 if report['status']=='passed_auxiliary_only' else 1)
'''
def finite_wav(pcm):
pack.require(0<len(pcm)<=16000*15*2 and len(pcm)%2==0,'decoded music PCM bound')
buffer=io.BytesIO()
with wave.open(buffer,'wb') as wav:
wav.setnchannels(1);wav.setsampwidth(2);wav.setframerate(16000);wav.writeframes(pcm)
return buffer.getvalue()
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--sha256',required=True)
parser.add_argument('--output',type=Path,required=True);args=parser.parse_args()
manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
pack.require(not output.exists() and output.is_relative_to(ROOT/'logs'),'new ignored evidence required')
pack.require(pack.file_sha(manifest)==args.sha256,'index hash drift')
index=pack.read_json(manifest);actions=index['actions']
pack.require(len(actions)==2 and {a['id'] for a in actions}=={'asset_01','asset_02'},'exactly two task dances required')
inputs=[];metadata=[]
for action in actions:
clip=action['clip'];path=pack.locate(manifest.parent,clip['path'])
pack.require(pack.file_sha(path)==clip['sha256'] and 0<clip['durationUs']<=15_000_000,'bounded task clip binding')
pcm=subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path),
'-map','0:a:0','-ac','1','-ar','16000','-f','s16le','-'],capture_output=True,check=True,timeout=30).stdout
audio=finite_wav(pcm) # Actual length, unlike ffmpeg's streaming WAV header.
pack.require(44<len(audio)<=16000*16*2,'public task audio byte bound')
inputs.append({'id':action['id'],'wav':base64.b64encode(audio).decode()})
metadata.append({'id':action['id'],'clip_sha256':clip['sha256'],'input_wav_bytes':len(audio),
'declared_video_duration_us':clip['durationUs'],'declared_audio_end_us':action['audioEndUs']})
run=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',
'cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],
input=('inputs='+repr(inputs)+'\n'+REMOTE).encode(),capture_output=True,timeout=140)
report=json.loads(run.stdout) if run.stdout else {'status':'failed','reason':'ssh_failed_no_retry','asr_requests':'unknown','paid_calls':0}
report.update(manifest_sha256=args.sha256,input_metadata=metadata,
probe_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),remote_exit=run.returncode)
pack.require(pack.file_sha(manifest)==args.sha256,'index drift during auxiliary check')
output.parent.mkdir(parents=True,exist_ok=True)
with output.open('x') as f:json.dump(report,f,indent=2);f.write('\n')
print(json.dumps(report,indent=2))
return run.returncode or (0 if report['status']=='passed_auxiliary_only' else 1)
if __name__=='__main__':raise SystemExit(main())