Wire legal idle variants and validate dance media offline
This commit is contained in:
@@ -25,7 +25,8 @@ interface MusicMediaPort {
|
|||||||
class ConversationMediaDriver(private val index: EmotionActionIndex,
|
class ConversationMediaDriver(private val index: EmotionActionIndex,
|
||||||
private val create: (Int)->CompositeMediaPort,private val music: MusicMediaPort,
|
private val create: (Int)->CompositeMediaPort,private val music: MusicMediaPort,
|
||||||
private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> },
|
private val reveal: (Int?)->Unit,private val report: (String,BodyFrameKey?)->Unit = { _,_-> },
|
||||||
private val allowSilentEdges: Boolean=false) : ActionPlayer {
|
private val allowSilentEdges: Boolean=false,
|
||||||
|
private val chooseIdle: (Int)->Int = { kotlin.random.Random.nextInt(it) }) : ActionPlayer {
|
||||||
private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack,
|
private data class Slot(val number: Int,val port: CompositeMediaPort,val pack: ContinuousAvatarPack,
|
||||||
val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false)
|
val entry: Int,val packageId: String?,var key: BodyFrameKey?=null,var live: Boolean=true,var closedMouth: Boolean=false)
|
||||||
private val slots=mutableListOf<Slot>()
|
private val slots=mutableListOf<Slot>()
|
||||||
@@ -35,6 +36,8 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
private var bridge: Slot?=null
|
private var bridge: Slot?=null
|
||||||
private var edge: ConversationEdge?=null
|
private var edge: ConversationEdge?=null
|
||||||
private var selectedId=index.fallbackId
|
private var selectedId=index.fallbackId
|
||||||
|
private var idleTarget: String?=null
|
||||||
|
private var lastIdle: String?=null
|
||||||
var selection: RoleVisualSelection?=null;private set
|
var selection: RoleVisualSelection?=null;private set
|
||||||
val currentPackageId: String? get() = if(inBridge || actionStarted) null else visible?.packageId
|
val currentPackageId: String? get() = if(inBridge || actionStarted) null else visible?.packageId
|
||||||
val visualStatus: String get() = when {
|
val visualStatus: String get() = when {
|
||||||
@@ -42,6 +45,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
actionStarted -> "action_mouth_disabled"
|
actionStarted -> "action_mouth_disabled"
|
||||||
inBridge -> "bridge_own_mouth"
|
inBridge -> "bridge_own_mouth"
|
||||||
edge!=null || revealing!=null -> "queued_emotion_safe_exit_or_prepared_surface"
|
edge!=null || revealing!=null -> "queued_emotion_safe_exit_or_prepared_surface"
|
||||||
|
idleTarget==visible?.packageId && idleTarget!=null -> "neutral_idle_variant"
|
||||||
visible?.packageId!=selectedId -> "queued_emotion_path_or_layer_unavailable"
|
visible?.packageId!=selectedId -> "queued_emotion_path_or_layer_unavailable"
|
||||||
else -> selection?.reason ?: "no_model_expression"
|
else -> selection?.reason ?: "no_model_expression"
|
||||||
}
|
}
|
||||||
@@ -63,7 +67,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
private val releaseWaiters=mutableListOf<()->Unit>()
|
private val releaseWaiters=mutableListOf<()->Unit>()
|
||||||
fun beginTurn(id: Long?) {
|
fun beginTurn(id: Long?) {
|
||||||
if(id==turn) return
|
if(id==turn) return
|
||||||
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null
|
turn=id;seq=-1;generation++;revision=0;talk=false;selection=null;idleTarget=null
|
||||||
selectedId=visible?.packageId ?: index.fallbackId
|
selectedId=visible?.packageId ?: index.fallbackId
|
||||||
if(!inBridge && revealing==null) discardRoute()
|
if(!inBridge && revealing==null) discardRoute()
|
||||||
applyMouth()
|
applyMouth()
|
||||||
@@ -90,8 +94,10 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
seq=reply.sequence
|
seq=reply.sequence
|
||||||
selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId)
|
selection=RoleVisualSelector.select(reply.emotion,reply.intensity,index.visuals,index.fallbackId)
|
||||||
selectedId=checkNotNull(selection).packageId
|
selectedId=checkNotNull(selection).packageId
|
||||||
|
idleTarget=null
|
||||||
}
|
}
|
||||||
talk=talking && reply?.turnId==turn
|
talk=talking && reply?.turnId==turn
|
||||||
|
if(talk) idleTarget=null
|
||||||
applyMouth()
|
applyMouth()
|
||||||
if(active && !inBridge && !actionStarted) plan()
|
if(active && !inBridge && !actionStarted) plan()
|
||||||
}
|
}
|
||||||
@@ -116,7 +122,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
slot.key=key;slot.closedMouth=closedMouth
|
slot.key=key;slot.closedMouth=closedMouth
|
||||||
if(slot===visible) {
|
if(slot===visible) {
|
||||||
reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key)
|
reveal(slot.number);report(if(inBridge) "bridge" else "body_${slot.packageId}",key)
|
||||||
if(!inBridge) { applyMouth();plan() }
|
if(!inBridge) { chooseIdleAtLoopEnd(slot,key,previous);applyMouth();plan() }
|
||||||
if(slot===visible && !actionStarted && !holdExit(slot)) slot.port.advance()
|
if(slot===visible && !actionStarted && !holdExit(slot)) slot.port.advance()
|
||||||
} else if(returning) restoreAction(slot) else plan()
|
} else if(returning) restoreAction(slot) else plan()
|
||||||
}
|
}
|
||||||
@@ -130,11 +136,32 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
private fun holdExit(slot: Slot): Boolean = !inBridge && (
|
private fun holdExit(slot: Slot): Boolean = !inBridge && (
|
||||||
slot.key?.index==edge?.fromFrame && edge!=null ||
|
slot.key?.index==edge?.fromFrame && edge!=null ||
|
||||||
action?.media?.let { slot.packageId==it.sourcePackage && slot.key?.index==it.sourceFrame }==true)
|
action?.media?.let { slot.packageId==it.sourcePackage && slot.key?.index==it.sourceFrame }==true)
|
||||||
|
/** Only a completed neutral cycle may schedule variation. Speech/emotion/action
|
||||||
|
* remains authoritative, and every departure still goes through plan's own-mouth edge. */
|
||||||
|
private fun chooseIdleAtLoopEnd(slot: Slot,key: BodyFrameKey,previous: BodyFrameKey?) {
|
||||||
|
if(talk || action!=null || edge!=null || revealing!=null || target!=null || closing!=0 ||
|
||||||
|
key==previous || key.index!=slot.pack.body.frameCount-1 ||
|
||||||
|
selection?.visualEmotion?.let { it!=com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }==true ||
|
||||||
|
index.visuals.none { it.id==slot.packageId && it.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL }) return
|
||||||
|
if(idleTarget!=null && slot.packageId==idleTarget && slot.packageId!=index.fallbackId) {
|
||||||
|
idleTarget=index.fallbackId;report("idle_variant_return_queued",key);return
|
||||||
|
}
|
||||||
|
if(slot.packageId!=index.fallbackId || selectedId!=index.fallbackId) return
|
||||||
|
val candidates=index.visuals.filter { p->p.emotion==com.gorios.lanvoice.dialogue.RoleEmotion.NEUTRAL &&
|
||||||
|
p.id!=index.fallbackId && p.approvedEdges &&
|
||||||
|
index.edges.any { it.from==index.fallbackId && it.to==p.id && it.mouthRuntime!=null } &&
|
||||||
|
index.edges.any { it.from==p.id && it.to==index.fallbackId && it.mouthRuntime!=null }
|
||||||
|
}.map { it.id }
|
||||||
|
val fresh=candidates.filter { it!=lastIdle }.ifEmpty { candidates }
|
||||||
|
if(fresh.isEmpty()) return
|
||||||
|
val picked=chooseIdle(fresh.size);check(picked in fresh.indices)
|
||||||
|
idleTarget=fresh[picked];lastIdle=idleTarget;report("idle_variant_queued",key)
|
||||||
|
}
|
||||||
private fun plan() {
|
private fun plan() {
|
||||||
val source=visible ?: return
|
val source=visible ?: return
|
||||||
val key=source.key ?: return
|
val key=source.key ?: return
|
||||||
if(inBridge || revealing!=null || !active || returning || actionStarted) return
|
if(inBridge || revealing!=null || !active || returning || actionStarted) return
|
||||||
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else selectedId
|
val wanted=if(action!=null) checkNotNull(action?.media).sourcePackage else idleTarget ?: selectedId
|
||||||
var reviewedLoop: ConversationEdge?=null
|
var reviewedLoop: ConversationEdge?=null
|
||||||
if(source.packageId==wanted) {
|
if(source.packageId==wanted) {
|
||||||
if(edge!=null && edge?.from!=edge?.to) { discardRoute();return }
|
if(edge!=null && edge?.from!=edge?.to) { discardRoute();return }
|
||||||
@@ -204,7 +231,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) {
|
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) {
|
||||||
val media=asset.media
|
val media=asset.media
|
||||||
if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return }
|
if(!active || action!=null || media==null || index.actionPack?.assets?.contains(asset)!=true) { failed();return }
|
||||||
action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;talk=false;applyMouth()
|
action=asset;actionFinished=finished;actionFailed=failed;musicReady=false;talk=false;idleTarget=null;applyMouth()
|
||||||
val epoch=++musicEpoch
|
val epoch=++musicEpoch
|
||||||
music.prepare(media,{ if(active && epoch==musicEpoch && action==asset) { musicReady=true;plan() } },
|
music.prepare(media,{ if(active && epoch==musicEpoch && action==asset) { musicReady=true;plan() } },
|
||||||
{ if(active && epoch==musicEpoch && actionStarted) reveal(3) },{
|
{ if(active && epoch==musicEpoch && actionStarted) reveal(3) },{
|
||||||
@@ -232,7 +259,7 @@ class ConversationMediaDriver(private val index: EmotionActionIndex,
|
|||||||
completed?.invoke(ActionEnd(true,true,true))
|
completed?.invoke(ActionEnd(true,true,true))
|
||||||
}
|
}
|
||||||
override fun stop(released: ()->Unit) {
|
override fun stop(released: ()->Unit) {
|
||||||
musicEpoch++;action=null;actionStarted=false;returning=false;musicReady=false
|
musicEpoch++;action=null;actionStarted=false;returning=false;musicReady=false;idleTarget=null
|
||||||
actionFinished=null;actionFailed=null;talk=false;generation++;revision=0
|
actionFinished=null;actionFailed=null;talk=false;generation++;revision=0
|
||||||
reveal(null);releaseWaiters.add(released)
|
reveal(null);releaseWaiters.add(released)
|
||||||
active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false
|
active=false;visible=null;revealing=null;target=null;bridge=null;edge=null;inBridge=false
|
||||||
|
|||||||
@@ -361,3 +361,32 @@ Gateway0.8/Qwen/TTS/provider parameters are unchanged; no deploy/restart/model
|
|||||||
request, no paid generation/probe. This is a partial-expression candidate,
|
request, no paid generation/probe. This is a partial-expression candidate,
|
||||||
not the idle/dance delivery. P4b/P5 remain under the independent asset owner.
|
not the idle/dance delivery. P4b/P5 remain under the independent asset owner.
|
||||||
Evidence: `logs/action-emotion/code17/pinned-release/` (ignored, not Git).
|
Evidence: `logs/action-emotion/code17/pinned-release/` (ignored, not Git).
|
||||||
|
|
||||||
|
### Idle/dance source preflight (2026-10-13; code17 APK unchanged)
|
||||||
|
|
||||||
|
Clean remote-matched baseline `04d73b4361a2de503534eee036d2157914e64fe6`.
|
||||||
|
Actual ConversationMediaDriver now schedules neutral variants only after a full
|
||||||
|
neutral cycle, through own-mouth entry/return edges and fallback, avoiding consecutive
|
||||||
|
variant repeats. TALK/new expression/action cancels idle selection; retained happy/sad
|
||||||
|
does not become neutral at speech end. Current code17 contains no new idle rows and
|
||||||
|
its published APK/pin remain unchanged. No in-production P4b/P5 output was touched.
|
||||||
|
|
||||||
|
Read-only full-index checking now accepts two dance rows and measures actual video
|
||||||
|
N/PTS/fps/duration, presented AAC end excluding encoder padding, finite nonempty PCM,
|
||||||
|
RMS/peak and file inventory before production Kotlin admission. Synthetic color+sine
|
||||||
|
fixtures prove path/mismatch rejection, not real dance/music quality. Dance import/
|
||||||
|
publication remains explicitly separate from this check and requires gateway capability
|
||||||
|
admission plus a new exact Pi pin; no live capability was enabled by checking fixtures.
|
||||||
|
|
||||||
|
Fresh9 JVM/UI entry points,22 packaging checks,71 media cases (56 actual view callbacks
|
||||||
|
plus15 boundary cases),289 bridge assertions and19 idle driver assertions passed.
|
||||||
|
Gateway archive98:97 pass/1 existing excluded Silero artifact skip. Application and
|
||||||
|
instrumentation Kotlin compilation passed; the first compile omitted the action-candidate
|
||||||
|
flag and failed configuration, then the corrected command passed. No new APK assembled.
|
||||||
|
Original e73f index passed complete decode/hash/cache and actual production-parser gate
|
||||||
|
again at5,804,040 RGBA bytes.200 unchanged GLES goldens retained with shader/harness
|
||||||
|
hashes matched. Evidence: `logs/action-emotion/idle-dance-preflight-01/`.
|
||||||
|
|
||||||
|
Paid calls/cost0; no model probes, gateway deployment/restart/provider/TTS change.
|
||||||
|
Physical device, real music listening/full-speed dance review and naturalness remain
|
||||||
|
not_run/not_certified. Handoff: **IDLE_DANCE_SOURCE_PREFLIGHT_READY_FOR_NEW_INDEX_SHA**.
|
||||||
|
|||||||
@@ -152,3 +152,22 @@ runtime RGBA counts sum under32MB; each runtime remains bounded8MB/N720.
|
|||||||
The new p4a-combined-02 index, all runtime references and files inventory require a
|
The new p4a-combined-02 index, all runtime references and files inventory require a
|
||||||
new exact Pi pin; old000d04ea…5008 is only the old silent-bridge candidate pin.
|
new exact Pi pin; old000d04ea…5008 is only the old silent-bridge candidate pin.
|
||||||
Offline processing does not require new AI/body generation or paid calls.
|
Offline processing does not require new AI/body generation or paid calls.
|
||||||
|
|
||||||
|
P4b/P5 integration preflight (2026-10-13; no new asset schema):
|
||||||
|
- Idle variants are additional neutral/visualIntensity0 conversationPackages rows,
|
||||||
|
each with own runtimeManifest, loopEdge and real fallback↔variant edges. Live
|
||||||
|
variant entry/return bridges need their own mouthRuntimeManifest too. Idle
|
||||||
|
selection occurs after a completed neutral cycle, returns through fallback and
|
||||||
|
avoids consecutive repeats where two variants exist. Active TALK, queued model
|
||||||
|
expression and action have priority; happy/sad expression is retained when speech
|
||||||
|
ends. No random phase cuts, fixed TTS delay or new model tag is introduced.
|
||||||
|
- The read-only package-avatar-emotion.py gate now accepts actions:[] or the two
|
||||||
|
dance rows. It checks actual video N/PTS/fps/duration, exactly video+AAC without
|
||||||
|
attached cover, presented audioEndUs (excluding AAC encoder padding), full decode,
|
||||||
|
nonempty finite PCM/RMS/peak and inventory/body/patch bytes before Kotlin admission.
|
||||||
|
Reports keep dance_available:false until independent exact pin/capability release.
|
||||||
|
Dance import/publication is separately blocked pending gateway capability admission;
|
||||||
|
read-only checking is available now without activating or rewriting owner assets.
|
||||||
|
- All source/target frames bind the silent delivered body SHA/PTS, not an immutable
|
||||||
|
master with audio/cover. Count241 and approximate10s are not substitutes for
|
||||||
|
independently measured video duration, final video PTS and presented audio end.
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Read-only partial v2 emotion gate by default; import/publish needs an external Pi pin."""
|
"""Read-only v2 conversation/dance gate; partial-emotion import/publish needs an external Pi pin."""
|
||||||
from pathlib import Path, PurePosixPath
|
from pathlib import Path, PurePosixPath
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from fractions import Fraction
|
from fractions import Fraction
|
||||||
import argparse
|
import argparse
|
||||||
|
import array
|
||||||
import hashlib
|
import hashlib
|
||||||
import importlib.util
|
import importlib.util
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import math
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -71,12 +73,52 @@ def probe_clip(path):
|
|||||||
return measured
|
return measured
|
||||||
|
|
||||||
|
|
||||||
|
def probe_music_clip(path):
|
||||||
|
"""Bounded offline decode, including presented AAC samples. No listening claim."""
|
||||||
|
result=subprocess.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error',
|
||||||
|
'-show_streams','-show_frames','-of','json',str(path)],capture_output=True,check=True,timeout=60)
|
||||||
|
data=json.loads(result.stdout);streams=data['streams']
|
||||||
|
require(len(streams)==2 and sorted(s['codec_type'] for s in streams)==['audio','video'],
|
||||||
|
'dance requires exactly video+audio, no attached cover')
|
||||||
|
v=next(s for s in streams if s['codec_type']=='video');a=next(s for s in streams if s['codec_type']=='audio')
|
||||||
|
require(v['codec_name']=='h264' and (v['width'],v['height'])==(480,848) and
|
||||||
|
not v.get('disposition',{}).get('attached_pic',0),'dance video codec/shape/cover')
|
||||||
|
require(a['codec_name']=='aac' and a['channels'] in (1,2) and 8000<=int(a['sample_rate'])<=96000,'dance AAC format')
|
||||||
|
us=lambda value:int((Decimal(value)*1_000_000).to_integral_value())
|
||||||
|
duration=us(v['duration']);require(1_000_000<=duration<=90_000_000,'dance duration bound')
|
||||||
|
frames=[f for f in data['frames'] if f['media_type']=='video']
|
||||||
|
require(1<=len(frames)<=5400,'dance decoded frame bound')
|
||||||
|
audio=[f for f in data['frames'] if f['media_type']=='audio']
|
||||||
|
require(audio and us(a.get('start_time','0'))>=0,'dance decoded audio missing/start')
|
||||||
|
decoded_end=max(us(f['best_effort_timestamp_time'])+int(round(int(f['nb_samples'])*1_000_000/int(a['sample_rate']))) for f in audio)
|
||||||
|
# AAC final frames can include encoder padding beyond the MP4 presentation end.
|
||||||
|
audio_end=us(a.get('start_time','0'))+us(a['duration'])
|
||||||
|
require(1<=audio_end<=duration and decoded_end+2>=audio_end,'dance presented audio end')
|
||||||
|
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path),
|
||||||
|
'-map','0:v:0','-f','null','-'],capture_output=True,check=True,timeout=60)
|
||||||
|
pcm=subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path),
|
||||||
|
'-map','0:a:0','-af','atrim=end='+str(Decimal(audio_end)/1_000_000),'-ac','2','-ar','48000',
|
||||||
|
'-f','f32le','-'],capture_output=True,check=True,timeout=60).stdout
|
||||||
|
require(0<len(pcm)<=90*48000*2*4 and len(pcm)%8==0,'dance PCM byte bound')
|
||||||
|
samples=array.array('f');samples.frombytes(pcm)
|
||||||
|
if sys.byteorder!='little': samples.byteswap()
|
||||||
|
require(all(math.isfinite(x) for x in samples),'dance PCM nonfinite')
|
||||||
|
rms=math.sqrt(sum(x*x for x in samples)/len(samples));peak=max(abs(x) for x in samples)
|
||||||
|
require(rms>0.00001 and peak<=1.001,'dance silent/out-of-range audio')
|
||||||
|
return {'ptsUs':[us(f['best_effort_timestamp_time']) for f in frames],
|
||||||
|
'durationUs':duration,'fps':Fraction(v['r_frame_rate']),'audioEndUs':audio_end,
|
||||||
|
'decodedAudioEndUs':decoded_end,'pcmFrames':len(samples)//2,'audioRms':rms,'audioPeak':peak,
|
||||||
|
'nearFullScaleSamples':sum(abs(x)>=0.999 for x in samples),'humanListening':'not_run'}
|
||||||
|
|
||||||
|
|
||||||
def check_bundle(manifest,expected,output):
|
def check_bundle(manifest,expected,output):
|
||||||
manifest=manifest.resolve(strict=True);root=manifest.parent
|
manifest=manifest.resolve(strict=True);root=manifest.parent
|
||||||
require(re.fullmatch('[0-9a-f]{64}',expected) and file_sha(manifest)==expected,'candidate index drift')
|
require(re.fullmatch('[0-9a-f]{64}',expected) and file_sha(manifest)==expected,'candidate index drift')
|
||||||
index=read_json(manifest)
|
index=read_json(manifest)
|
||||||
require(index['schemaVersion']==2 and index['identityId']=='a01' and index['packId']=='a01-expression-action-v1','index identity/schema')
|
require(index['schemaVersion']==2 and index['identityId']=='a01' and index['packId']=='a01-expression-action-v1','index identity/schema')
|
||||||
require(index['actions']==[],'this partial-emotion packer requires actions:[]; dance needs its separate audio gate')
|
actions=index['actions']
|
||||||
|
require(isinstance(actions,list) and (not actions or len(actions)==2 and
|
||||||
|
{a['id'] for a in actions}=={'asset_01','asset_02'}),'actions require exactly asset_01/asset_02 or []')
|
||||||
rows=index['conversationPackages'];require(1<=len(rows)<=12,'package count')
|
rows=index['conversationPackages'];require(1<=len(rows)<=12,'package count')
|
||||||
files={};measurements={};runtimes=[]
|
files={};measurements={};runtimes=[]
|
||||||
def add(name,digest,bound):
|
def add(name,digest,bound):
|
||||||
@@ -107,6 +149,16 @@ def check_bundle(manifest,expected,output):
|
|||||||
require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'],'decoded clip N mismatch: '+name)
|
require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'],'decoded clip N mismatch: '+name)
|
||||||
require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'decoded clip PTS mismatch: '+name)
|
require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'decoded clip PTS mismatch: '+name)
|
||||||
require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'decoded clip timing mismatch: '+name)
|
require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'decoded clip timing mismatch: '+name)
|
||||||
|
action_measurements=[]
|
||||||
|
for action in actions:
|
||||||
|
clip=action['clip'];name=relative(clip['path']);path=add(name,clip['sha256'],128_000_000)
|
||||||
|
require(clip['hasAudio'] is True,'dance requires actual audio')
|
||||||
|
measured=probe_music_clip(path)
|
||||||
|
require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'], 'dance decoded N mismatch: '+name)
|
||||||
|
require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'dance decoded PTS mismatch: '+name)
|
||||||
|
require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'dance decoded timing mismatch: '+name)
|
||||||
|
require(abs(measured['audioEndUs']-action['audioEndUs'])<=2,'dance audioEndUs mismatch: '+name)
|
||||||
|
action_measurements.append({'id':action['id'],**{k:v for k,v in measured.items() if k!='fps'}})
|
||||||
# Preview inventory is checked too, but only runtime-referenced files enter APK.
|
# Preview inventory is checked too, but only runtime-referenced files enter APK.
|
||||||
declared=index['files']
|
declared=index['files']
|
||||||
if isinstance(declared,dict): declared=[dict(v,path=k) for k,v in declared.items()]
|
if isinstance(declared,dict): declared=[dict(v,path=k) for k,v in declared.items()]
|
||||||
@@ -126,7 +178,8 @@ def check_bundle(manifest,expected,output):
|
|||||||
for name,row in files.items(): require(file_sha(locate(root,name))==row['sha256'],'bundle changed during gate')
|
for name,row in files.items(): require(file_sha(locate(root,name))==row['sha256'],'bundle changed during gate')
|
||||||
report={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':expected,
|
report={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':expected,
|
||||||
'runtime_packages':runtimes,'combined_rgba_bytes':rgba,'referenced_files':len(files),'preview_files_not_packaged':len(table.keys()-files.keys()),
|
'runtime_packages':runtimes,'combined_rgba_bytes':rgba,'referenced_files':len(files),'preview_files_not_packaged':len(table.keys()-files.keys()),
|
||||||
'edge_count':len(index['edges']),'action_count':0,'dance_available':False,'production_kotlin_index':'passed',
|
'edge_count':len(index['edges']),'action_count':len(actions),'dance_available':False,
|
||||||
|
'candidate_dance_validated':bool(actions),'action_measurements':action_measurements,'production_kotlin_index':'passed',
|
||||||
'naturalness':'not_certified','real_device':'not_run','files':files}
|
'naturalness':'not_certified','real_device':'not_run','files':files}
|
||||||
(output/'bundle-gate.json').write_text(json.dumps(report,indent=2)+'\n')
|
(output/'bundle-gate.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||||
return report
|
return report
|
||||||
@@ -271,6 +324,8 @@ def main():
|
|||||||
args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
|
args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
|
||||||
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
|
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
|
||||||
if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required')
|
if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required')
|
||||||
|
if args.import_only or args.publish:
|
||||||
|
require(read_json(manifest)['actions']==[],'dance import/publication requires separately reviewed gateway capability admission; read-only gate supported')
|
||||||
output.mkdir(parents=True)
|
output.mkdir(parents=True)
|
||||||
report=check_bundle(manifest,args.sha256,output)
|
report=check_bundle(manifest,args.sha256,output)
|
||||||
if args.import_only or args.publish:
|
if args.import_only or args.publish:
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ fun main() {
|
|||||||
conversationPackageCheck()
|
conversationPackageCheck()
|
||||||
actualMediaViewCheck()
|
actualMediaViewCheck()
|
||||||
mediaBoundaryCheck()
|
mediaBoundaryCheck()
|
||||||
|
idleVariantCheck()
|
||||||
checkContinuous()
|
checkContinuous()
|
||||||
checkEngineering()
|
checkEngineering()
|
||||||
checkSafeDriver()
|
checkSafeDriver()
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import com.gorios.lanvoice.avatar.*
|
||||||
|
import com.gorios.lanvoice.dialogue.RoleEmotion
|
||||||
|
|
||||||
|
/** Actual driver callbacks, synthetic bodies; no naturalness or device claim. */
|
||||||
|
fun idleVariantCheck() {
|
||||||
|
var checks=0
|
||||||
|
class Port: CompositeMediaPort {
|
||||||
|
lateinit var pack: ContinuousAvatarPack
|
||||||
|
lateinit var frame: (BodyFrameKey,Boolean)->Unit
|
||||||
|
lateinit var ended: ()->Unit
|
||||||
|
var talking=false;var closed=false;var loop=false
|
||||||
|
override fun prepare(pack: ContinuousAvatarPack,entryFrame: Int,mouth: Boolean,loop: Boolean,
|
||||||
|
frame: (BodyFrameKey,Boolean)->Unit,ended: ()->Unit,failed: ()->Unit) {
|
||||||
|
this.pack=pack;this.frame=frame;this.ended=ended;this.loop=loop
|
||||||
|
}
|
||||||
|
override fun advance() {}
|
||||||
|
override fun mouth(talk: Boolean,generation: Long,revision: Long) { talking=talk }
|
||||||
|
override fun close(released: ()->Unit) { closed=true;released() }
|
||||||
|
fun emit(i: Int,ordinal: Long=0) { frame(BodyFrameKey(i,ordinal,pack.body.ptsUs[i]),!talking) }
|
||||||
|
}
|
||||||
|
val base=mediaFixtureIndex()
|
||||||
|
val index=base.copy(actionPack=null,visuals=base.visuals.map {
|
||||||
|
if(it.id=="neutral") it else it.copy(emotion=RoleEmotion.NEUTRAL)
|
||||||
|
})
|
||||||
|
val music=object: MusicMediaPort {
|
||||||
|
override fun prepare(media: ActionMedia,ready: ()->Unit,firstFrame: ()->Unit,ended: ()->Unit,failed: ()->Unit) { error("No music") }
|
||||||
|
override fun start() { error("No music") }
|
||||||
|
override fun close(released: ()->Unit) { released() }
|
||||||
|
}
|
||||||
|
val ports=mutableListOf<Port>();val trace=mutableListOf<String>()
|
||||||
|
val driver=ConversationMediaDriver(index,{ Port().also(ports::add) },music,{}, { phase,_->trace.add(phase) },chooseIdle={0})
|
||||||
|
driver.beginTurn(7);driver.start();val fallback=ports.single()
|
||||||
|
(0..95).forEach { fallback.emit(it) }
|
||||||
|
check(ports.size==1);checks++ // No arbitrary phase departure.
|
||||||
|
fallback.emit(96);check(ports.size==3 && trace.contains("idle_variant_queued"));checks++
|
||||||
|
fun bridgeTo(target: Port,bridge: Port) {
|
||||||
|
target.emit(0);bridge.emit(0)
|
||||||
|
check(trace.last()=="bridge" && !bridge.loop);checks++
|
||||||
|
(1 until bridge.pack.body.frameCount).forEach { bridge.emit(it) };bridge.ended()
|
||||||
|
check(bridge.closed && driver.currentPackageId!=null);checks++
|
||||||
|
}
|
||||||
|
val idle1=ports[1];bridgeTo(idle1,ports[2])
|
||||||
|
check(driver.currentPackageId=="happy" && driver.visualStatus=="neutral_idle_variant");checks++
|
||||||
|
(1 until idle1.pack.body.frameCount).forEach { idle1.emit(it) }
|
||||||
|
check(trace.contains("idle_variant_return_queued") && ports.size==5);checks++
|
||||||
|
val returned=ports[3];bridgeTo(returned,ports[4])
|
||||||
|
(1..96).forEach { returned.emit(it) }
|
||||||
|
val idle2=ports[5];bridgeTo(idle2,ports[6])
|
||||||
|
check(driver.currentPackageId=="sad");checks++ // Pick0 still excludes previous idle1.
|
||||||
|
driver.intent(mediaReply(RoleEmotion.NEUTRAL),true)
|
||||||
|
check(idle2.talking && ports.size==9);checks++ // Audio continues on current own body while returning.
|
||||||
|
(1 until idle2.pack.body.frameCount).forEach { idle2.emit(it) }
|
||||||
|
val speakingFallback=ports[7];bridgeTo(speakingFallback,ports[8])
|
||||||
|
check(speakingFallback.talking);checks++
|
||||||
|
(1..96).forEach { speakingFallback.emit(it) }
|
||||||
|
check(ports.size==9);checks++ // No variation during active TALK.
|
||||||
|
driver.stop {};val count=trace.size
|
||||||
|
idle2.emit(0);ports[8].ended();check(trace.size==count && ports.all { it.closed });checks++
|
||||||
|
|
||||||
|
// Missing bridge mouth prevents idle activation even with valid own body layers.
|
||||||
|
val noMouth=index.copy(edges=index.edges.map { if(it.nativeLoop) it else it.copy(mouthRuntime=null) })
|
||||||
|
val guarded=mutableListOf<Port>()
|
||||||
|
val other=ConversationMediaDriver(noMouth,{ Port().also(guarded::add) },music,{},chooseIdle={0})
|
||||||
|
other.beginTurn(7);other.start();(0..96).forEach { guarded[0].emit(it) }
|
||||||
|
check(guarded.size==1);checks++;other.stop {}
|
||||||
|
// A retained happy/sad expression must not turn neutral when speech ends.
|
||||||
|
val expressive=mutableListOf<Port>()
|
||||||
|
val retained=ConversationMediaDriver(base,{ Port().also(expressive::add) },music,{},chooseIdle={0})
|
||||||
|
retained.beginTurn(7);retained.start();retained.intent(mediaReply(RoleEmotion.HAPPY),false)
|
||||||
|
(0..96).forEach { expressive[0].emit(it) };expressive[1].emit(0);expressive[2].emit(0)
|
||||||
|
expressive[2].emit(1);expressive[2].emit(2);expressive[2].ended()
|
||||||
|
(1..48).forEach { expressive[1].emit(it) }
|
||||||
|
check(retained.currentPackageId=="happy" && expressive.size==3);checks++;retained.stop {}
|
||||||
|
println("PASS: $checks idle variant driver assertions: complete cycle/legal own-mouth bridges, different N/fps, no consecutive repeat, TALK priority, release/late callbacks, expression retention; fixtures only")
|
||||||
|
}
|
||||||
@@ -138,6 +138,25 @@ fun actualMediaViewCheck() {
|
|||||||
check(statuses.size==before);cases++
|
check(statuses.size==before);cases++
|
||||||
actionView.dispose();TestScheduler.advanceBy(100)
|
actionView.dispose();TestScheduler.advanceBy(100)
|
||||||
}
|
}
|
||||||
|
// New idle rows use the actual view/renderer/codec path and reviewed graph.
|
||||||
|
reset()
|
||||||
|
val idleIndex=mediaFixtureIndex().let { it.copy(actionPack=null,visuals=it.visuals.map { p->p.copy(emotion=RoleEmotion.NEUTRAL) }) }
|
||||||
|
val (idleView,idleBinding,idleTrace)=rig(idleIndex)
|
||||||
|
TestScheduler.advanceBy(3000)
|
||||||
|
check(idleTrace.all { it.actual=="body_neutral" });cases++
|
||||||
|
TestScheduler.until { idleBinding.currentPackageId in setOf("happy","sad") }
|
||||||
|
val firstIdle=idleBinding.currentPackageId
|
||||||
|
check(idleTrace.any { it.actual=="bridge" } && idleBinding.visualStatus=="neutral_idle_variant");cases++
|
||||||
|
TestScheduler.until { idleBinding.currentPackageId=="neutral" }
|
||||||
|
TestScheduler.until { idleBinding.currentPackageId in setOf("happy","sad") }
|
||||||
|
check(idleBinding.currentPackageId!=firstIdle && idleTrace.none { it.actual=="media_failed" });cases++
|
||||||
|
idleBinding.intent(mediaReply(RoleEmotion.NEUTRAL),true)
|
||||||
|
TestScheduler.until { idleBinding.currentPackageId=="neutral" }
|
||||||
|
val speechStart=idleTrace.size;TestScheduler.advanceBy(9000)
|
||||||
|
check(idleTrace.drop(speechStart).all { it.actual=="body_neutral" });cases++
|
||||||
|
val beforeDispose=idleTrace.size;idleView.dispose();TestScheduler.advanceBy(1000)
|
||||||
|
check(idleTrace.size==beforeDispose && driverField.get(idleView)==null && CodecFixture.releases>=7);cases++
|
||||||
|
|
||||||
// Real renderer path over a25-frame own-mouth bridge, no loop or endpoint patches.
|
// Real renderer path over a25-frame own-mouth bridge, no loop or endpoint patches.
|
||||||
reset()
|
reset()
|
||||||
val ownBridge=dynamicPack(25,24,"f".repeat(64)).copy(root="bridge25/")
|
val ownBridge=dynamicPack(25,24,"f".repeat(64)).copy(root="bridge25/")
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ class PackageTests(unittest.TestCase):
|
|||||||
'bytes':(cls.source/'neutral'/name).stat().st_size} for name in names],
|
'bytes':(cls.source/'neutral'/name).stat().st_size} for name in names],
|
||||||
'fixtureNotice':'Synthetic index declaration, ${noInterpolation}, not Pi review'}
|
'fixtureNotice':'Synthetic index declaration, ${noInterpolation}, not Pi review'}
|
||||||
cls.manifest=cls.source/'manifest.json'
|
cls.manifest=cls.source/'manifest.json'
|
||||||
|
cls.music=cls.source/'synthetic-music.mp4'
|
||||||
|
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-f','lavfi','-i',
|
||||||
|
'color=c=gray:s=480x848:r=24:d=1','-f','lavfi','-i','sine=frequency=440:sample_rate=48000:duration=1',
|
||||||
|
'-c:v','libx264','-threads','1','-pix_fmt','yuv420p','-c:a','aac','-ac','2','-t','1',str(cls.music)],check=True)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def tearDownClass(cls): cls.temp.cleanup()
|
def tearDownClass(cls): cls.temp.cleanup()
|
||||||
@@ -69,9 +73,52 @@ class PackageTests(unittest.TestCase):
|
|||||||
bad=copy.deepcopy(self.index);bad['files']=bad['files'][1:]
|
bad=copy.deepcopy(self.index);bad['files']=bad['files'][1:]
|
||||||
with self.assertRaisesRegex(ValueError,'inventory missing'): self.gate(bad,'inventory-gate')
|
with self.assertRaisesRegex(ValueError,'inventory missing'): self.gate(bad,'inventory-gate')
|
||||||
|
|
||||||
def test_no_dance_in_partial_packer(self):
|
def test_incomplete_dance_set_rejected(self):
|
||||||
bad=copy.deepcopy(self.index);bad['actions']=[{'id':'asset_01'}]
|
bad=copy.deepcopy(self.index);bad['actions']=[{'id':'asset_01'}]
|
||||||
with self.assertRaisesRegex(ValueError,'requires actions'): self.gate(bad,'action-gate')
|
with self.assertRaisesRegex(ValueError,'actions require exactly'): self.gate(bad,'action-gate')
|
||||||
|
|
||||||
|
def dance_index(self):
|
||||||
|
index=copy.deepcopy(self.index);measured=pack.probe_music_clip(self.music)
|
||||||
|
clip={'path':self.music.name,'sha256':pack.file_sha(self.music),'width':480,'height':848,
|
||||||
|
'hasAudio':True,'frameCount':len(measured['ptsUs']),'ptsUs':measured['ptsUs'],
|
||||||
|
'durationUs':measured['durationUs'],'fpsNumerator':measured['fps'].numerator,'fpsDenominator':measured['fps'].denominator}
|
||||||
|
index['actions']=[{'id':name,'kind':'dance','mouthAllowed':False,'disallowTALK':True,
|
||||||
|
'entryAnchor':'A','returnAnchor':'A','sourcePackageId':'neutral','returnPackageId':'neutral',
|
||||||
|
'sourceFrame':96,'sourcePtsUs':4_000_000,'returnFrame':0,'returnPtsUs':0,
|
||||||
|
'audioEndUs':measured['audioEndUs'],'clip':clip,'reviewEvidence':'synthetic color+sine; no dance/naturalness claim'}
|
||||||
|
for name in ('asset_01','asset_02')]
|
||||||
|
index['files'].append({'path':self.music.name,'sha256':clip['sha256'],'bytes':self.music.stat().st_size})
|
||||||
|
return index
|
||||||
|
|
||||||
|
def test_music_pcm_and_full_index_readonly(self):
|
||||||
|
result=self.gate(self.dance_index(),'music-full-gate')
|
||||||
|
self.assertEqual(result['action_count'],2);self.assertTrue(result['candidate_dance_validated'])
|
||||||
|
self.assertFalse(result['dance_available'])
|
||||||
|
for measured in result['action_measurements']:
|
||||||
|
self.assertEqual(len(measured['ptsUs']),24)
|
||||||
|
self.assertEqual(measured['audioEndUs'],1_000_000)
|
||||||
|
self.assertGreater(measured['pcmFrames'],47000);self.assertGreater(measured['audioRms'],0)
|
||||||
|
self.assertLess(measured['audioPeak'],1);self.assertEqual(measured['humanListening'],'not_run')
|
||||||
|
|
||||||
|
def test_music_actual_audio_end_mismatch(self):
|
||||||
|
bad=self.dance_index();bad['actions'][0]['audioEndUs']-=1000
|
||||||
|
with self.assertRaisesRegex(ValueError,'audioEndUs mismatch'): self.gate(bad,'music-end-gate')
|
||||||
|
|
||||||
|
def test_music_actual_video_pts_mismatch(self):
|
||||||
|
bad=self.dance_index();bad['actions'][0]['clip']['ptsUs'][1]+=4
|
||||||
|
with self.assertRaisesRegex(ValueError,'dance decoded PTS mismatch'): self.gate(bad,'music-pts-gate')
|
||||||
|
|
||||||
|
def test_music_silent_video_rejected(self):
|
||||||
|
with self.assertRaisesRegex(ValueError,'exactly video.audio'):
|
||||||
|
pack.probe_music_clip(self.source/'neutral'/self.runtime['body']['path'])
|
||||||
|
|
||||||
|
def test_dance_not_imported_by_readonly_gate(self):
|
||||||
|
self.manifest.write_text(json.dumps(self.dance_index()));out=self.base/'dance-no-import'
|
||||||
|
digest=pack.file_sha(self.manifest)
|
||||||
|
result=subprocess.run([sys.executable,str(ROOT/'scripts/package-avatar-emotion.py'),
|
||||||
|
'--manifest',str(self.manifest),'--sha256',digest,'--pi-pin',digest,'--output',str(out),'--import-only'],capture_output=True,text=True)
|
||||||
|
self.assertNotEqual(result.returncode,0);self.assertIn('read-only gate supported',result.stderr)
|
||||||
|
self.assertFalse(out.exists())
|
||||||
|
|
||||||
def test_paths(self):
|
def test_paths(self):
|
||||||
for name in ('../x','x/../y','x//y','/x','x/./y','https://host/x','x\\y'):
|
for name in ('../x','x/../y','x//y','/x','x/./y','https://host/x','x\\y'):
|
||||||
|
|||||||
Reference in New Issue
Block a user