Enhance postcard puzzles and narration

This commit is contained in:
Hadrian Burkhardt
2026-11-14 08:55:48 +01:00
parent abaab927d9
commit b19295472d
158 changed files with 5257 additions and 1695 deletions
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""Audit the shared Elias reference, retained cast and ASR coverage."""
import hashlib
import json
from pathlib import Path
root = Path(__file__).resolve().parents[1]
package = root / 'assets/stories/midnight-invitation/narration'
work = root / 'artifacts/elias-consistent'
manifest = json.loads((package / 'manifest.json').read_text())
baseline = json.loads((work / 'original-manifest.json').read_text())
review = json.loads((work / 'transcription-review.json').read_text())
review_by_hash = {row['sha256']: row for row in review.values()}
reference = manifest['voiceClone']['referenceSha256']
assert hashlib.sha256((package / 'references/elias.wav').read_bytes()).hexdigest() == reference
cloned = retained = flags = 0
for page, track in manifest['tracks'].items():
old = baseline['tracks'][page]
for cue, previous in zip(track['cues'], old['cues'], strict=True):
if cue['speaker'] in ('Elias', 'The echo'):
assert cue['synthesis']['referenceSha256'] == reference
assert cue['takeSha256'] in review_by_hash, f'Unreviewed take: {page}'
flags += bool(review_by_hash[cue['takeSha256']]['differences'])
cloned += 1
else:
assert cue['takeSha256'] == previous['takeSha256'], f'Other actor changed: {page}'
retained += 1
print(f'{cloned} Elias/echo cues use one reference; {retained} other-actor takes retained.')
print(f'{flags} cues have automatic transcript differences; flags require listening.')
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Check generated postcard narration and ensure its text stays in sync."""
import json
import hashlib
import os
from pathlib import Path
import subprocess
import sys
import wave
root = Path(__file__).resolve().parents[1]
source = json.loads((root / 'assets/postcards/recordings-source.json').read_text())
current = json.loads(subprocess.check_output([
os.environ.get('DART_BIN', 'dart'),
'tool/export_postcards.dart',
], cwd=root))
if source != current:
sys.exit('Postcard narration source differs from the current card text.')
if len(source) != 14 or len({p['id'] for p in source}) != 14:
sys.exit('Expected fourteen uniquely identified postcards.')
seconds = 0
illustrations = set()
for card in source:
illustration = root / 'assets/postcards/illustrations' / (card['id'] + '.png')
data = illustration.read_bytes()
if not data.startswith(b'\x89PNG\r\n\x1a\n'):
sys.exit(f'{illustration}: expected PNG illustration')
illustrations.add(hashlib.sha256(data).digest())
path = root / 'assets/postcards/audio' / (card['id'] + '.wav')
with wave.open(str(path), 'rb') as wav:
if wav.getnchannels() != 1 or wav.getframerate() != 24000 or wav.getsampwidth() != 2:
sys.exit(f'{path}: expected mono PCM16 at 24 kHz')
duration = wav.getnframes() / wav.getframerate()
if not 3 < duration < 180:
sys.exit(f'{path}: implausible duration {duration:.1f}s')
seconds += duration
if len(illustrations) != len(source):
sys.exit('Each postcard must have a distinct illustration.')
print(f'14 distinct illustrations and recordings, {seconds/60:.1f} minutes, source text synchronized.')
+19 -1
View File
@@ -29,6 +29,11 @@ if performance_path.exists():
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'
@@ -63,7 +68,20 @@ for page in notebook:
if performance_path.exists():
expected = ' '.join((cast[segment['speaker']]['designPrompt'],
performance['delivery'], segment['direction']))
assert cue['instruct'] == expected, 'Performance instruction was not rendered'
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']
+13 -1
View File
@@ -25,12 +25,24 @@ def visit(value):
missing.append(value)
for name in ['index.html', 'flutter_bootstrap.js', 'main.dart.js',
for name in ['index.html', 'flutter_bootstrap.js', 'narration.js', 'main.dart.js',
'manifest.json', 'main.dart.wasm', 'main.dart.mjs', 'assets/AssetManifest.bin.json',
'assets/assets/fonts/DancingScript.ttf']:
if not (root / name).is_file():
missing.append(name)
bootstrap = root / 'flutter_bootstrap.js'
if bootstrap.is_file() and ('{{flutter_js}}' in bootstrap.read_text() or
'{{flutter_build_config}}' in bootstrap.read_text()):
raise SystemExit('Flutter bootstrap still contains source templates; serve the built output, not web/.')
postcards = Path('assets/postcards/recordings-source.json')
if postcards.is_file():
visit('assets/postcards/island-postcard-v1.png')
for card in json.loads(postcards.read_text()):
visit(f"assets/postcards/audio/{card['id']}.wav")
visit(f"assets/postcards/illustrations/{card['id']}.png")
font_manifest = root / 'assets/FontManifest.json'
if font_manifest.is_file():
visit(json.loads(font_manifest.read_text()))
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Compare old/new voice embeddings as a heuristic, not a listening test."""
import json
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from huggingface_hub import snapshot_download
from qwen_tts import Qwen3TTSModel
root = Path(__file__).resolve().parents[1]
work = root / 'artifacts/elias-consistent'
package = root / 'assets/stories/midnight-invitation/narration'
new = json.loads((package / 'manifest.json').read_text())
old = json.loads((work / 'original-manifest.json').read_text())
cache = {}
for meta in (work / 'takes').glob('*.json'):
data = json.loads(meta.read_text())
cache[data['sha256']] = meta.with_suffix('.wav')
pairs = []
for page, track in new['tracks'].items():
for current, previous in zip(track['cues'], old['tracks'][page]['cues'], strict=True):
if current['speaker'] != 'Elias': continue
oldpath = root / 'artifacts/midnight-qwen-full/takes' / (previous['requestSha256'] + '.wav')
newpath = cache[current['takeSha256']]
if sf.info(oldpath).duration >= 5 and sf.info(newpath).duration >= 5:
pairs.append((page, oldpath, newpath))
break
if len(pairs) == 12: break
if len(pairs) < 8: raise ValueError('Insufficient matched passages')
model_path = snapshot_download('Qwen/Qwen3-TTS-12Hz-1.7B-Base', revision='fd4b254389122332181a7c3db7f27e918eec64e3', local_files_only=True)
model = Qwen3TTSModel.from_pretrained(model_path, device_map='cuda', dtype=torch.float16, attn_implementation='sdpa')
def embedding(path):
data, rate = sf.read(path, dtype='float32')
if rate != 24000 or data.ndim != 1: raise ValueError(path)
data = data[:rate * 15]
with torch.inference_mode():
value = model.model.extract_speaker_embedding(audio=data, sr=rate).float().cpu().numpy()
return value / np.linalg.norm(value)
reference = embedding(package / 'references/elias.wav')
rows = []
for page, before, after in pairs:
rows.append({'page':page,'oldCosine':float(reference @ embedding(before)), 'newCosine':float(reference @ embedding(after))})
print(page, round(rows[-1]['oldCosine'],3), round(rows[-1]['newCosine'],3), flush=True)
report = {'note':'Same-model speaker embedding similarity is only a heuristic; it cannot establish perceived voice consistency or replace listening.',
'samples':rows,'oldMean':float(np.mean([r['oldCosine'] for r in rows])),
'newMean':float(np.mean([r['newCosine'] for r in rows]))}
(work / 'speaker-consistency.json').write_text(json.dumps(report,indent=2)+'\n')
print('Means:',round(report['oldMean'],3),round(report['newMean'],3),flush=True)
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""Regenerate Elias from one reference; retain the other actors and Foley.
All pages are staged first, with resumable content-addressed clone batches.
The existing packaged narration is not replaced until every page succeeds.
"""
import hashlib
import json
import os
from pathlib import Path
import shutil
import time
import numpy as np
import soundfile as sf
import torch
from huggingface_hub import snapshot_download
from qwen_tts import Qwen3TTSModel
from render_qwen_narration import assemble, file_hash, instruction, read, write
ROOT = Path(__file__).resolve().parents[1]
package = ROOT / 'assets/stories/midnight-invitation'
work = ROOT / 'artifacts/elias-consistent'
oldwork = ROOT / 'artifacts/midnight-qwen-full/takes'
source = package / 'narration'
for name in ('takes', 'pages'):
(work / name).mkdir(parents=True, exist_ok=True)
records = read(source / 'scripts.json')
cast = read(source / 'cast.json')
performance = read(source / 'performance.json')
current_manifest = read(source / 'manifest.json')
baseline_path = work / 'original-manifest.json'
if baseline_path.exists():
original = read(baseline_path)
elif current_manifest.get('voiceClone'):
raise RuntimeError('Original VoiceDesign manifest is missing; regenerate the original takes first')
else:
original = current_manifest
write(baseline_path, original)
source_hashes = {name: file_hash(source / name) for name in ('scripts.json','cast.json','performance.json','manifest.json','references/elias.wav','references/elias.json')}
reference = source / 'references/elias.wav'
reference_metadata = read(source / 'references/elias.json')
reference_text = reference_metadata['text']
reference_sha = file_hash(reference)
if reference_metadata['sha256'] != reference_sha:
raise ValueError('Elias reference does not match its metadata')
revision = 'fd4b254389122332181a7c3db7f27e918eec64e3'
requests = []
for record in records:
old_cues = original['tracks'][record['pageId']]['cues']
for index, (segment, cue) in enumerate(zip(record['segments'], old_cues, strict=True)):
if segment['speaker'] not in ('Elias', 'The echo'):
continue
request = {'text':segment['text'].strip(), 'speaker':segment['speaker'],
'model':'Qwen/Qwen3-TTS-12Hz-1.7B-Base', 'revision':revision,
'referenceSha256':reference_sha, 'referenceText':reference_text,
'generation':'clone-v1', 'seed':4217}
key = hashlib.sha256(json.dumps(request, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
requests.append((record['pageId'], index, request, key))
requests.sort(key=lambda r: (len(r[2]['text'].split()), r[0], r[1]))
paths = {}
model = prompt = None
for offset in range(0, len(requests), 4):
group = requests[offset:offset+4]
keys = [item[3] for item in group]
batch_key = hashlib.sha256(''.join(keys).encode()).hexdigest()[:16]
cached = []
for page, index, req, key in group:
path = work / 'takes' / f'{key}-{batch_key}.wav'
meta = path.with_suffix('.json')
valid = (path.exists() and meta.exists() and
read(meta).get('sha256') == file_hash(path) and
read(meta).get('batchSeed', 4217 + offset) == 4217 + offset)
cached.append(valid)
paths[(page,index)] = (path, req, key, batch_key, 4217 + offset)
if all(cached):
print(f'{offset+len(group)}/{len(requests)} cached',flush=True)
continue
if model is None:
snapshot = snapshot_download('Qwen/Qwen3-TTS-12Hz-1.7B-Base', revision=revision, local_files_only=True)
model = Qwen3TTSModel.from_pretrained(snapshot, device_map='cuda', dtype=torch.float16, attn_implementation='sdpa')
prompt = model.create_voice_clone_prompt(ref_audio=str(reference), ref_text=reference_text)
print(f'{offset+1}-{offset+len(group)}/{len(requests)} rendering',flush=True)
torch.manual_seed(4217 + offset)
with torch.inference_mode():
waves, rate = model.generate_voice_clone(text=[r[2]['text'] for r in group], language='English', voice_clone_prompt=prompt, max_new_tokens=2048)
for (page,index,req,key), audio in zip(group,waves,strict=True):
path = paths[(page,index)][0]
data = np.asarray(audio,dtype=np.float32).reshape(-1)
if rate != 24000 or len(data) < rate*.2 or not np.isfinite(data).all():
raise ValueError(f'Invalid take {page}:{index}')
words = len(req['text'].split())
if not max(.15, words/7) <= len(data)/rate <= max(12, words*1.5):
raise ValueError(f'Implausible duration {page}:{index} {len(data)/rate:.1f}s')
tmp = path.with_suffix('.tmp.wav')
sf.write(tmp,data,rate,subtype='FLOAT'); os.replace(tmp,path)
write(path.with_suffix('.json'), {'request':req,'sha256':file_hash(path),
'batch':batch_key,'batchSeed':4217 + offset})
tracks = {}
for record in records:
old = original['tracks'][record['pageId']]
takes = []
for index, cue in enumerate(old['cues']):
original_key = cue['requestSha256']
original_spec = read(oldwork / (original_key + '.json'))['spec']
if (record['pageId'],index) in paths:
path, req, key, batch, batch_seed = paths[(record['pageId'],index)]
spec = {**original_spec, 'seed':batch_seed, 'cloneRequest':req, 'cloneBatch':batch}
else:
path = oldwork / (original_key + '.wav')
spec = original_spec
if not path.exists(): raise FileNotFoundError(path)
takes.append((path,spec))
track = assemble(record,takes,cast,work / 'pages')
for index, cue in enumerate(track['cues']):
if (record['pageId'],index) in paths:
# Base voice cloning uses the reference, not the VoiceDesign
# natural-language direction stored in the original script.
cue['instruct'] = ''
cue['synthesis'] = {'engine':'qwen3-voice-clone','model':'Qwen/Qwen3-TTS-12Hz-1.7B-Base',
'revision':revision,'referenceSha256':reference_sha,
'seed':paths[(record['pageId'],index)][4]}
track.update(asset=old['asset'],engine=old['engine'],model=old['model'],modelRevision=old['modelRevision'])
tracks[record['pageId']] = track
provenance = {**original, 'method':'Qwen VoiceDesign cast with reference-anchored Qwen Base Elias/echo.',
'voiceClone': {'model':'Qwen/Qwen3-TTS-12Hz-1.7B-Base','revision':revision,
'referenceSha256':reference_sha,'referenceText':reference_text},
'tracks':tracks}
write(work / 'manifest.json',provenance)
if os.environ.get('PUBLISH_ELIAS') == '1':
if any(file_hash(source / name) != sha for name,sha in source_hashes.items()):
raise RuntimeError('Sources changed during render; refusing publication')
for track in tracks.values():
for src,dst in ((work/'pages'/track['file'],source/'wav'/track['file']),
(work/'pages'/track['file'],package/'audio'/track['file']),
(work/'pages'/track['flacFile'],source/'flac'/track['flacFile'])):
tmp=dst.with_suffix(dst.suffix+'.tmp');shutil.copyfile(src,tmp);os.replace(tmp,dst)
write(source/'manifest.json',provenance)
write(package/'audio/narration_manifest.json',{'tracks':tracks})
print('Published all reference-anchored Elias readings.',flush=True)
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Render postcard readings from the island narrator reference; resume per card."""
import hashlib
import json
import os
from pathlib import Path
import shutil
import numpy as np
import soundfile as sf
import torch
from huggingface_hub import snapshot_download
from qwen_tts import Qwen3TTSModel
ROOT = Path(__file__).resolve().parents[1]
records = json.loads((ROOT / 'assets/postcards/recordings-source.json').read_text())
work = ROOT / 'artifacts/postcard-voices'
work.mkdir(parents=True, exist_ok=True)
reference_text = ('The compass rests in a shallow wooden box beneath the notebook. '
'Its needle trembles as you lift it, then settles.\n\n'
'Inside the lid, Gran has written a few words.')
source = ROOT / 'assets/narration/wav/narration_cottage_compass_memory.wav'
ref = work / 'narrator-reference.wav'
wav, sr = sf.read(source, dtype='float32')
sf.write(ref, wav[round(.18 * sr):round(11.7 * sr)], sr)
model_path = snapshot_download('Qwen/Qwen3-TTS-12Hz-1.7B-Base', revision='fd4b254389122332181a7c3db7f27e918eec64e3', local_files_only=True)
model = Qwen3TTSModel.from_pretrained(model_path, device_map='cuda', dtype=torch.float16, attn_implementation='sdpa')
prompt = model.create_voice_clone_prompt(ref_audio=str(ref), ref_text=reference_text)
for n, card in enumerate(records):
target = work / (card['id'] + '.wav')
signature = hashlib.sha256((card['text'] + reference_text).encode()).hexdigest()
meta = target.with_suffix('.json')
if target.exists() and meta.exists() and json.loads(meta.read_text())['signature'] == signature:
print(f'{n+1}/14 cached: {card["id"]}', flush=True)
continue
print(f'{n+1}/14 rendering: {card["id"]}', flush=True)
paragraphs = [x.strip() for x in card['text'].split('\n\n') if x.strip()]
pieces = []
rate = 24000
for offset in range(0, len(paragraphs), 4):
group = paragraphs[offset:offset + 4]
group_hash = hashlib.sha256(json.dumps([group, reference_text, 4242 + offset], ensure_ascii=False).encode()).hexdigest()
checkpoint = work / f'{card["id"]}-{offset}-{group_hash[:12]}.npz'
if checkpoint.exists():
with np.load(checkpoint, allow_pickle=False) as saved:
waves = [saved[f'w{i}'] for i in range(len(group))]
print(f' batch {offset//4 + 1} cached', flush=True)
else:
torch.manual_seed(4242 + offset)
with torch.inference_mode():
waves, rate = model.generate_voice_clone(text=group, language='English', voice_clone_prompt=prompt, max_new_tokens=2048)
if rate != 24000 or len(waves) != len(group):
raise ValueError(f'Invalid batch: {card["id"]}')
data = {f'w{i}': np.asarray(audio, dtype=np.float32) for i, audio in enumerate(waves)}
temp = checkpoint.with_suffix('.tmp.npz')
np.savez(temp, **data)
temp.replace(checkpoint)
print(f' batch {offset//4 + 1} saved', flush=True)
for audio in waves:
data = np.asarray(audio, dtype=np.float32)
if rate != 24000 or len(data) < rate * .2 or not np.isfinite(data).all():
raise ValueError(f'Invalid audio: {card["id"]}')
pieces.extend([data, np.zeros(int(rate * .35), dtype=np.float32)])
combined = np.concatenate(pieces)
peak = max(float(np.max(np.abs(combined))), .001)
combined *= .85 / peak
temporary = target.with_suffix('.tmp.wav')
sf.write(temporary, combined, rate, subtype='PCM_16')
temporary.replace(target)
meta.write_text(json.dumps({'signature':signature,'duration':len(combined)/rate})+'\n')
print(f' {len(combined)/rate:.1f}s', flush=True)
out = ROOT / 'assets/postcards/audio'
out.mkdir(parents=True, exist_ok=True)
for card in records:
shutil.copy2(work / (card['id'] + '.wav'), out / (card['id'] + '.wav'))
print('Published all 14 recordings.', flush=True)
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/env python3
"""Audition offline TTS against the existing door scene without changing app assets.
Preparation needs only Python and ffmpeg. Run each TTS backend in its own venv.
"""
import argparse
import gc
import hashlib
import importlib.metadata
import json
import random
import subprocess
import time
import wave
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
STORY = ROOT / 'assets/stories/midnight-invitation'
DEFAULT_OUT = ROOT / 'artifacts/voice-audition'
PAGE = 'midnight.feather.memory'
RATE = 24000
DIRECTIONS = {
'Elias': 'An adult British male storyteller with a warm, low voice. '
'Intimate and measured, recounting a frightening personal memory. '
'Restrained unease, clear diction, quiet natural speech; no shouting.',
'Iris': 'An adult British woman with a soft, slightly weary voice. '
'Speak quietly and urgently, warning someone of danger nearby. '
'Restrained fear, clear diction, deliberate natural speech; no shouting.',
}
def ffmpeg(*args):
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y',
*map(str, args)], check=True)
def write_json(path, value):
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n')
def mix(dry, out):
"""Identical loudness target and background gain for each engine."""
normalized = dry.with_name(dry.stem + '-matched.wav')
ffmpeg('-i', dry, '-af', 'loudnorm=I=-19:TP=-2:LRA=7',
'-ar', RATE, '-ac', 1, normalized)
with wave.open(str(normalized)) as master:
duration = master.getnframes() / master.getframerate()
ffmpeg('-i', normalized, '-stream_loop', '-1', '-i', out / 'ambience.wav',
'-filter_complex',
f'[1:a]volume=0.07,afade=t=in:d=0.5,'
f'afade=t=out:st={max(0, duration-.8)}:d=0.8[bed];'
'[0:a][bed]amix=inputs=2:duration=first:normalize=0,'
'alimiter=limit=0.98:level=false[a]',
'-map', '[a]', '-ar', RATE, '-ac', 1, dry.with_name(dry.stem + '-mix.wav'))
def prepare(out):
out.mkdir(parents=True, exist_ok=True)
track = json.loads((STORY / 'audio/narration_manifest.json').read_text())['tracks'][PAGE]
record = next(r for r in json.loads((STORY / 'narration/scripts.json').read_text())
if r['pageId'] == PAGE)
# Start at the knock; retain all the warnings and the closing "Hurry".
start = track['cues'][1]['startMs'] / 1000
length = track['durationMs'] / 1000 - start
ffmpeg('-i', ROOT / track['asset'], '-ss', start, '-t', length,
'-ar', RATE, '-ac', 1, out / '01-kokoro-dry.wav')
ffmpeg('-i', STORY / 'audio/ambience_threshold.wav', '-ar', RATE, '-ac', 1,
out / 'ambience.wav')
refs = {}
for speaker, index in [('Elias', 0), ('Iris', 8)]:
cue = track['cues'][index]
path = out / f'reference-kokoro-{speaker.lower()}.wav'
ffmpeg('-i', ROOT / track['asset'], '-ss', cue['startMs'] / 1000,
'-t', (cue['endMs'] - cue['startMs']) / 1000,
'-ar', RATE, '-ac', 1, path)
refs[speaker] = {'file': path.name, 'text': cue['text'].strip()}
write_json(out / 'script.json', {
'pageId': PAGE, 'sourceSha256': track['wavSha256'],
'segments': record['segments'][1:], 'directions': DIRECTIONS,
'references': refs,
'comparison': 'Same prose, pauses, effects, perspective filter and mixing. '
'Qwen uses designed voices; Chatterbox uses existing synthetic '
'Kokoro references. Voice identity is not held constant.',
})
mix(out / '01-kokoro-dry.wav', out)
print(f'Prepared {length:.1f}s Kokoro baseline in {out}', flush=True)
def render(args):
import numpy as np
import soundfile as sf
import torch
from audio_drama import effect
out = args.out
script = json.loads((out / 'script.json').read_text())
device = args.device
if device == 'auto':
device = 'cuda' if torch.cuda.is_available() else 'cpu'
if device == 'cuda' and not torch.cuda.is_available():
raise RuntimeError('GPU unavailable. Pass /dev/kfd and /dev/dri into the '
'container and install a compatible ROCm PyTorch build.')
torch.set_num_threads(args.threads)
torch.manual_seed(args.seed)
random.seed(args.seed)
np.random.seed(args.seed)
print(f'{args.backend}: {device}; torch {torch.__version__}; HIP {torch.version.hip}', flush=True)
started = time.monotonic()
take_dir = out / args.backend
take_dir.mkdir(exist_ok=True)
dtype = torch.float32 if device == 'cpu' else torch.float16
if args.backend == 'qwen':
from qwen_tts import Qwen3TTSModel
from huggingface_hub import snapshot_download
from huggingface_hub.errors import LocalEntryNotFoundError
def local_model(repo):
# Load cached snapshots by path: some tokenizer versions still query
# model_info for a repo ID even with HF_HUB_OFFLINE enabled.
try:
return snapshot_download(repo, local_files_only=True)
except LocalEntryNotFoundError:
return snapshot_download(repo)
design_id = 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign'
model_id = 'Qwen/Qwen3-TTS-12Hz-1.7B-Base'
needs_design = any(not (take_dir / f'reference-{speaker.lower()}.wav').exists()
for speaker in script['references'])
design = Qwen3TTSModel.from_pretrained(
local_model(design_id), device_map=device, dtype=dtype,
attn_implementation='eager') if needs_design else None
for speaker, ref in script['references'].items():
path = take_dir / f'reference-{speaker.lower()}.wav'
if not path.exists():
print(f'Designing {speaker}', flush=True)
with torch.inference_mode():
wavs, sr = design.generate_voice_design(
text=ref['text'], language='English',
instruct=script['directions'][speaker], max_new_tokens=2048)
sf.write(path, wavs[0], sr)
del design
gc.collect()
if device == 'cuda':
torch.cuda.empty_cache()
model = Qwen3TTSModel.from_pretrained(
local_model(model_id), device_map=device, dtype=dtype, attn_implementation='eager')
prompts = {speaker: model.create_voice_clone_prompt(
ref_audio=str(take_dir / f'reference-{speaker.lower()}.wav'),
ref_text=ref['text']) for speaker, ref in script['references'].items()}
def generate(segment):
wavs, sr = model.generate_voice_clone(
text=segment['text'].strip(), language='English',
voice_clone_prompt=prompts[segment['speaker']], max_new_tokens=2048)
return wavs[0], sr
else:
from chatterbox.tts import ChatterboxTTS
model_id = 'ResembleAI/chatterbox'
model = ChatterboxTTS.from_pretrained(device=device)
def generate(segment):
ref = script['references'][segment['speaker']]
wav = model.generate(
segment['text'].strip(), audio_prompt_path=str(out / ref['file']),
exaggeration=0.65, cfg_weight=0.3)
return wav.detach().cpu().numpy().reshape(-1), model.sr
pieces, cues, elapsed_frames = [], [], 0
model_ready_seconds = time.monotonic() - started
for index, segment in enumerate(script['segments']):
path = take_dir / f'{index:02d}-{segment["speaker"].lower()}.wav'
print(f'{args.backend} {index+1}/{len(script["segments"])}: {segment["speaker"]}', flush=True)
# Only successful raw takes are cached; edits to the script require --out anew.
cached = path.exists() and index not in args.retake
generation_started = time.monotonic()
if not cached:
torch.manual_seed(args.seed + index)
np.random.seed(args.seed + index)
random.seed(args.seed + index)
with torch.inference_mode():
audio, sr = generate(segment)
audio = np.asarray(audio, dtype=np.float32).reshape(-1)
if not np.isfinite(audio).all() or len(audio) < sr * 0.1:
raise ValueError(f'Invalid generated audio: {path}')
sf.write(path, audio, sr, subtype='FLOAT')
write_json(path.with_suffix('.json'), {
'seed': args.seed + index, 'device': device, 'model': model_id,
'text': segment['text'], 'speaker': segment['speaker'],
})
generation_seconds = time.monotonic() - generation_started
converted = take_dir / 'resampled.wav'
ffmpeg('-i', path, '-ar', RATE, '-ac', 1, converted)
audio, _ = sf.read(converted, dtype='float32')
if segment.get('perspective') == 'behind-door':
audio = np.convolve(audio, np.ones(9) / 9, mode='same') * .86
fade = min(240, len(audio) // 4)
audio[:fade] *= np.linspace(0, 1, fade)
audio[-fade:] *= np.linspace(1, 0, fade)
cues.append({**segment, 'cached': cached,
'take': json.loads(path.with_suffix('.json').read_text())
if path.with_suffix('.json').exists() else {'source': 'initial audition run'},
'generationSeconds': round(generation_seconds, 3),
'startMs': round(elapsed_frames * 1000 / RATE),
'endMs': round((elapsed_frames + len(audio)) * 1000 / RATE)})
pause = np.zeros(round(RATE * segment.get('pauseMs', 600) / 1000), dtype=np.float32)
if segment.get('afterEffect'):
sound = effect(segment['afterEffect'], RATE)
lead = round(RATE * .16)
pause = np.pad(pause, (0, max(0, lead + len(sound) - len(pause))))
pause[lead:lead + len(sound)] += sound
pieces.extend([audio, pause])
elapsed_frames += len(audio) + len(pause)
prefix = '02-qwen' if args.backend == 'qwen' else '03-chatterbox'
dry = out / f'{prefix}-dry.wav'
sf.write(dry, np.concatenate(pieces), RATE, subtype='FLOAT')
mix(dry, out)
packages = {}
for name in ['torch', 'torchaudio', 'qwen-tts', 'chatterbox-tts', 'transformers']:
try:
packages[name] = importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
pass
write_json(out / f'{prefix}-provenance.json', {
'model': model_id, 'device': device, 'hip': torch.version.hip,
'gpu': torch.cuda.get_device_name() if device == 'cuda' else None,
'seed': args.seed, 'packages': packages, 'cues': cues,
'scriptSha256': hashlib.sha256((out / 'script.json').read_bytes()).hexdigest(),
'wallSecondsThisRun': round(time.monotonic() - started, 2),
'modelReadySeconds': round(model_ready_seconds, 2),
'durationSeconds': elapsed_frames / RATE,
'designModel': design_id if args.backend == 'qwen' else None,
'directions': script['directions'] if args.backend == 'qwen' else None,
'exaggeration': .65 if args.backend == 'chatterbox' else None,
'cfgWeight': .3 if args.backend == 'chatterbox' else None,
})
print(f'Saved {out / (prefix + "-dry-mix.wav")}', flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('backend', choices=['prepare', 'qwen', 'chatterbox'])
parser.add_argument('--out', type=Path, default=DEFAULT_OUT)
parser.add_argument('--device', choices=['auto', 'cpu', 'cuda'], default='auto')
parser.add_argument('--threads', type=int, default=8)
parser.add_argument('--seed', type=int, default=1031)
parser.add_argument('--retake', type=int, action='append', default=[],
help='Regenerate this zero-based excerpt segment, retaining other takes')
args = parser.parse_args()
if args.backend == 'prepare':
prepare(args.out)
else:
render(args)
if __name__ == '__main__':
main()
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Retake one postcard paragraph while keeping the remaining checkpointed takes."""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from huggingface_hub import snapshot_download
from qwen_tts import Qwen3TTSModel
from review_qwen_narration import words
ROOT = Path(__file__).resolve().parents[1]
work = ROOT / 'artifacts/postcard-voices'
parser = argparse.ArgumentParser()
parser.add_argument('id')
parser.add_argument('paragraph', type=int, help='1-based paragraph')
parser.add_argument('--seed', type=int, default=12161)
parser.add_argument('--spoken-text', help='Alternative punctuation only; words must be unchanged')
args = parser.parse_args()
records = json.loads((ROOT / 'assets/postcards/recordings-source.json').read_text())
card = next(c for c in records if c['id'] == args.id)
paragraphs = [p.strip() for p in card['text'].split('\n\n') if p.strip()]
index = args.paragraph - 1
if not 0 <= index < len(paragraphs):
parser.error('Paragraph is out of range')
spoken_text = args.spoken_text or paragraphs[index]
if words(spoken_text) != words(paragraphs[index]):
parser.error('Retake text must keep the same words as the postcard')
reference_text = ('The compass rests in a shallow wooden box beneath the notebook. '
'Its needle trembles as you lift it, then settles.\n\n'
'Inside the lid, Gran has written a few words.')
def checkpoint(offset):
group = paragraphs[offset:offset + 4]
h = hashlib.sha256(json.dumps([group, reference_text, 4242 + offset], ensure_ascii=False).encode()).hexdigest()
return work / f'{card["id"]}-{offset}-{h[:12]}.npz'
offset = index // 4 * 4
path = checkpoint(offset)
with np.load(path, allow_pickle=False) as original:
takes = {name: original[name] for name in original.files}
model_path = snapshot_download('Qwen/Qwen3-TTS-12Hz-1.7B-Base', revision='fd4b254389122332181a7c3db7f27e918eec64e3', local_files_only=True)
model = Qwen3TTSModel.from_pretrained(model_path, device_map='cuda', dtype=torch.float16, attn_implementation='sdpa')
prompt = model.create_voice_clone_prompt(ref_audio=str(work / 'narrator-reference.wav'), ref_text=reference_text)
torch.manual_seed(args.seed)
with torch.inference_mode():
waves, rate = model.generate_voice_clone(text=spoken_text, language='English', voice_clone_prompt=prompt, max_new_tokens=1024)
if rate != 24000 or len(waves[0]) < rate * .2 or not np.isfinite(waves[0]).all():
raise ValueError('Invalid audio')
takes[f'w{index-offset}'] = np.asarray(waves[0], dtype=np.float32)
temp = path.with_suffix('.tmp.npz')
np.savez(temp, **takes)
temp.replace(path)
pieces = []
for off in range(0, len(paragraphs), 4):
with np.load(checkpoint(off), allow_pickle=False) as data:
for i in range(len(paragraphs[off:off+4])):
pieces.extend([data[f'w{i}'], np.zeros(int(rate * .35), dtype=np.float32)])
audio = np.concatenate(pieces)
audio *= .85 / max(float(np.max(np.abs(audio))), .001)
target = work / (card['id'] + '.wav')
temporary = target.with_suffix('.retake.wav')
sf.write(temporary, audio, rate, subtype='PCM_16')
temporary.replace(target)
meta = target.with_suffix('.json')
metadata = json.loads(meta.read_text())
metadata.update({'duration': len(audio)/rate, 'retake': {'paragraph': args.paragraph, 'seed': args.seed, 'spokenText': spoken_text}})
meta.write_text(json.dumps(metadata)+'\n')
asset = ROOT / 'assets/postcards/audio' / target.name
if asset.parent.exists():
import shutil
temporary_asset = asset.with_suffix('.retake.wav')
shutil.copy2(target, temporary_asset)
temporary_asset.replace(asset)
print(f'Retook {card["id"]} paragraph {args.paragraph}; {len(audio)/rate:.1f}s', flush=True)
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Offline ASR flags for reference-anchored Elias takes; not a listening test."""
import difflib
import hashlib
import json
import time
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from scipy.signal import resample_poly
from huggingface_hub import snapshot_download
from transformers import pipeline
from review_qwen_narration import words
ROOT = Path(__file__).resolve().parents[1]
work = ROOT / 'artifacts/elias-consistent'
torch.set_num_threads(2)
model = snapshot_download('openai/whisper-base.en', revision='911407f4214e0e1d82085af863093ec0b66f9cd6', local_files_only=True)
recognizer = pipeline('automatic-speech-recognition', model=model, device='cpu')
results = {}
while True:
for metadata in sorted((work / 'takes').glob('*.json')):
if metadata.name in results: continue
take = json.loads(metadata.read_text())
path = metadata.with_suffix('.wav')
if not path.exists(): continue
sha = hashlib.sha256(path.read_bytes()).hexdigest()
if take['sha256'] != sha: raise ValueError(f'Stale take: {path}')
audio, rate = sf.read(path, dtype='float32')
if rate != 24000: raise ValueError(path)
recognized = recognizer({'raw':np.asarray(resample_poly(audio,2,3)), 'sampling_rate':16000}, chunk_length_s=25, ignore_warning=True)['text']
expected, actual = words(take['request']['text']), words(recognized)
differences = [{'expected':' '.join(expected[i:j]),'recognized':' '.join(actual[k:l])}
for tag,i,j,k,l in difflib.SequenceMatcher(None,expected,actual).get_opcodes() if tag != 'equal']
results[metadata.name] = {'expected':take['request']['text'],'recognized':recognized,'differences':differences,'sha256':sha}
(work / 'transcription-review.json').write_text(json.dumps(results,indent=2,ensure_ascii=False)+'\n')
print(f'Reviewed {len(results)}: {len(differences)} flags',flush=True)
if (work / 'manifest.json').exists() and len(results) == len(list((work / 'takes').glob('*.json'))): break
time.sleep(10)
print(f'{len(results)} takes reviewed; transcription flags require listening.',flush=True)
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Offline transcription flags for generated postcards; not a listening review."""
import difflib
import argparse
import hashlib
import json
from pathlib import Path
import time
import numpy as np
import soundfile as sf
import torch
from scipy.signal import resample_poly
from huggingface_hub import snapshot_download
from transformers import pipeline
from review_qwen_narration import words
root = Path(__file__).resolve().parents[1]
work = root / 'artifacts/postcard-voices'
cards = json.loads((root / 'assets/postcards/recordings-source.json').read_text())
parser = argparse.ArgumentParser()
parser.add_argument('--id', help='Review one postcard again')
args = parser.parse_args()
if args.id:
cards = [card for card in cards if card['id'] == args.id]
if not cards:
parser.error('Unknown postcard')
torch.set_num_threads(2)
model = snapshot_download('openai/whisper-base.en', revision='911407f4214e0e1d82085af863093ec0b66f9cd6', local_files_only=True)
recognizer = pipeline('automatic-speech-recognition', model=model, device='cpu')
report_path = work / 'transcription-review.json'
results = json.loads(report_path.read_text()) if args.id and report_path.exists() else {}
if args.id:
results.pop(args.id, None)
while not all(card['id'] in results for card in cards):
for card in cards:
if card['id'] in results:
continue
path = work / (card['id'] + '.wav')
if not path.exists() or not path.with_suffix('.json').exists():
continue
audio, rate = sf.read(path, dtype='float32')
if rate != 24000:
raise ValueError(path)
recognized = recognizer({'raw': np.asarray(resample_poly(audio, 2, 3)), 'sampling_rate': 16000}, chunk_length_s=25, ignore_warning=True)['text']
expected, actual = words(card['text']), words(recognized)
changes = [{'expected':' '.join(expected[i:j]), 'recognized':' '.join(actual[k:l])}
for tag, i, j, k, l in difflib.SequenceMatcher(None, expected, actual).get_opcodes() if tag != 'equal']
results[card['id']] = {'expected': card['text'], 'recognized': recognized, 'differences': changes,
'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}
report_path.write_text(json.dumps(results, indent=2, ensure_ascii=False) + '\n')
print(f'{len(results)}/14 {card["id"]}: {len(changes)} potential differences', flush=True)
if not all(card['id'] in results for card in cards):
time.sleep(10)
+101
View File
@@ -0,0 +1,101 @@
// End-to-end Flutter web autoplay test under Chromium's strict gesture policy.
import {spawn} from 'node:child_process';
import {mkdtemp, rm, writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import assert from 'node:assert/strict';
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const profile=await mkdtemp(join(tmpdir(),'lumen-app-'));
const port=19377;
const browser=spawn(process.env.CHROME_BIN||'/home/ubuntu/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome',[
'--headless=new','--no-sandbox','--disable-dev-shm-usage','--disable-gpu',
'--autoplay-policy=user-gesture-required','--remote-allow-origins=*',`--remote-debugging-port=${port}`,
`--user-data-dir=${profile}`,'about:blank'],{stdio:'ignore'});
let ws;
try {
let target;
for(let i=0;i<100;i++){try{const r=await fetch(`http://127.0.0.1:${port}/json/new?about:blank`,{method:'PUT'});if(r.ok){target=await r.json();break;}}catch(_){}await wait(100);}
assert.ok(target,'Chromium did not start');
ws=new WebSocket(target.webSocketDebuggerUrl);await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j;});
let n=0;const pending=new Map();
ws.onmessage=e=>{const m=JSON.parse(e.data);if(m.id&&pending.has(m.id)){const p=pending.get(m.id);pending.delete(m.id);m.error?p.reject(Error(m.error.message)):p.resolve(m.result);}};
const cdp=(method,params={})=>new Promise((resolve,reject)=>{const id=++n;pending.set(id,{resolve,reject});ws.send(JSON.stringify({id,method,params}));});
const evaluate=async expression=>{const r=await cdp('Runtime.evaluate',{expression,awaitPromise:true,returnByValue:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
await cdp('Page.enable');await cdp('Runtime.enable');
await cdp('Emulation.setDeviceMetricsOverride',{width:600,height:960,deviceScaleFactor:1,mobile:false});
await cdp('Page.addScriptToEvaluateOnNewDocument',{source:`
window.__audioEvents=[];
let api;
Object.defineProperty(window,'lumenNarration',{configurable:true,get(){return api},set(v){
api=v; const original=v.play;
v.play=function(id,url,speed,reload){
const event={id,url,status:'requested'};window.__audioEvents.push(event);
const result=original(id,url,speed,reload);
result.then(()=>event.status='started',error=>{event.status='rejected';event.error=String(error)});
return result;
};
}});`});
if(process.env.LUMEN_POSTCARD==='1') {
await cdp('Page.addScriptToEvaluateOnNewDocument',{source:`for(let i=0;i<3;i++) localStorage.setItem('done_postcard_v2_washing-line_'+i,'true');`});
}
await cdp('Page.navigate',{url:'http://127.0.0.1:18765/'});
let ready=false;
for(let i=0;i<180;i++){try{ready=await evaluate("!document.getElementById('loading') && !!window.lumenNarration && !!document.querySelector('flt-glass-pane')");if(ready)break;}catch(_){}await wait(500);}
assert.ok(ready,'Flutter shelf did not load');
await wait(2500);
const click=async(x,y)=>{await cdp('Input.dispatchMouseEvent',{type:'mousePressed',x,y,button:'left',clickCount:1});await cdp('Input.dispatchMouseEvent',{type:'mouseReleased',x,y,button:'left',clickCount:1});await wait(1500);};
if(process.env.LUMEN_MIDNIGHT==='1') {
await cdp('Input.dispatchMouseEvent',{type:'mouseWheel',x:300,y:700,deltaX:0,deltaY:1370});
await wait(1500);
const shelf=await cdp('Page.captureScreenshot',{format:'png'});
await writeFile('artifacts/web-autoplay-midnight-shelf.png',Buffer.from(shelf.data,'base64'));
if(process.env.LUMEN_SCREENSHOT_ONLY==='1') { console.log('Captured midnight shelf'); }
else { await click(300,650); await wait(1000);
const home=await cdp('Page.captureScreenshot',{format:'png'});
await writeFile('artifacts/web-autoplay-midnight-home.png',Buffer.from(home.data,'base64'));
await click(300,456);
await wait(6000);
const events=await evaluate('window.__audioEvents');
console.log('Midnight attempts:',JSON.stringify(events));
assert.ok(events.some(e=>e.status==='started' && e.url.includes('midnight_opening.mp3') && /[?&]v=[0-9a-f]{64}/.test(e.url)),'Elias opening did not autoplay with its recording version');
assert.ok(!events.some(e=>e.status==='rejected'),'Midnight playback was rejected');
console.log('PASS: The Midnight Invitation autoplays its opening recording.');
}
} else if(process.env.LUMEN_POSTCARD==='1') {
await click(290,255); // postcard collection on shelf
const card=await cdp('Page.captureScreenshot',{format:'png'});
await writeFile('artifacts/web-autoplay-card-collection.png',Buffer.from(card.data,'base64'));
if(process.env.LUMEN_SCREENSHOT_ONLY==='1'){console.log('Captured postcard collection');} else {
await click(300,750); // collected card action
await wait(6000);
const events=await evaluate('window.__audioEvents');
console.log('Postcard attempts:',JSON.stringify(events));
assert.ok(events.some(e=>e.status==='started' && e.url.includes('washing-line.mp3')),'Postcard did not autoplay its recording');
assert.ok(!events.some(e=>e.status==='rejected'),'Postcard playback was rejected');
console.log('PASS: actual Flutter web autoplays a collected postcard.');
}
process.exitCode=0;
} else {
await click(300,600); // Mara book on shelf
const image=await cdp('Page.captureScreenshot',{format:'png'});
await writeFile('artifacts/web-autoplay-after-book.png',Buffer.from(image.data,'base64'));
if(process.env.LUMEN_SCREENSHOT_ONLY==='1'){console.log('Captured book screen');process.exitCode=0;}
else {
await click(300,706); // open notebook action
await wait(6000);
const events=await evaluate('window.__audioEvents');
console.log('Playback attempts:',JSON.stringify(events));
assert.ok(events.some(e=>e.status==='started' && /[?&]v=[0-9a-f]{64}/.test(e.url)),'No versioned recording started after opening a book');
assert.ok(!events.some(e=>e.status==='rejected'),'A browser playback request was rejected');
const reading = await cdp('Page.captureScreenshot',{format:'png'});
await writeFile('artifacts/web-autoplay-first-reading.png',Buffer.from(reading.data,'base64'));
await click(390,830); // next leaf
await wait(6000);
const afterTurn=await evaluate('window.__audioEvents');
console.log('After turning:',JSON.stringify(afterTurn));
assert.ok(afterTurn.some(e=>e.status==='started' && e.url.includes('narration_cottage_window.mp3')),'Next leaf did not autoplay its own recording');
assert.ok(!afterTurn.some(e=>e.status==='rejected'),'A page-turn playback request was rejected');
console.log('PASS: actual Flutter web autoplays distinct recordings after opening and turning a leaf.');
}
}
} finally {ws?.close();browser.kill('SIGTERM');await wait(500);await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:100});}
+84
View File
@@ -0,0 +1,84 @@
// Exercise the real HTML audio bridge under Chromium's strict gesture policy.
import {spawn} from 'node:child_process';
import {createServer} from 'node:http';
import {mkdtemp, readFile, rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import assert from 'node:assert/strict';
const root = process.cwd();
const chrome = process.env.CHROME_BIN || '/home/ubuntu/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome';
const sleep = ms => new Promise(r => setTimeout(r, ms));
const server = createServer(async (req,res) => {
try {
if (req.url === '/') { res.setHeader('Content-Type','text/html'); res.end('<!doctype html><button id="tap">Tap</button><script src="/narration.js"></script>'); return; }
const path = req.url === '/narration.js' ? join(root,'web/narration.js') : join(root,'build/web',decodeURIComponent(req.url.slice(1)));
const data = await readFile(path);
res.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'audio/mpeg');
res.setHeader('Accept-Ranges','bytes');
const range = req.headers.range?.match(/bytes=(\d+)-(\d*)/);
if (range) {
const start=Number(range[1]), end=range[2] ? Math.min(Number(range[2]),data.length-1) : data.length-1;
res.writeHead(206, {'Content-Range': `bytes ${start}-${end}/${data.length}`, 'Content-Length': end-start+1});
res.end(data.subarray(start,end+1));
} else { res.setHeader('Content-Length',data.length); res.end(data); }
} catch (_) { res.writeHead(404); res.end(); }
});
await new Promise(r => server.listen(0,'127.0.0.1',r));
const port=server.address().port;
const debugServer=createServer();
await new Promise(r => debugServer.listen(0,'127.0.0.1',r));
const debugPort=debugServer.address().port;
await new Promise(r => debugServer.close(r));
const profile=await mkdtemp(join(tmpdir(),'lumen-chrome-'));
const browser=spawn(chrome,['--headless=new','--no-sandbox','--disable-dev-shm-usage','--disable-gpu',
'--autoplay-policy=user-gesture-required','--remote-allow-origins=*',`--remote-debugging-port=${debugPort}`,
`--user-data-dir=${profile}`,'about:blank'],{stdio:'ignore'});
let ws;
try {
let target;
for (let i=0;i<100;i++) {
try {
const result=await fetch(`http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(`http://127.0.0.1:${port}/`)}`,{method:'PUT'});
if (result.ok) {target=await result.json();break;}
} catch (_) {}
await sleep(100);
}
assert.ok(target,'Chromium failed to start');
ws=new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve,reject)=>{ws.onopen=resolve;ws.onerror=reject;});
let id=0; const pending=new Map();
ws.onmessage=event=>{const message=JSON.parse(event.data);if(message.id&&pending.has(message.id)){const p=pending.get(message.id);pending.delete(message.id);message.error?p.reject(Error(message.error.message)):p.resolve(message.result);}};
const cdp=(method,params={})=>new Promise((resolve,reject)=>{const n=++id;pending.set(n,{resolve,reject});ws.send(JSON.stringify({id:n,method,params}));});
const evaluate=async expression=>{const out=await cdp('Runtime.evaluate',{expression,awaitPromise:true,returnByValue:true});if(out.exceptionDetails)throw Error(out.exceptionDetails.text+': '+JSON.stringify(out.exceptionDetails.exception));return out.result.value;};
await cdp('Page.enable');
for(let i=0;i<100;i++){if(await evaluate("document.readyState === 'complete' && !!window.lumenNarration"))break;await sleep(100);}
const first=`http://127.0.0.1:${port}/assets/assets/postcards/audio/washing-line.mp3`;
const second=`http://127.0.0.1:${port}/assets/assets/postcards/audio/bakery-door.mp3`;
await evaluate('window.a=lumenNarration.create(()=>{});window.b=lumenNarration.create(()=>{});');
const blocked=await evaluate(`lumenNarration.play(a,${JSON.stringify(first)},1,true).then(()=>false,()=>true)`);
assert.equal(blocked,true,'Chromium must enforce gesture policy in this test');
await cdp('Input.dispatchMouseEvent',{type:'mousePressed',x:20,y:20,button:'left',clickCount:1});
await cdp('Input.dispatchMouseEvent',{type:'mouseReleased',x:20,y:20,button:'left',clickCount:1});
await sleep(3000);
await evaluate(`lumenNarration.play(a,${JSON.stringify(first)},1,true)`);
await sleep(1200);
assert.equal(await evaluate('lumenNarration.playing(a)'),true,'first reading did not play');
assert.ok(await evaluate('lumenNarration.position(a)')>300,'first reading did not advance');
await evaluate('lumenNarration.stop(a)');
await sleep(100);
await evaluate(`lumenNarration.play(a,${JSON.stringify(second)},1,true)`);
await sleep(1200);
assert.equal(await evaluate('lumenNarration.playing(a)'),true,'next reading did not autoplay');
assert.ok(await evaluate('lumenNarration.position(a)')>300,'next reading did not advance');
await evaluate('lumenNarration.pause(a)');
assert.equal(await evaluate('lumenNarration.playing(a)'),false,'pause did not stop playback');
await evaluate(`lumenNarration.play(b,${JSON.stringify(first)},1,true)`);
await sleep(500);
assert.equal(await evaluate('lumenNarration.playing(b)'),true,'second narrator was not unlocked');
await evaluate('lumenNarration.dispose(a);lumenNarration.dispose(b)');
console.log('PASS: blocked before gesture; after one tap, both narrators play, advance, change tracks and pause.');
} finally {
ws?.close(); browser.kill('SIGTERM'); server.close();
await sleep(500); await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:100});
}