Files
logic-puzzle/scripts/check_story_package.py
2026-11-14 08:55:48 +01:00

128 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""Validate a narrated story package, using standard Python plus ffmpeg."""
import argparse
import hashlib
import json
import struct
import subprocess
import wave
from pathlib import Path
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('package', type=Path)
a = parser.parse_args()
repo = Path(__file__).resolve().parents[1]
package = a.package.resolve()
read = lambda path: json.loads(path.read_text())
sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
campaign = read(package / 'campaign.json')
notebook = read(package / 'notebook.json')['pages']
scripts = {s['pageId']: s for s in read(package / 'narration/scripts.json')}
manifest = read(package / 'narration/manifest.json')
tracks = read(package / 'audio/narration_manifest.json')['tracks']
assert tracks == manifest['tracks'], 'Runtime/provenance manifests differ'
performance_path = package / 'narration/performance.json'
if performance_path.exists():
performance = read(performance_path)
cast = read(package / 'narration/cast.json')
assert manifest.get('performance') == performance, 'Stale performance configuration'
assert manifest.get('speakers') == cast, 'Stale voice design'
assert manifest.get('model') == performance['model'], 'Wrong narration model'
assert manifest.get('modelRevision') == performance['revision'], 'Wrong model revision'
if manifest.get('voiceClone'):
reference = package / 'narration/references/elias.wav'
metadata = read(reference.with_suffix('.json'))
assert sha(reference) == metadata['sha256'] == manifest['voiceClone']['referenceSha256']
assert metadata['text'] == manifest['voiceClone']['referenceText']
assert len({p['id'] for p in notebook}) == len(notebook), 'Duplicate page IDs'
prose = {p['id'] for p in notebook if p['type'] != 'puzzle'}
assert set(scripts) == prose == set(tracks), 'Every prose page must have exactly one recording'
images = {package / 'artwork/cover-v1.png'}
for level in campaign['levels']:
images.add(repo / level['illustrationAsset'])
for path in images:
data = path.read_bytes()
assert data[:8] == b'\x89PNG\r\n\x1a\n', path
w, h, depth, colour = struct.unpack('>IIBB', data[16:26])
assert min(w, h) >= 512 and depth == 8 and colour == 6, f'Expected large RGBA PNG: {path}'
for page in notebook:
if page['type'] == 'puzzle':
assert page['id'] not in tracks, 'Puzzle instructions should not autoplay'
continue
index = page.get('campaignIndex')
source = page.get('textSource')
text = campaign['levels'][index][source] if source in ('before', 'after') else page['text']
text = '\n\n'.join(s for s in [text, page.get('continuation', '')] if s)
script, track = scripts[page['id']], tracks[page['id']]
assert text == script['text'] == track['text'], f'Stale script: {page["id"]}'
assert hashlib.sha256(text.encode()).hexdigest() == track['textSha256']
assert track.get('cueJoin','\n\n').join(c['text'] for c in track['cues']) == text, f'Incomplete cues: {page["id"]}'
if script.get('segments'):
cast = read(package / 'narration/cast.json')
assert track['segments'] == script['segments'], 'Stale performance directions'
assert ''.join(s['text'] for s in script['segments']) == text
assert len(script['segments']) == len(track['cues'])
for segment, cue in zip(script['segments'], track['cues']):
assert segment['speaker'] == cue['speaker']
assert cast[segment['speaker']]['voice'] == cue['voice']
if performance_path.exists():
expected = ' '.join((cast[segment['speaker']]['designPrompt'],
performance['delivery'], segment['direction']))
synthesis = cue.get('synthesis')
if manifest.get('voiceClone'):
assert bool(synthesis) == (segment['speaker'] in ('Elias', 'The echo')), \
'Every Elias and echo cue must use the shared reference'
if synthesis:
assert segment['speaker'] in ('Elias', 'The echo')
assert synthesis['engine'] == 'qwen3-voice-clone'
assert synthesis['model'] == manifest['voiceClone']['model']
assert synthesis['revision'] == manifest['voiceClone']['revision']
assert synthesis['referenceSha256'] == manifest['voiceClone']['referenceSha256']
assert synthesis['seed'] == cue['seed']
assert cue['instruct'] == '', 'Cloning did not use VoiceDesign instructions'
else:
assert cue['instruct'] == expected, 'Performance instruction was not rendered'
assert track['engine'] == performance['engine']
assert track['model'] == performance['model']
assert track['modelRevision'] == performance['revision']
for event in track['events']:
assert 0 <= event['startMs'] < event['endMs'] <= track['durationMs']
assert all(event['endMs'] <= c['startMs'] or event['startMs'] >= c['endMs'] for c in track['cues']), 'Foley must leave the spoken words clear'
wav = repo / track['asset']
master = package / 'narration/wav' / track['file']
flac = package / 'narration/flac' / track['flacFile']
assert sha(wav) == sha(master) == track['wavSha256'], wav
assert sha(flac) == track['flacSha256'], flac
with wave.open(str(wav), 'rb') as audio:
assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (1, 2, 24000)
assert audio.getnframes() == track['frames']
pcm = audio.readframes(audio.getnframes())
samples = memoryview(pcm).cast('h')
peak = max(abs(v) for v in samples)
assert 1000 < peak < 32000, f'Silent/clipped recording: {wav}'
assert abs(track['durationMs'] - round(track['frames'] / 24)) <= 1
last = 0
for cue in track['cues']:
assert last <= cue['startMs'] < cue['endMs'] <= track['durationMs']
last = cue['endMs']
decoded = subprocess.check_output(['ffmpeg', '-v', 'error', '-i', str(flac), '-f', 's16le', '-acodec', 'pcm_s16le', '-'])
assert decoded == pcm, f'Lossless master mismatch: {flac}'
print(f'PASS {page["id"]}: script, cues, PCM and lossless archive ({track["durationMs"]/1000:.1f}s)')
minutes = sum(t['durationMs'] for t in tracks.values()) / 60000
if (package / 'audio/atmosphere.json').exists():
atmosphere = read(package / 'audio/atmosphere.json')
provenance = read(package / 'audio/atmosphere_provenance.json')['tracks']
for page_id, scene in atmosphere['pages'].items():
assert page_id in {p['id'] for p in notebook}
assert scene in atmosphere['scenes']
for name, scene in atmosphere['scenes'].items():
path = repo / scene['asset']
assert sha(path) == provenance[name]['wavSha256']
with wave.open(str(path), 'rb') as audio:
assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (1, 2, 24000)
pcm = memoryview(audio.readframes(audio.getnframes())).cast('h')
assert abs(pcm[-1] - pcm[0]) <= 1, 'Loop has a discontinuity'
assert 1000 < max(abs(v) for v in pcm) < 24000
print(f'PASS atmosphere: {name}, bundled PCM and seamless loop')
print(f'PASS package: {len(campaign["levels"])} puzzles, {len(notebook)} leaves, {len(images)} illustrations, {len(tracks)} recordings, {minutes:.1f} minutes')