feat: refine role expression and diagnose camera context in 0.5.2
This commit is contained in:
@@ -29,10 +29,13 @@ with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt',
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/FaceCueRules.kt',
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/CameraPermissionGate.kt',
|
||||
'app/src/main/java/com/gorios/lanvoice/expression/FaceDiagnostics.kt',
|
||||
'tests/expression/ExpressionRulesCheck.kt',
|
||||
'tests/expression/FaceCueRulesCheck.kt',
|
||||
'tests/expression/CameraPermissionCheck.kt'], check=True)
|
||||
'tests/expression/CameraPermissionCheck.kt',
|
||||
'tests/expression/FaceDiagnosticsCheck.kt'], check=True)
|
||||
subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True)
|
||||
subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceCueRulesCheckKt'], check=True)
|
||||
subprocess.run([java, '-cp', output + ':' + stdlib, 'CameraPermissionCheckKt'], check=True)
|
||||
subprocess.run([java, '-cp', output + ':' + stdlib, 'FaceDiagnosticsCheckKt'], check=True)
|
||||
PY
|
||||
|
||||
@@ -23,7 +23,7 @@ compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.
|
||||
cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')])
|
||||
source = ROOT/'app/src/main/java/com/gorios/lanvoice'
|
||||
suites = [
|
||||
('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
|
||||
('session','ConnectionCheckKt', [source/'audio/VoiceSession.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
|
||||
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt']),
|
||||
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
|
||||
('protocol','ProtocolCheckKt', [source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
|
||||
|
||||
@@ -7,13 +7,16 @@ from pathlib import Path
|
||||
import hashlib,json
|
||||
root=Path.cwd();directory=root/'logs/voice-investigation'
|
||||
load=lambda name:json.loads((directory/name).read_text())
|
||||
deploy=load('gateway-emotion-deploy.json');probe=load('probe-emotion.json');client=load('client-emotion-tests.json');compat=load('reply-structure.json')
|
||||
deploy=load('gateway-emotion-deploy.json');probe=load('probe-emotion.json');client=load('client-emotion-tests.json')
|
||||
compat=json.loads((root/'logs/emotion-052/semantic-candidate.json').read_text())
|
||||
assert deploy['applied'] and deploy['health']=='ok' and deploy['environment_unchanged']
|
||||
assert probe['status']=='passed' and probe['downlink_bytes']>0 and probe['emotion_before_pcm'] and probe['drained_ack'] and probe['tts_requests']==1
|
||||
assert compat['status']=='passed' and client['status']=='passed'
|
||||
assert compat['status']=='passed' and compat['semantic_status']=='matched_fixed_cases' and client['status']=='passed'
|
||||
for name,digest in deploy['hashes'].items():assert hashlib.sha256((root/'gateway'/name).read_bytes()).hexdigest()==digest,name
|
||||
for name,digest in client['hashes'].items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest,name
|
||||
assert not (root/'artifacts/lan-voice-v051-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite'
|
||||
assert not (root/'artifacts/lan-voice-v052-arm64-debug.apk').exists(), 'release artifact exists: refusing overwrite'
|
||||
assert (root/'artifacts/lan-voice-v051-arm64-debug.apk').is_file(), 'previous release required for signature comparison/rollback'
|
||||
assert hashlib.sha256((root/'gateway/reply_emotion.py').read_bytes()).hexdigest()==compat['candidate_source_sha256'], 'semantic probe does not match candidate prompt source'
|
||||
print('Verified tested client/provider source and successful deployed pipeline before APK build')
|
||||
PY
|
||||
./scripts/build.sh
|
||||
@@ -29,20 +32,19 @@ from pathlib import Path
|
||||
root=Path.cwd()
|
||||
badging=(root/'logs/voice-investigation/release-emotion-badging.txt').read_text()
|
||||
assert "name='com.gorios.lanvoice'" in badging
|
||||
assert "versionCode='9'" in badging and "versionName='0.5.1'" in badging
|
||||
assert "versionCode='10'" in badging and "versionName='0.5.2'" in badging
|
||||
native=re.search(r'^native-code: (.+)$',badging,re.M)
|
||||
assert native and native[1].strip()=="'arm64-v8a'", 'unexpected ABI'
|
||||
source=root/'app/build/outputs/apk/debug/app-debug.apk'
|
||||
previous=root/'artifacts/lan-voice-v040-arm64-debug.apk'
|
||||
previous=root/'artifacts/lan-voice-v051-arm64-debug.apk'
|
||||
if previous.exists():
|
||||
old=subprocess.check_output(['/home/ubuntu/android-build/sdk/build-tools/34.0.0/apksigner','verify','--print-certs',str(previous)],text=True)
|
||||
new=(root/'logs/voice-investigation/release-emotion-signature.txt').read_text()
|
||||
pattern=r'Signer #1 certificate SHA-256 digest: (\w+)'
|
||||
assert re.search(pattern,old)[1]==re.search(pattern,new)[1], 'signing certificate changed: update install would fail'
|
||||
artifact=root/'artifacts/lan-voice-v051-arm64-debug.apk'
|
||||
artifact=root/'artifacts/lan-voice-v052-arm64-debug.apk'
|
||||
assert not artifact.exists(), 'release artifact exists: refusing overwrite'
|
||||
assert hashlib.sha256((root/'artifacts/lan-voice-v040-arm64-debug.apk').read_bytes()).hexdigest()=='5a6f88cb2f825dbcd5c7b8c1f212b369534bc53c49533e196fb5e9287902e934'
|
||||
assert hashlib.sha256((root/'artifacts/lan-voice-v050-arm64-debug.apk').read_bytes()).hexdigest()=='da47f7a08f63a68fbb6dbe7fb3d803ee58b402de393112a32f92a63ad50c1f33'
|
||||
assert hashlib.sha256(previous.read_bytes()).hexdigest()=='7d089517cde3241d79c971d6260ed8f71af86851e2623fdc66e51fb1583ae77f'
|
||||
shutil.copy2(source,artifact)
|
||||
digest=hashlib.sha256(artifact.read_bytes()).hexdigest()
|
||||
artifact.with_suffix('.apk.sha256').write_text(f'{digest} {artifact.name}\n')
|
||||
@@ -60,7 +62,7 @@ for path in ('artifacts/'+artifact.name, artifact.name):
|
||||
if downloaded==digest: url=base+path;break
|
||||
except Exception: pass
|
||||
assert url is not None, 'APK built, but existing HTTP server did not serve matching bytes'
|
||||
result=dict(version_name='0.5.1',version_code=9,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,download_http_status=200,download_bytes=len(content),signature='apksigner_verified',real_phone_playback='not_tested')
|
||||
result=dict(version_name='0.5.2',version_code=10,apk=str(artifact.relative_to(root)),bytes=artifact.stat().st_size,sha256=digest,url=url,download_http_status=200,download_bytes=len(content),signature='apksigner_verified',same_signing_certificate_as='0.5.1',real_phone_playback='not_tested')
|
||||
(root/'logs/voice-investigation/release-emotion.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print(json.dumps(result,indent=2))
|
||||
PY
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'gateway'))
|
||||
from reply_emotion import REPLY_SCHEMA
|
||||
from reply_emotion import REPLY_SCHEMA, SYSTEM_FRAGMENT
|
||||
|
||||
REMOTE = r'''
|
||||
import asyncio, json, pathlib, ssl, subprocess, time, urllib.request
|
||||
@@ -17,6 +18,7 @@ from llm_provider import LLMProvider
|
||||
from reply_emotion import SYSTEM_FRAGMENT, parse_reply
|
||||
from persona_resolver import resolve_persona
|
||||
root=pathlib.Path('/home/gorios-spark-2/lan-voice')
|
||||
if candidate_prompt is not None: SYSTEM_FRAGMENT=candidate_prompt
|
||||
result={'status':'failed','public_samples':samples,'rows':[],'real_phone_playback':'not_tested'}
|
||||
async def probe():
|
||||
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
|
||||
@@ -33,9 +35,8 @@ async def probe():
|
||||
rules=resolve_persona(root,persona,voice_ids)['rules']
|
||||
if preflight:system='以下角色设定只约束reply字段的口述内容;其中旧有不输出JSON等格式约定不约束本轮外层结构。\n'+rules+'\n\n'+SYSTEM_FRAGMENT
|
||||
else:system='以下角色设定只约束reply字段的可朗读正文。\n'+rules+'\n\n'+SYSTEM_FRAGMENT
|
||||
public=['请简短说一声你好。','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。']
|
||||
async with httpx.AsyncClient(trust_env=False,timeout=30) as client:
|
||||
for index,text in enumerate(public[:samples]):
|
||||
for index,(name,text,expected) in enumerate(cases):
|
||||
url,headers,body=p.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160)
|
||||
if preflight:body['response_format']={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}
|
||||
else:assert body.get('response_format')=={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}, 'schema_not_enabled'
|
||||
@@ -59,9 +60,13 @@ async def probe():
|
||||
elapsed=round((time.perf_counter()-start)*1000,2)
|
||||
parsed=parse_reply(raw,finish_reason=finish)
|
||||
row={'sample':index+1,'http_status':response.status_code,'sse_done':done,'chunks':chunks,'envelope_chars':len(raw),'reply_chars':len(parsed.reply),'emotion':parsed.emotion,'intensity':parsed.intensity,'source':parsed.source,'reason':parsed.reason,'parse_branch':parsed.parse_branch,'finish_reason':finish,'usage':usage,'max_tokens':160,'first_content_ms':first,'complete_ms':elapsed,'structured_wait_ms':round(elapsed-(first or elapsed),2)}
|
||||
row['case']=name
|
||||
if expected is not None:row.update(expected_emotion=expected,expected_emotion_match=parsed.emotion==expected)
|
||||
result['rows'].append(row)
|
||||
assert done and finish=='stop' and parsed.source=='model' and parsed.parse_branch=='strict_json' and 0<len(parsed.reply)<=160, 'schema_validation_failed'
|
||||
result.update(status='passed',provider='qwen3.8-27b',thinking=False,format_mode='json_schema',persona=persona)
|
||||
if any(row.get('expected_emotion_match') is False for row in result['rows']):result['semantic_status']='mismatch'
|
||||
elif any('expected_emotion_match' in row for row in result['rows']):result['semantic_status']='matched_fixed_cases'
|
||||
try:asyncio.run(probe())
|
||||
except Exception as error:
|
||||
result['error_type']=type(error).__name__
|
||||
@@ -75,12 +80,23 @@ def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--preflight',action='store_true',help='Validate explicit schema before provider implementation is deployed')
|
||||
parser.add_argument('--samples',type=int,choices=(1,2),default=1)
|
||||
parser.add_argument('--emotion-cases',action='store_true',help='Six fixed public semantic cases; records every match/mismatch without resampling')
|
||||
parser.add_argument('--candidate',action='store_true',help='Use workspace candidate prompt in memory before deploying it')
|
||||
args=parser.parse_args()
|
||||
payload='schema='+repr(REPLY_SCHEMA)+'\npreflight='+repr(args.preflight)+'\nsamples='+repr(args.samples)+'\n'+REMOTE
|
||||
result=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=payload.encode(),capture_output=True,timeout=85)
|
||||
cases=[('greeting','请简短说一声你好。',None),('explicit_happy','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。',None)][:args.samples]
|
||||
if args.emotion_cases:
|
||||
cases=[('fact','七乘八等于多少?只给出结果。','neutral'),
|
||||
('congratulations','朋友通过资格考试了,请简短祝贺。','happy'),
|
||||
('sympathy','朋友努力准备的比赛落选了,请简短表示惋惜并安慰。','sad'),
|
||||
('disapproval','有人故意插队还嘲讽排队的人,请用克制口吻表达你对此的不满。','angry'),
|
||||
('definition','客观解释“愤怒”一词的含义,不表达你自己的情绪。','neutral'),
|
||||
('negated_fact','这不是一个悲伤的故事。请只回答一加一等于几。','neutral')]
|
||||
payload='schema='+repr(REPLY_SCHEMA)+'\npreflight='+repr(args.preflight)+'\nsamples='+repr(len(cases))+'\ncases='+repr(cases)+'\ncandidate_prompt='+repr(SYSTEM_FRAGMENT if args.candidate else None)+'\n'+REMOTE
|
||||
result=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=payload.encode(),capture_output=True,timeout=220 if args.emotion_cases else 85)
|
||||
if result.stdout:
|
||||
data=json.loads(result.stdout)
|
||||
target=ROOT/'logs/structure-output-fix'/('schema-preflight.json' if args.preflight else 'schema-deployed.json')
|
||||
if args.candidate:data['candidate_source_sha256']=hashlib.sha256((ROOT/'gateway/reply_emotion.py').read_bytes()).hexdigest()
|
||||
target=ROOT/'logs/emotion-052'/('semantic-candidate.json' if args.candidate else 'semantic-deployed.json') if args.emotion_cases else ROOT/'logs/structure-output-fix'/('schema-preflight.json' if args.preflight else 'schema-deployed.json')
|
||||
target.parent.mkdir(parents=True,exist_ok=True)
|
||||
target.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
|
||||
print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||
|
||||
@@ -100,7 +100,7 @@ async def probe():
|
||||
if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count')
|
||||
if kind=='metrics':
|
||||
values=event.get('values',{})
|
||||
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens','llm_structured_output')}
|
||||
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','llm_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens','llm_structured_output','face_context')}
|
||||
summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])]
|
||||
if kind=='error': raise RuntimeError('gateway_backend_error')
|
||||
if kind=='tts' and event.get('state')=='stop':
|
||||
@@ -120,6 +120,7 @@ async def probe():
|
||||
summary['invalid_face_control_survived']=True
|
||||
assert summary['emotion_count']==1 and summary.get('tts_input_matches_body') and summary.get('tts_requests')==1
|
||||
assert summary['structured_model_output'], 'live structured reply fell back'
|
||||
assert summary['backend_metrics'].get('llm_request_count')==1, 'LLM request count differs'
|
||||
assert summary['pcm_peak']>327, 'no voiced PCM amplitude'
|
||||
summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2)
|
||||
summary['status']='passed'
|
||||
|
||||
Reference in New Issue
Block a user