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
@@ -37,8 +37,12 @@ object BodyTimeline {
/** This parser admits only coordinator-selected debug runtime data; no production graph. */ /** This parser admits only coordinator-selected debug runtime data; no production graph. */
object ContinuousAvatarManifest { object ContinuousAvatarManifest {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
fun read(root: Map<String,Any?>,sha: String,expectedSha: String,debug: Boolean,pathRoot: String): ContinuousAvatarPack? { fun read(root: Map<String,Any?>,sha: String,expectedSha: String,debug: Boolean,pathRoot: String,
if(!debug || !expectedSha.matches(Regex("[0-9a-f]{64}")) || sha!=expectedSha) return null onReject: ((String)->Unit)? = null): ContinuousAvatarPack? {
if(!debug || !expectedSha.matches(Regex("[0-9a-f]{64}")) || sha!=expectedSha) {
onReject?.invoke("externalPin");return null
}
var field="schemaVersion"
return try { return try {
fun obj(v: Any?)=v as Map<String,Any?> fun obj(v: Any?)=v as Map<String,Any?>
fun integer(v: Any?): Long { val n=v as Number; val l=n.toLong(); require(n.toDouble()==l.toDouble()); return l } fun integer(v: Any?): Long { val n=v as Number; val l=n.toLong(); require(n.toDouble()==l.toDouble()); return l }
@@ -49,7 +53,9 @@ object ContinuousAvatarManifest {
val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04" || dynamic val apertureMode=root["packId"]=="a01-neutral-graph-v1-runtime-04" || dynamic
require(integer(root["schemaVersion"])==(if(dynamic) 2L else 1L) && root["identityId"]=="a01" && require(integer(root["schemaVersion"])==(if(dynamic) 2L else 1L) && root["identityId"]=="a01" &&
(apertureMode || root["packId"]=="a01-neutral-graph-v1-runtime-03")) (apertureMode || root["packId"]=="a01-neutral-graph-v1-runtime-03"))
field="publishApproval/runtimeReady"
require(root["publishApproval"]==false && root["runtimeReady"]==true) require(root["publishApproval"]==false && root["runtimeReady"]==true)
field="body"
val b=obj(root["body"]) val b=obj(root["body"])
val count=smallInt(b["frameCount"]);require(count in 2..BodyTimeline.MAX_TALK_FRAMES) val count=smallInt(b["frameCount"]);require(count in 2..BodyTimeline.MAX_TALK_FRAMES)
val fpsN=smallInt(b["fpsNumerator"]);val fpsD=smallInt(b["fpsDenominator"]) val fpsN=smallInt(b["fpsNumerator"]);val fpsD=smallInt(b["fpsDenominator"])
@@ -62,6 +68,7 @@ object ContinuousAvatarManifest {
require(count==97 && kotlin.math.abs(body.durationUs-4_041_667)<=2 && fpsN==24 && fpsD==1) require(count==97 && kotlin.math.abs(body.durationUs-4_041_667)<=2 && fpsN==24 && fpsD==1)
require(integer(b["frameDurationUsNumerator"])==1_000_000L && integer(b["frameDurationUsDenominator"])==24L) require(integer(b["frameDurationUsNumerator"])==1_000_000L && integer(b["frameDurationUsDenominator"])==24L)
} }
field="patchFormat"
val patchFormat=obj(root["patchFormat"]) val patchFormat=obj(root["patchFormat"])
require(patchFormat["alphaEncoding"]=="straight_unassociated" && patchFormat["format"]=="PNG RGBA 8bit") require(patchFormat["alphaEncoding"]=="straight_unassociated" && patchFormat["format"]=="PNG RGBA 8bit")
if(dynamic) require(hash(patchFormat["bodySha256"])==body.sha256) if(dynamic) require(hash(patchFormat["bodySha256"])==body.sha256)
@@ -69,8 +76,10 @@ object ContinuousAvatarManifest {
require((patchFormat["apertureLevels"] as List<*>).map(::finite)==listOf(0f,.25f,.5f,.75f,1f)) require((patchFormat["apertureLevels"] as List<*>).map(::finite)==listOf(0f,.25f,.5f,.75f,1f))
require(patchFormat["requiresRendererExtension"]==true) require(patchFormat["requiresRendererExtension"]==true)
} }
field="patches"
val rows=root["patches"] as List<Map<String,Any?>>; require(rows.size==count) val rows=root["patches"] as List<Map<String,Any?>>; require(rows.size==count)
val patches=rows.mapIndexed { index,p -> val patches=rows.mapIndexed { index,p ->
field="patches[$index]"
val patch=RegisteredMouthPatch(smallInt(p["frameIndex"]),integer(p["ptsUs"]),p["path"] as String,hash(p["sha256"]), val patch=RegisteredMouthPatch(smallInt(p["frameIndex"]),integer(p["ptsUs"]),p["path"] as String,hash(p["sha256"]),
finite(p["x"]),finite(p["y"]),smallInt(p["width"]),smallInt(p["height"])) finite(p["x"]),finite(p["y"]),smallInt(p["width"]),smallInt(p["height"]))
require(patch.frameIndex==index && if(dynamic) patch.ptsUs==pts[index] else kotlin.math.abs(patch.ptsUs-pts[index])<=2) require(patch.frameIndex==index && if(dynamic) patch.ptsUs==pts[index] else kotlin.math.abs(patch.ptsUs-pts[index])<=2)
@@ -78,7 +87,9 @@ object ContinuousAvatarManifest {
require(patch.width in 1..128 && patch.height in 1..128 && patch.x>=0 && patch.y>=0 && require(patch.width in 1..128 && patch.height in 1..128 && patch.x>=0 && patch.y>=0 &&
patch.x+patch.width<=480 && patch.y+patch.height<=848) patch.x+patch.width<=480 && patch.y+patch.height<=848)
if(apertureMode) { if(apertureMode) {
field="patches[$index].levels"
val levels=(p["levels"] as List<Map<String,Any?>>).also { require(it.size==5) }.mapIndexed { level,row -> val levels=(p["levels"] as List<Map<String,Any?>>).also { require(it.size==5) }.mapIndexed { level,row ->
field="patches[$index].levels[$level]"
require(level in 0..4 && smallInt(row["levelIndex"])==level && finite(row["aperture"])==level/4f) require(level in 0..4 && smallInt(row["levelIndex"])==level && finite(row["aperture"])==level/4f)
MouthPatchLevel(level,level/4f,row["path"] as String,hash(row["sha256"])).also { MouthPatchLevel(level,level/4f,row["path"] as String,hash(row["sha256"])).also {
require(it.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png"))) require(it.path.matches(Regex("patches/[a-zA-Z0-9_.-]+\\.png")))
@@ -91,19 +102,27 @@ object ContinuousAvatarManifest {
patch patch
} }
} }
field="patches.uniquePaths/cacheBytes"
val paths=patches.flatMap { if(apertureMode) it.levels.map { l -> l.path } else listOf(it.path) } val paths=patches.flatMap { if(apertureMode) it.levels.map { l -> l.path } else listOf(it.path) }
require(paths.distinct().size==count*(if(apertureMode) 5 else 1)) require(paths.distinct().size==count*(if(apertureMode) 5 else 1))
require(patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) }<=BodyTimeline.MAX_RGBA_BYTES) require(patches.sumOf { it.width*it.height*4L*(if(apertureMode) 5 else 1) }<=BodyTimeline.MAX_RGBA_BYTES)
field="mouthStates"
val states=root["mouthStates"] as List<Map<String,Any?>> val states=root["mouthStates"] as List<Map<String,Any?>>
require(states.size==5) require(states.size==5)
val c=states.associateBy { it["id"] as String } val c=states.associateBy { it["id"] as String }
require(c.keys==setOf("idle","opening","talk1","talk2","end-talk")) require(c.keys==setOf("idle","opening","talk1","talk2","end-talk"))
val curves=c.mapValues { (id,v) -> val curves=c.mapValues { (id,v) ->
val stateField="mouthStates[${states.indexOf(v)}]"
field="$stateField.durationMs"
val row=obj(v); val duration=integer(row["durationMs"]) val row=obj(v); val duration=integer(row["durationMs"])
field="$stateField.globalAlphaByFrame"
val alpha=(row["globalAlphaByFrame"] as List<*>).also { require(it.size in 2..60) }.map(::finite) val alpha=(row["globalAlphaByFrame"] as List<*>).also { require(it.size in 2..60) }.map(::finite)
val bridge=id in setOf("opening","end-talk") val bridge=id in setOf("opening","end-talk")
field="$stateField.frameCount"
require(integer(row["frameCount"])==alpha.size.toLong()) require(integer(row["frameCount"])==alpha.size.toLong())
field="$stateField.ptsUs"
val curvePts=if(dynamic) (row["ptsUs"] as List<*>).also { require(it.size==alpha.size) }.map(::integer) else alpha.indices.map { it*1_000_000L/24 } val curvePts=if(dynamic) (row["ptsUs"] as List<*>).also { require(it.size==alpha.size) }.map(::integer) else alpha.indices.map { it*1_000_000L/24 }
field="$stateField.timeline"
if(dynamic) { if(dynamic) {
require(duration in 100..1_000 && BodyTimeline.valid(curvePts,alpha.size,duration*1000, require(duration in 100..1_000 && BodyTimeline.valid(curvePts,alpha.size,duration*1000,
smallInt(row["fpsNumerator"]),smallInt(row["fpsDenominator"]),60,1_000_000)) smallInt(row["fpsNumerator"]),smallInt(row["fpsDenominator"]),60,1_000_000))
@@ -112,9 +131,13 @@ object ContinuousAvatarManifest {
require(alpha.size==if(bridge) 6 else 12) require(alpha.size==if(bridge) 6 else 12)
require(integer(row["fpsNumerator"])==24L && integer(row["fpsDenominator"])==1L) require(integer(row["fpsNumerator"])==24L && integer(row["fpsDenominator"])==1L)
} }
field="$stateField.globalAlphaByFrame"
require(alpha.all { it in 0f..1f }) require(alpha.all { it in 0f..1f })
field="$stateField.entryMouthAnchor"
require(row["entryMouthAnchor"]==if(id in setOf("idle","opening")) "A" else "B") require(row["entryMouthAnchor"]==if(id in setOf("idle","opening")) "A" else "B")
field="$stateField.exitMouthAnchor"
require(row["exitMouthAnchor"]==if(id in setOf("idle","end-talk")) "A" else "B") require(row["exitMouthAnchor"]==if(id in setOf("idle","end-talk")) "A" else "B")
field="$stateField.globalAlphaByFrame"
when(id) { when(id) {
"idle" -> require(alpha.all { it==0f }) "idle" -> require(alpha.all { it==0f })
"opening" -> require(alpha.first()==0f && alpha.last()==1f) "opening" -> require(alpha.first()==0f && alpha.last()==1f)
@@ -123,14 +146,16 @@ object ContinuousAvatarManifest {
} }
MouthCurve(id,duration,alpha,curvePts) MouthCurve(id,duration,alpha,curvePts)
} }
field="stateRouting"
val routing=obj(root["stateRouting"]) val routing=obj(root["stateRouting"])
val required=mapOf("idle" to setOf("idle","opening"),"opening" to setOf("talk1","talk2","end-talk"), val required=mapOf("idle" to setOf("idle","opening"),"opening" to setOf("talk1","talk2","end-talk"),
"talk1" to setOf("talk1","talk2","end-talk"),"talk2" to setOf("talk1","talk2","end-talk"),"end-talk" to setOf("idle")) "talk1" to setOf("talk1","talk2","end-talk"),"talk2" to setOf("talk1","talk2","end-talk"),"end-talk" to setOf("idle"))
require(routing.keys==required.keys) require(routing.keys==required.keys)
required.forEach { (id,targets) -> required.forEach { (id,targets) ->
field="stateRouting.$id"
val list=routing[id] as List<*>;require(list.size==targets.size && list.toSet()==targets) val list=routing[id] as List<*>;require(list.size==targets.size && list.toSet()==targets)
} }
ContinuousAvatarPack(body,patches,curves,pathRoot,sha,apertureMode) ContinuousAvatarPack(body,patches,curves,pathRoot,sha,apertureMode)
} catch(_: Exception) { null } } catch(_: Exception) { onReject?.invoke(field);null }
} }
} }
@@ -14,8 +14,12 @@ data class ConversationEdge(val id: String,val from: String,val to: String,val f
object EmotionActionManifest { object EmotionActionManifest {
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
fun read(root: Map<String,Any?>, actualSha: String, piPinnedSha: String,pathRoot: String="", fun read(root: Map<String,Any?>, actualSha: String, piPinnedSha: String,pathRoot: String="",
loadRuntime: (String,String)->ContinuousAvatarPack?): EmotionActionIndex? = try { onReject: ((String)->Unit)? = null,
loadRuntime: (String,String)->ContinuousAvatarPack?): EmotionActionIndex? {
var field="externalPin"
return try {
require(piPinnedSha.matches(Regex("[0-9a-f]{64}")) && actualSha==piPinnedSha) require(piPinnedSha.matches(Regex("[0-9a-f]{64}")) && actualSha==piPinnedSha)
field="schemaVersion/identityId/packId"
require(root["schemaVersion"]==2L || root["schemaVersion"]==2) require(root["schemaVersion"]==2L || root["schemaVersion"]==2)
require(root["identityId"]=="a01" && root["packId"]=="a01-expression-action-v1") require(root["identityId"]=="a01" && root["packId"]=="a01-expression-action-v1")
fun obj(value: Any?)=value as Map<String,Any?> fun obj(value: Any?)=value as Map<String,Any?>
@@ -26,16 +30,20 @@ object EmotionActionManifest {
fun integer(value: Any?): Long { val n=value as Number;require(n.toDouble()==n.toLong().toDouble());return n.toLong() } fun integer(value: Any?): Long { val n=value as Number;require(n.toDouble()==n.toLong().toDouble());return n.toLong() }
fun boundedInt(value: Any?, maximum: Int): Int = integer(value).also { require(it in 1..maximum.toLong()) }.toInt() fun boundedInt(value: Any?, maximum: Int): Int = integer(value).also { require(it in 1..maximum.toLong()) }.toInt()
val fallback=root["fallbackPackageId"] as String val fallback=root["fallbackPackageId"] as String
field="conversationPackages"
val rows=root["conversationPackages"] as List<Map<String,Any?>> val rows=root["conversationPackages"] as List<Map<String,Any?>>
require(rows.isNotEmpty() && rows.size<=12 && rows.map { it["id"] }.distinct().size==rows.size) require(rows.isNotEmpty() && rows.size<=12 && rows.map { it["id"] }.distinct().size==rows.size)
val packages=linkedMapOf<String,ContinuousAvatarPack>() val packages=linkedMapOf<String,ContinuousAvatarPack>()
val visuals=rows.map { row -> val visuals=rows.mapIndexed { index,row ->
field="conversationPackages[$index]"
val id=row["id"] as String;require(id.matches(Regex("[a-z0-9_-]{1,48}"))) val id=row["id"] as String;require(id.matches(Regex("[a-z0-9_-]{1,48}")))
val emotion=RoleEmotion.entries.single { it.wire==row["emotion"] } val emotion=RoleEmotion.entries.single { it.wire==row["emotion"] }
require(emotion in setOf(RoleEmotion.NEUTRAL,RoleEmotion.HAPPY,RoleEmotion.SAD) && require(emotion in setOf(RoleEmotion.NEUTRAL,RoleEmotion.HAPPY,RoleEmotion.SAD) &&
integer(row["visualIntensity"])==if(emotion==RoleEmotion.NEUTRAL) 0L else 1L) integer(row["visualIntensity"])==if(emotion==RoleEmotion.NEUTRAL) 0L else 1L)
field="conversationPackages[$index].runtimeManifest"
val reference=obj(row["runtimeManifest"]) val reference=obj(row["runtimeManifest"])
val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"]))) val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"])))
field="conversationPackages[$index].mouthBodySha256"
require(runtime.apertureMode && runtime.body.sha256==hash(row["mouthBodySha256"])) require(runtime.apertureMode && runtime.body.sha256==hash(row["mouthBodySha256"]))
require(runtime.patches.size==runtime.body.frameCount && runtime.patches.all { it.levels.size==5 }) require(runtime.patches.size==runtime.body.frameCount && runtime.patches.all { it.levels.size==5 })
require(runtime.body.ptsUs==runtime.patches.map { it.ptsUs } && require(runtime.body.ptsUs==runtime.patches.map { it.ptsUs } &&
@@ -45,16 +53,23 @@ object EmotionActionManifest {
val pts=runtime.patches.map { it.ptsUs } val pts=runtime.patches.map { it.ptsUs }
TalkPackage(id,emotion,runtime.body.sha256,hash(row["mouthBodySha256"]),runtime.body.ptsUs,pts,false) TalkPackage(id,emotion,runtime.body.sha256,hash(row["mouthBodySha256"]),runtime.body.ptsUs,pts,false)
} }
field="conversationPackages.cacheBytes/fallbackPackageId"
require(packages.values.sumOf { it.rgbaBytes }<=BodyTimeline.MAX_PACK_CACHE_BYTES) require(packages.values.sumOf { it.rgbaBytes }<=BodyTimeline.MAX_PACK_CACHE_BYTES)
require(visuals.single { it.id==fallback }.emotion==RoleEmotion.NEUTRAL) require(visuals.single { it.id==fallback }.emotion==RoleEmotion.NEUTRAL)
field="edges"
val edges=root["edges"] as List<Map<String,Any?>> val edges=root["edges"] as List<Map<String,Any?>>
require(edges.size<=100 && edges.map { it["id"] }.distinct().size==edges.size) require(edges.size<=100 && edges.map { it["id"] }.distinct().size==edges.size)
val admittedEdges=edges.map { edge -> val admittedEdges=edges.mapIndexed { index,edge ->
val edgeField="edges[$index]"
field="$edgeField.from/to"
require(edge["from"] in packages && edge["to"] in packages) require(edge["from"] in packages && edge["to"] in packages)
val from=checkNotNull(packages[edge["from"]]);val to=checkNotNull(packages[edge["to"]]) val from=checkNotNull(packages[edge["from"]]);val to=checkNotNull(packages[edge["to"]])
field="$edgeField.fromFrame"
require(integer(edge["fromFrame"]) in 0 until from.body.frameCount.toLong()) require(integer(edge["fromFrame"]) in 0 until from.body.frameCount.toLong())
field="$edgeField.toFrame"
require(integer(edge["toFrame"]) in 0 until to.body.frameCount.toLong()) require(integer(edge["toFrame"]) in 0 until to.body.frameCount.toLong())
require(edge["fromAnchor"]=="A" && edge["toAnchor"]=="A") require(edge["fromAnchor"]=="A" && edge["toAnchor"]=="A")
field="$edgeField.clip"
val clip=obj(edge["clip"]);path(clip["path"]);hash(clip["sha256"]) val clip=obj(edge["clip"]);path(clip["path"]);hash(clip["sha256"])
require(clip["hasAudio"]==false && integer(clip["width"])==480L && integer(clip["height"])==848L) require(clip["hasAudio"]==false && integer(clip["width"])==480L && integer(clip["height"])==848L)
val count=boundedInt(clip["frameCount"],BodyTimeline.MAX_TALK_FRAMES) val count=boundedInt(clip["frameCount"],BodyTimeline.MAX_TALK_FRAMES)
@@ -62,15 +77,20 @@ object EmotionActionManifest {
require(BodyTimeline.valid(pts,count,integer(clip["durationUs"]), require(BodyTimeline.valid(pts,count,integer(clip["durationUs"]),
boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000))) boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)))
val source=rows.single { it["id"]==edge["from"] } val source=rows.single { it["id"]==edge["from"] }
field="$edgeField.fromFrame/legalExitFrames"
require(integer(edge["fromFrame"]) in (source["legalExitFrames"] as List<*>).map(::integer)) require(integer(edge["fromFrame"]) in (source["legalExitFrames"] as List<*>).map(::integer))
field="$edgeField.fromPtsUs"
require(integer(edge["fromPtsUs"])==from.body.ptsUs[integer(edge["fromFrame"]).toInt()]) require(integer(edge["fromPtsUs"])==from.body.ptsUs[integer(edge["fromFrame"]).toInt()])
field="$edgeField.toPtsUs"
require(integer(edge["toPtsUs"])==to.body.ptsUs[integer(edge["toFrame"]).toInt()]) require(integer(edge["toPtsUs"])==to.body.ptsUs[integer(edge["toFrame"]).toInt()])
field="$edgeField.nativeLoop"
require(edge["nativeLoop"]==null || edge["nativeLoop"] is Boolean) require(edge["nativeLoop"]==null || edge["nativeLoop"] is Boolean)
val nativeLoop=edge["nativeLoop"]==true val nativeLoop=edge["nativeLoop"]==true
if(nativeLoop) require(edge["from"]==edge["to"] && integer(edge["fromFrame"])==from.body.frameCount-1L && if(nativeLoop) require(edge["from"]==edge["to"] && integer(edge["fromFrame"])==from.body.frameCount-1L &&
integer(edge["toFrame"])==0L && hash(clip["sha256"])==from.body.sha256 && pts==from.body.ptsUs && integer(edge["toFrame"])==0L && hash(clip["sha256"])==from.body.sha256 && pts==from.body.ptsUs &&
integer(clip["durationUs"])==from.body.durationUs) integer(clip["durationUs"])==from.body.durationUs)
val mouthRuntime=edge["mouthRuntimeManifest"]?.let { value -> val mouthRuntime=edge["mouthRuntimeManifest"]?.let { value ->
field="$edgeField.mouthRuntimeManifest"
require(!nativeLoop) // Native loops already use their exact package layer. require(!nativeLoop) // Native loops already use their exact package layer.
val reference=obj(value) val reference=obj(value)
val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"]))) val runtime=checkNotNull(loadRuntime(path(reference["path"]),hash(reference["sha256"])))
@@ -83,6 +103,7 @@ object EmotionActionManifest {
runtime.body.fpsDenominator==integer(clip["fpsDenominator"]).toInt()) runtime.body.fpsDenominator==integer(clip["fpsDenominator"]).toInt())
runtime runtime
} }
field="$edgeField.mouthAllowed"
require(edge["mouthAllowed"]==null || edge["mouthAllowed"] is Boolean) require(edge["mouthAllowed"]==null || edge["mouthAllowed"] is Boolean)
require(edge["mouthAllowed"]!=true || nativeLoop || mouthRuntime!=null) require(edge["mouthAllowed"]!=true || nativeLoop || mouthRuntime!=null)
require(mouthRuntime==null || edge["mouthAllowed"]!=false) require(mouthRuntime==null || edge["mouthAllowed"]!=false)
@@ -91,9 +112,11 @@ object EmotionActionManifest {
ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),480,848,pts.size, ContinuousBodyAsset(path(clip["path"]),hash(clip["sha256"]),480,848,pts.size,
integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)),nativeLoop,mouthRuntime) integer(clip["durationUs"]),pts,boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000)),nativeLoop,mouthRuntime)
} }
field="combinedRuntimeCacheBytes"
require(packages.values.sumOf { it.rgbaBytes }+ require(packages.values.sumOf { it.rgbaBytes }+
admittedEdges.mapNotNull { it.mouthRuntime }.sumOf { it.rgbaBytes }<=BodyTimeline.MAX_PACK_CACHE_BYTES) admittedEdges.mapNotNull { it.mouthRuntime }.sumOf { it.rgbaBytes }<=BodyTimeline.MAX_PACK_CACHE_BYTES)
val admitted=visuals.map { visual -> val admitted=visuals.map { visual ->
field="conversationPackages[${rows.indexOfFirst { it["id"]==visual.id }}].anchors/loopEdge/legalExitFrames"
val row=rows.single { it["id"]==visual.id } val row=rows.single { it["id"]==visual.id }
require(row["entryAnchor"]=="A" && row["exitAnchor"]=="A") require(row["entryAnchor"]=="A" && row["exitAnchor"]=="A")
val loop=row["loopEdge"] as String val loop=row["loopEdge"] as String
@@ -106,12 +129,16 @@ object EmotionActionManifest {
} }
visual.copy(approvedEdges=true) visual.copy(approvedEdges=true)
} }
field="actions"
val actions=root["actions"] as List<Map<String,Any?>> val actions=root["actions"] as List<Map<String,Any?>>
val actionPack=if(actions.isEmpty()) null else { val actionPack=if(actions.isEmpty()) null else {
require(actions.size==2 && actions.map { it["id"] }.toSet()==setOf("asset_01","asset_02")) require(actions.size==2 && actions.map { it["id"] }.toSet()==setOf("asset_01","asset_02"))
val assets=actions.map { action -> val assets=actions.mapIndexed { index,action ->
val actionField="actions[$index]"
field="$actionField.kind/mouthAllowed/disallowTALK/anchors"
require(action["kind"]=="dance" && action["mouthAllowed"]==false && action["disallowTALK"]==true) require(action["kind"]=="dance" && action["mouthAllowed"]==false && action["disallowTALK"]==true)
require(action["entryAnchor"]=="A" && action["returnAnchor"]=="A") require(action["entryAnchor"]=="A" && action["returnAnchor"]=="A")
field="$actionField.clip/audioEndUs"
val clip=obj(action["clip"]);path(clip["path"]);hash(clip["sha256"]) val clip=obj(action["clip"]);path(clip["path"]);hash(clip["sha256"])
val duration=integer(clip["durationUs"]) val duration=integer(clip["durationUs"])
require(clip["hasAudio"]==true && integer(action["audioEndUs"]) in 1..duration) require(clip["hasAudio"]==true && integer(action["audioEndUs"]) in 1..duration)
@@ -121,11 +148,14 @@ object EmotionActionManifest {
require(BodyTimeline.valid(pts,count,duration, require(BodyTimeline.valid(pts,count,duration,
boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000),5400,90_000_000)) boundedInt(clip["fpsNumerator"],120_000),boundedInt(clip["fpsDenominator"],10_000),5400,90_000_000))
require(duration in 1_000_000..90_000_000) require(duration in 1_000_000..90_000_000)
field="$actionField.sourcePackageId/returnPackageId"
require(action["sourcePackageId"]==fallback && action["returnPackageId"]==fallback) require(action["sourcePackageId"]==fallback && action["returnPackageId"]==fallback)
val runtime=packages.getValue(fallback) val runtime=packages.getValue(fallback)
field="$actionField.sourceFrame/returnFrame"
val sourceFrame=integer(action["sourceFrame"]);val returnFrame=integer(action["returnFrame"]) val sourceFrame=integer(action["sourceFrame"]);val returnFrame=integer(action["returnFrame"])
require(sourceFrame in 0 until runtime.body.frameCount.toLong() && returnFrame in 0 until runtime.body.frameCount.toLong()) require(sourceFrame in 0 until runtime.body.frameCount.toLong() && returnFrame in 0 until runtime.body.frameCount.toLong())
require(sourceFrame in (rows.single { it["id"]==fallback }["legalExitFrames"] as List<*>).map(::integer)) require(sourceFrame in (rows.single { it["id"]==fallback }["legalExitFrames"] as List<*>).map(::integer))
field="$actionField.sourcePtsUs/returnPtsUs"
require(integer(action["sourcePtsUs"])==runtime.body.ptsUs[sourceFrame.toInt()] && require(integer(action["sourcePtsUs"])==runtime.body.ptsUs[sourceFrame.toInt()] &&
integer(action["returnPtsUs"])==runtime.body.ptsUs[returnFrame.toInt()]) integer(action["returnPtsUs"])==runtime.body.ptsUs[returnFrame.toInt()])
ActionAsset(action["id"] as String,(duration+999)/1000,ActionMedia(path(clip["path"]),hash(clip["sha256"]),pathRoot, ActionAsset(action["id"] as String,(duration+999)/1000,ActionMedia(path(clip["path"]),hash(clip["sha256"]),pathRoot,
@@ -134,5 +164,6 @@ object EmotionActionManifest {
ReviewedActionPack(actualSha,assets) ReviewedActionPack(actualSha,assets)
} }
EmotionActionIndex(fallback,packages,admitted,actionPack,admittedEdges,pathRoot,rows.associate { it["id"] as String to it["loopEdge"] as String }) EmotionActionIndex(fallback,packages,admitted,actionPack,admittedEdges,pathRoot,rows.associate { it["id"] as String to it["loopEdge"] as String })
} catch(_: Exception) { null } } catch(_: Exception) { onReject?.invoke(field);null }
}
} }
+36
View File
@@ -429,3 +429,39 @@ Runtime Android/backend source and published code17 APK are unchanged; no new AP
or deployment needed. Exact new P4b/P5 index SHA/files, every idle bridge's own runtime, or deployment needed. Exact new P4b/P5 index SHA/files, every idle bridge's own runtime,
independent Pi pin and server duration allowlist remain required for actual activation. independent Pi pin and server duration allowlist remain required for actual activation.
Handoff: **PUBLIC_ACTION_CALLING_PATH_PASSED_AWAIT_REAL_INDEX_AND_EXACT_PI_PIN**. Handoff: **PUBLIC_ACTION_CALLING_PATH_PASSED_AWAIT_REAL_INDEX_AND_EXACT_PI_PIN**.
### Candidate rejection diagnostics and auxiliary music ASR (2026-10-13)
Clean remote-matched baseline `33b552473a5873325b4a2d0368d4d563d28c17cd`.
Candidate01 exact index `8fc051af130aae828dabcedf65881bb088bc2136885673c6d958b174fbc6d07e`
remains rejected and immutable. New optional parser observers report structural fields
only; normal admission predicates and null-on-rejection behavior remain unchanged.
`scripts/diagnose-avatar-candidate.py` writes bounded evidence without import/activation.
Actual candidate evidence: `logs/action-emotion/p4b-p5-reject-diagnostics-01/`.
It lists20 curve count/PTS mismatch records (both idle runtimes' five states), two
dance attached-cover stream rejects, plus three production parser records (first bad
state in each idle runtime and the index's failed runtime reference). These are25
records, with intentionally overlapping causes; not25 distinct independent failures.
Full4529 inventory/cache admission did not pass. Candidate02 has not arrived at
the finite existence check; no polling or unknown index activation follows.
Task-generated dance audio was decoded in memory and sent to the unchanged existing
ASR service, once successfully per clip. Both returned HTTP200, nonempty text length4,
model identifier absent/unknown. No transcription/lyrics/audio were saved. Evidence:
`logs/action-emotion/task-music-asr-finite-wav-01.json`. ASR cannot attribute background
lyrics to the actor, distinguish music hallucinations or certify no singing; human
listening, full-speed naturalness and device checks remain not_run/not_certified.
Two earlier transport attempts remain recorded: loopback connection failure (no
service response) and one413 response using ffmpeg's streaming WAV header declaring
2147483647 frames. The corrected finite WAV declares160085 actual frames. Successful
requests2; additional failed transport attempts2; no further requests, no LLM/TTS,
paid calls/cost0, no model/service/config/provider changes. The413 response proves
transport rejection, not successful inference; its server rejection reason was not read.
Fresh9 JVM/UI entry points and24 packaging/diagnostic tests passed, including exact
field callbacks, real malformed runtime admission and finite WAV frame/header bounds.
Application/instrumentation Kotlin compilation passed against the existing e73f pin;
no APK assembled or installed.200 GLES goldens and gateway97 pass/1 Silero skip are
retained prior evidence, not rerun for this diagnostics-only milestone. Code17 APK,
exact pin and live0.8 Qwen/TTS/allowlist are unchanged.
Handoff: **REJECTION_FIELD_REPORT_READY_AWAIT_CANDIDATE02_EXACT_SHA**.
+10
View File
@@ -168,6 +168,16 @@ P4b/P5 integration preflight (2026-10-13; no new asset schema):
Reports keep dance_available:false until independent exact pin/capability release. Reports keep dance_available:false until independent exact pin/capability release.
Dance import/publication is separately blocked pending gateway capability admission; Dance import/publication is separately blocked pending gateway capability admission;
read-only checking is available now without activating or rewriting owner assets. read-only checking is available now without activating or rewriting owner assets.
Structural rejection diagnostics (read only, no admission or approval):
`python3 scripts/diagnose-avatar-candidate.py --manifest <index>/manifest.json --sha256 <exact-sha> --output logs/action-emotion/<new-directory>`.
The bounded `reject-details.json` and `production-parser.json` identify task-relative
files and field paths without raw metadata/model output. Each runtime is independently
passed through the production Kotlin parser, which reports its first rejected field;
curve count/PTS comparisons additionally list all such mismatches, and both action
stream layouts are inspected even if a runtime fails. At most128 rejection rows are
written. No rejection found is not a full decode/hash/cache admission; the existing
package-avatar-emotion.py full gate and external Pi pin remain mandatory.
- All source/target frames bind the silent delivered body SHA/PTS, not an immutable - 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 master with audio/cover. Count241 and approximate10s are not substitutes for
independently measured video duration, final video PTS and presented audio end. independently measured video duration, final video PTS and presented audio end.
+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('--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('--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('--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() args = parser.parse_args()
if args.index_manifest and args.runtime_manifest: parser.error('Choose runtime or index manifest, not both') 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: for name, main, real in suites:
if args.suite and name != args.suite: continue if args.suite and name != args.suite: continue
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out: 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=Path(out)/'ActualIndexCheck.kt'
extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+ 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'+ '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'+ 'val parsed=runtimes.mapValues { (path,value) ->\nval hash=hashes.getValue(path) as String\n'+
'check(hashes[path]==hash)\n@Suppress("UNCHECKED_CAST")\n'+ '@Suppress("UNCHECKED_CAST")\nContinuousAvatarManifest.read(value as Map<String,Any?>,hash,hash,true,"fixture/"+path.substringBeforeLast(47.toChar())+"/",'+
'ContinuousAvatarManifest.read(runtimes[path] as Map<String,Any?>,hash,hash,true,"fixture/"+path.substringBeforeLast(47.toChar())+"/")\n})\n'+ '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.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')+ ('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') '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) files.append(extra)
subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib', 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) '-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: if name == 'avatar' and args.runtime_manifest:
subprocess.run([JAVA,'-cp',out+':'+cp,'ActualRuntimeCheckKt'],check=True,cwd=ROOT,timeout=30) subprocess.run([JAVA,'-cp',out+':'+cp,'ActualRuntimeCheckKt'],check=True,cwd=ROOT,timeout=30)
if name == 'avatar' and args.index_manifest: 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())
+6
View File
@@ -33,6 +33,12 @@ fun conversationPackageCheck() {
check(index.packages.values.map { it.body.frameCount }==listOf(97,121,49) && index.actionPack==null) check(index.packages.values.map { it.body.frameCount }==listOf(97,121,49) && index.actionPack==null)
check(index.edges.size==7 && index.edges.all { it.clip.ptsUs.size==12 && it.clip.sha256==pin }) check(index.edges.size==7 && index.edges.all { it.clip.ptsUs.size==12 && it.clip.sha256==pin })
val graph=edges(packs) val graph=edges(packs)
val rejectFields=mutableListOf<String>()
val badCursor=meta+("edges" to listOf(graph[0]+("toPtsUs" to 1L))+graph.drop(1))
check(EmotionActionManifest.read(badCursor,pin,pin,onReject=rejectFields::add) { path,hash ->
packs[path.substringBefore('/')]?.takeIf { it.manifestSha==hash }
}==null)
check(rejectFields==listOf("edges[0].toPtsUs"))
var rejected=0 var rejected=0
fun invalid(change: Map<String,Any?>) { check(read(meta+change)==null);rejected++ } fun invalid(change: Map<String,Any?>) { check(read(meta+change)==null);rejected++ }
invalid(mapOf("edges" to graph.filterNot { it["id"]=="sad-neutral" })) invalid(mapOf("edges" to graph.filterNot { it["id"]=="sad-neutral" }))
+8
View File
@@ -71,6 +71,14 @@ fun dynamicBodyCheck() {
invalid(root+("patches" to listOf(patches[0]+("levels" to listOf(levels[0],levels[1]+("path" to levels[0]["path"]))+levels.drop(2)))+patches.drop(1))) invalid(root+("patches" to listOf(patches[0]+("levels" to listOf(levels[0],levels[1]+("path" to levels[0]["path"]))+levels.drop(2)))+patches.drop(1)))
val states=root["mouthStates"] as List<Map<String,Any?>> val states=root["mouthStates"] as List<Map<String,Any?>>
invalid(root+("mouthStates" to listOf(states[0]+("ptsUs" to listOf(0L)))+states.drop(1))) invalid(root+("mouthStates" to listOf(states[0]+("ptsUs" to listOf(0L)))+states.drop(1)))
for((stateIndex,key,value) in listOf(Triple(1,"frameCount",count),Triple(2,"ptsUs",listOf(0L)))) {
val changed=states.mapIndexed { i,s -> if(i==stateIndex) s+(key to value) else s }
val fields=mutableListOf<String>()
check(ContinuousAvatarManifest.read(root+("mouthStates" to changed),sha,sha,true,"fixture/",fields::add)==null)
check(fields==listOf("mouthStates[$stateIndex].$key"));boundaries++
}
val acceptedFields=mutableListOf<String>()
check(ContinuousAvatarManifest.read(root,sha,sha,true,"fixture/",acceptedFields::add)!=null && acceptedFields.isEmpty())
check(runCatching { ContinuousFramePresenter(pack).decoded(pack.body.ptsUs[1]) }.isFailure) check(runCatching { ContinuousFramePresenter(pack).decoded(pack.body.ptsUs[1]) }.isFailure)
check(runCatching { selectMouthPatch(pack,count,.5f) }.isFailure) check(runCatching { selectMouthPatch(pack,count,.5f) }.isFailure)
if(fpsD==1) { if(fpsD==1) {
@@ -0,0 +1,58 @@
"""Actual parser field reports and finite WAV transport; no model calls or asset mutation."""
import copy
import importlib.util
import io
import json
from pathlib import Path
import sys
import unittest
import wave
ROOT=Path(__file__).resolve().parents[2]
sys.path.insert(0,str(Path(__file__).parent))
import test_emotion_package as fixture
def load(name,path):
spec=importlib.util.spec_from_file_location(name,ROOT/path)
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module);return module
diagnostic=load('diagnostic','scripts/diagnose-avatar-candidate.py')
music=load('music_probe','scripts/probe-task-music-asr.py')
class DiagnosticTests(unittest.TestCase):
def test_actual_curve_reject_and_bounded_artifact(self):
fixture.PackageTests.setUpClass()
try:
runtime=copy.deepcopy(fixture.PackageTests.runtime)
runtime['mouthStates'][0]['frameCount']=97
runtime['mouthStates'][0]['ptsUs']=runtime['body']['ptsUs']
path=fixture.PackageTests.source/'neutral/manifest.json';path.write_text(json.dumps(runtime))
index=copy.deepcopy(fixture.PackageTests.index)
index['conversationPackages'][0]['runtimeManifest']['sha256']=diagnostic.pack.file_sha(path)
fixture.PackageTests.manifest.write_text(json.dumps(index))
report=diagnostic.diagnose(fixture.PackageTests.manifest,diagnostic.pack.file_sha(fixture.PackageTests.manifest),fixture.PackageTests.base/'diagnostic')
self.assertEqual(report['status'],'rejected');self.assertEqual(report['production_metadata'],'rejected')
self.assertIn({'file':'neutral/manifest.json','field':'mouthStates[0].frameCount','code':'production_metadata_rejected'},report['rejects'])
self.assertTrue(any(r['code']=='curve_pts_count_mismatch' for r in report['rejects']))
self.assertLessEqual(len(report['rejects']),128);self.assertFalse(report['dance_available'])
self.assertEqual(runtime,json.loads(path.read_bytes()))
with self.assertRaises(ValueError):
diagnostic.diagnose(fixture.PackageTests.manifest,'0'*64,fixture.PackageTests.base/'wrong-hash')
self.assertFalse((fixture.PackageTests.base/'wrong-hash').exists())
with self.assertRaises(ValueError):
diagnostic.diagnose(fixture.PackageTests.manifest,diagnostic.pack.file_sha(fixture.PackageTests.manifest),fixture.PackageTests.source/'owner-output')
self.assertFalse((fixture.PackageTests.source/'owner-output').exists())
finally:fixture.PackageTests.tearDownClass()
def test_music_finite_wav_header_and_full_payload(self):
pcm=b'\x01\x00'*160085
with wave.open(io.BytesIO(music.finite_wav(pcm))) as wav:
self.assertEqual((wav.getframerate(),wav.getnchannels(),wav.getsampwidth()),(16000,1,2))
self.assertEqual(wav.getnframes(),160085)
self.assertEqual(wav.readframes(wav.getnframes()),pcm)
for invalid in (b'',b'x',b'\0'*(16000*15*2+2)):
with self.subTest(size=len(invalid)),self.assertRaises(ValueError):music.finite_wav(invalid)
if __name__=='__main__':unittest.main(verbosity=2)