Add portable avatar animation asset skill and silent media audit
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only silent H264 timing audit; no generation, tracking or runtime approval."""
|
||||
import argparse
|
||||
from decimal import Decimal, ROUND_HALF_EVEN
|
||||
from fractions import Fraction
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
class AuditError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def require(value, reason):
|
||||
if not value:
|
||||
raise AuditError(reason)
|
||||
|
||||
|
||||
def file_sha(path):
|
||||
with path.open('rb') as stream:
|
||||
digest = hashlib.sha256()
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def microseconds(value):
|
||||
return int((Decimal(str(value)) * 1_000_000).to_integral_value(rounding=ROUND_HALF_EVEN))
|
||||
|
||||
|
||||
def audit(video, role, width, height, fps, ffprobe, ffmpeg):
|
||||
before = file_sha(video)
|
||||
result = subprocess.run([
|
||||
ffprobe, '-v', 'error', '-show_entries',
|
||||
'stream=codec_type,codec_name,width,height,r_frame_rate,duration:stream_disposition=attached_pic:frame=media_type,best_effort_timestamp_time',
|
||||
'-show_streams', '-show_frames', '-of', 'json', str(video),
|
||||
], capture_output=True, timeout=60)
|
||||
require(result.returncode == 0, 'ffprobe_failed')
|
||||
data = json.loads(result.stdout)
|
||||
streams = data['streams']
|
||||
require(len(streams) == 1 and streams[0]['codec_type'] == 'video', 'requires_single_video_no_audio')
|
||||
stream = streams[0]
|
||||
require(stream['codec_name'] == 'h264' and not stream.get('disposition', {}).get('attached_pic', 0), 'requires_normal_h264')
|
||||
require((stream['width'], stream['height']) == (width, height), 'shape_mismatch')
|
||||
actual_fps = Fraction(stream['r_frame_rate'])
|
||||
require(actual_fps == fps and 1 <= actual_fps <= 60, 'fps_mismatch')
|
||||
frames = [frame for frame in data['frames'] if frame.get('media_type') == 'video']
|
||||
pts = [microseconds(frame['best_effort_timestamp_time']) for frame in frames]
|
||||
limit = 5400 if role == 'action' else 720
|
||||
duration = microseconds(stream['duration'])
|
||||
require(2 <= len(pts) <= limit, 'frame_count_bound')
|
||||
require((1_000_000 if role == 'action' else 100_000) <= duration <= (90_000_000 if role == 'action' else 30_000_000), 'duration_bound')
|
||||
require(pts[0] == 0 and pts[-1] < duration and all(a < b for a, b in zip(pts, pts[1:])), 'invalid_actual_pts')
|
||||
period = Fraction(1_000_000, 1) / fps
|
||||
require(abs(Fraction(duration) - len(pts) * period) <= period + 2 and
|
||||
duration - pts[-1] <= 2 * period + 2 and
|
||||
all(b - a <= 2 * period + 2 for a, b in zip(pts, pts[1:])), 'timeline_inconsistent')
|
||||
decoded = subprocess.run([
|
||||
ffmpeg, '-nostdin', '-v', 'error', '-xerror', '-i', str(video),
|
||||
'-map', '0:v:0', '-f', 'null', '-',
|
||||
], capture_output=True, timeout=60)
|
||||
require(decoded.returncode == 0, 'full_decode_failed')
|
||||
require(file_sha(video) == before, 'source_drift')
|
||||
return {
|
||||
'status': 'passed', 'scope': 'silent_media_only_not_runtime_admission',
|
||||
'source_file': video.name, 'role': role, 'sha256': before, 'bytes': video.stat().st_size,
|
||||
'codec': 'h264', 'width': width, 'height': height, 'frameCount': len(pts),
|
||||
'ptsUs': pts, 'durationUs': duration, 'fpsNumerator': fps.numerator,
|
||||
'fpsDenominator': fps.denominator, 'hasAudio': False, 'streams': 1,
|
||||
'full_decode': 'passed', 'talking_visual_review': 'not_run',
|
||||
'seam_review': 'not_run', 'production_parser': 'not_run', 'device': 'not_run',
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--video', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--role', choices=('body', 'bridge', 'action'), required=True)
|
||||
parser.add_argument('--width', type=int, default=720)
|
||||
parser.add_argument('--height', type=int, default=1280)
|
||||
parser.add_argument('--fps', default='24')
|
||||
parser.add_argument('--ffprobe', default='ffprobe')
|
||||
parser.add_argument('--ffmpeg', default='ffmpeg')
|
||||
args = parser.parse_args()
|
||||
video = args.video.resolve(strict=True)
|
||||
output = args.output.resolve()
|
||||
require(video.is_file(), 'source_not_file')
|
||||
require(not output.exists() and not output.is_relative_to(video.parent), 'fresh_evidence_outside_media_directory_required')
|
||||
require((args.width, args.height) in ((720, 1280), (480, 848)), 'unsupported_target_shape')
|
||||
try:
|
||||
fps = Fraction(args.fps)
|
||||
require(1 <= fps <= 60, 'invalid_target_fps')
|
||||
report = audit(video, args.role, args.width, args.height, fps, args.ffprobe, args.ffmpeg)
|
||||
except AuditError as error:
|
||||
report = {'status': 'rejected', 'scope': 'silent_media_only_not_runtime_admission', 'reason': str(error)}
|
||||
except FileNotFoundError:
|
||||
report = {'status': 'not_run', 'reason': 'required_media_tool_missing'}
|
||||
except subprocess.TimeoutExpired:
|
||||
report = {'status': 'rejected', 'reason': 'media_tool_timeout'}
|
||||
except (KeyError, ValueError, TypeError, ArithmeticError):
|
||||
report = {'status': 'rejected', 'reason': 'invalid_probe_metadata_or_target_fps'}
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with output.open('x') as target:
|
||||
json.dump(report, target, indent=2)
|
||||
target.write('\n')
|
||||
print(json.dumps({key: value for key, value in report.items() if key != 'ptsUs'}))
|
||||
return 0 if report['status'] == 'passed' else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (AuditError, OSError) as error:
|
||||
print(json.dumps({'status': 'rejected', 'reason': str(error) if isinstance(error, AuditError) else 'file_operation_failed'}))
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Finite synthetic-media checks; no AI, portraits, device or network access."""
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).with_name('audit-silent-video.py')
|
||||
FFMPEG = os.environ.get('AVATAR_AUDIT_FFMPEG') or shutil.which('ffmpeg')
|
||||
FFPROBE = os.environ.get('AVATAR_AUDIT_FFPROBE') or shutil.which('ffprobe')
|
||||
|
||||
|
||||
@unittest.skipUnless(FFMPEG and FFPROBE, 'ffmpeg/ffprobe required for synthetic media integration tests')
|
||||
class MediaAuditTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix='avatar-skill-test-')
|
||||
cls.root = Path(cls.temp.name)
|
||||
cls.media = cls.root/'media'
|
||||
cls.media.mkdir()
|
||||
cls.silent = cls.media/'synthetic-silent.mp4'
|
||||
cls.audio = cls.media/'synthetic-with-aac.mp4'
|
||||
subprocess.run([FFMPEG, '-nostdin', '-v', 'error', '-f', 'lavfi', '-i',
|
||||
'color=c=gray:s=480x848:r=24', '-frames:v', '48', '-c:v', 'libx264',
|
||||
'-pix_fmt', 'yuv420p', '-an', str(cls.silent)], check=True, capture_output=True, timeout=30)
|
||||
subprocess.run([FFMPEG, '-nostdin', '-v', 'error', '-i', str(cls.silent),
|
||||
'-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=mono',
|
||||
'-c:v', 'copy', '-c:a', 'aac', '-shortest', str(cls.audio)],
|
||||
check=True, capture_output=True, timeout=30)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.temp.cleanup()
|
||||
|
||||
def run_audit(self, source, name, *extra):
|
||||
output = self.root/(name+'.json')
|
||||
result = subprocess.run([sys.executable, str(SCRIPT), '--video', str(source),
|
||||
'--role', 'action', '--width', '480', '--height', '848',
|
||||
'--output', str(output), '--ffmpeg', FFMPEG, '--ffprobe', FFPROBE,
|
||||
*extra], capture_output=True, text=True, timeout=30)
|
||||
return result, output
|
||||
|
||||
def test_silent_video_measures_actual_pts_and_keeps_review_unrun(self):
|
||||
result, output = self.run_audit(self.silent, 'silent')
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
report = json.loads(output.read_text())
|
||||
self.assertEqual(report['frameCount'], 48)
|
||||
self.assertEqual(len(report['ptsUs']), 48)
|
||||
self.assertEqual(report['ptsUs'][:4], [0, 41667, 83333, 125000])
|
||||
self.assertEqual(report['durationUs'], 2_000_000)
|
||||
self.assertFalse(report['hasAudio'])
|
||||
self.assertEqual(report['full_decode'], 'passed')
|
||||
self.assertEqual(report['production_parser'], 'not_run')
|
||||
self.assertEqual(report['talking_visual_review'], 'not_run')
|
||||
|
||||
def test_even_silent_aac_is_rejected(self):
|
||||
result, output = self.run_audit(self.audio, 'audio')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(json.loads(output.read_text())['reason'], 'requires_single_video_no_audio')
|
||||
|
||||
def test_wrong_fps_and_shape_are_rejected(self):
|
||||
for name, extra, reason in (
|
||||
('fps', ['--fps', '30'], 'fps_mismatch'),
|
||||
('shape', ['--width', '720', '--height', '1280'], 'shape_mismatch'),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
result, output = self.run_audit(self.silent, name, *extra)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(json.loads(output.read_text())['reason'], reason)
|
||||
|
||||
def test_existing_evidence_cannot_be_overwritten(self):
|
||||
result, output = self.run_audit(self.silent, 'existing')
|
||||
self.assertEqual(result.returncode, 0)
|
||||
before = output.read_bytes()
|
||||
result, _ = self.run_audit(self.audio, 'existing')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(output.read_bytes(), before)
|
||||
|
||||
def test_evidence_cannot_be_written_into_media_directory(self):
|
||||
result, output = self.run_audit(self.silent, 'unused', '--output', str(self.media/'report.json'))
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse((self.media/'report.json').exists())
|
||||
|
||||
def test_missing_tool_is_not_a_pass(self):
|
||||
result, output = self.run_audit(self.silent, 'missing', '--ffprobe', str(self.root/'absent-ffprobe'))
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(json.loads(output.read_text())['status'], 'not_run')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user