Files
logic-puzzle/scripts/render_narration.py
T
Hadrian Burkhardt 68871ec573 Expand narrated story, preserve solved patterns, and add ambience
Connect the island story with new character memories and narrative transitions.
Blend each solved symbol into its artwork and retain a replayable pattern stamp.
Allow completed grids to be inspected after navigation and app restarts.
Reduce campaign difficulty spikes and keep explained story hints free.

Append 24 narrated continuations while preserving original PCM takes. Add
four offline environmental loops with saved mute/volume controls, scene
fades, narration ducking and lifecycle handling.

Validation: 31 unit/widget tests, Flutter analysis, narration and soundscape
asset checks, tablet discovery layouts and extended-audio integration,
including simultaneous active voice and ambience mixer tracks.
2026-11-02 05:04:57 +01:00

93 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""Prepare WAV masters, runtime WAVs and archival FLACs; playback never synthesizes speech."""
import argparse, hashlib, importlib.metadata, json, subprocess, shutil
from pathlib import Path
import numpy as np
import soundfile as sf
import onnxruntime as ort
import espeakng_loader
from kokoro_onnx import Kokoro
from kokoro_onnx.config import EspeakConfig
parser=argparse.ArgumentParser()
parser.add_argument('--model',type=Path,required=True)
parser.add_argument('--voices',type=Path,required=True)
parser.add_argument('--voice',default='bf_emma')
parser.add_argument('--speed',type=float,default=.82)
parser.add_argument('--speaker', help='Render only this speaker, preserving all other recordings')
parser.add_argument('--append-continuations', action='store_true', help='Preserve existing takes and append the new narrator passages')
parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1])
a=parser.parse_args()
source=a.root/'assets/narration';raw=a.root/'assets/audio'
(source/'wav').mkdir(parents=True,exist_ok=True);raw.mkdir(parents=True,exist_ok=True)
options=ort.SessionOptions();options.intra_op_num_threads=4;options.inter_op_num_threads=1
session=ort.InferenceSession(str(a.model),sess_options=options,providers=['CPUExecutionProvider'])
session.disable_fallback()
config=EspeakConfig(lib_path=str(espeakng_loader.get_library_path()),data_path=str(espeakng_loader.get_data_path()))
engine=Kokoro.from_session(session,str(a.voices),espeak_config=config)
previous=json.loads((source/'manifest.json').read_text()) if (source/'manifest.json').exists() else {}
tracks=dict(previous.get('tracks',{})) if a.speaker or a.append_continuations else {}
for record in json.loads((source/'scripts.json').read_text()):
if a.speaker and record.get('speaker')!=a.speaker: continue
old=tracks.get(record['pageId'])
if a.append_continuations:
if old and old['text']==record['text']:
assert old['wavSha256']==hashlib.sha256((source/'wav'/old['file']).read_bytes()).hexdigest()
continue
assert old and old['text']==record['baseText'], f"Cannot append to stale take: {record['pageId']}"
paragraphs=[]
text=record['continuation'] if a.append_continuations else record.get('baseText',record['text'])
for part in text.split('\n\n'):
if paragraphs and len(part)<45:paragraphs[-1]+='\n\n'+part
elif paragraphs and len(paragraphs[-1])<45:paragraphs[-1]+='\n\n'+part
else:paragraphs.append(part)
rate=24000;pieces=[np.zeros(int(rate*.18),dtype=np.float32)];frames=len(pieces[0]);cues=[]
if a.append_continuations:
original,_=sf.read(source/'wav'/old['file'],dtype='int16')
master,master_rate=sf.read(source/'wav'/old['file'],dtype='float32')
assert master_rate==rate
pieces=[master,np.zeros(int(rate*.18),dtype=np.float32)];frames=sum(len(p) for p in pieces)
cues=[{**c,'speaker':c.get('speaker',record['speaker'])} for c in old['cues']]
sections=[(part,'Narrator' if a.append_continuations else record['speaker']) for part in paragraphs]
if not a.append_continuations and record.get('continuation'):
sections.extend((part,'Narrator') for part in record['continuation'].split('\n\n'))
for number,(part,speaker) in enumerate(sections,1):
print(f"Rendering {record['pageId']} · {number}/{len(sections)}",flush=True)
voice='bm_george' if speaker=='Narrator' else record.get('voice',a.voice)
speed=.88 if speaker=='Narrator' else record.get('speed',a.speed)
samples,sample_rate=engine.create(part.replace('\n',' '),voice=voice,speed=speed,lang='en-gb',sentence_pause=.38,clause_pause=.14)
assert sample_rate==rate
samples=np.asarray(samples,dtype=np.float32).reshape(-1)
assert len(samples)>rate*.3 and np.isfinite(samples).all()
fade=min(240,len(samples)//4)
samples[:fade]*=np.linspace(0,1,fade);samples[-fade:]*=np.linspace(1,0,fade)
peak=float(np.max(np.abs(samples)));assert peak>.01
samples*=.86/peak
start=frames;pieces.append(samples);frames+=len(samples)
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part,'speaker':speaker})
pause=np.zeros(int(rate*.60),dtype=np.float32);pieces.append(pause);frames+=len(pause)
audio=np.concatenate(pieces);peak=float(np.max(np.abs(audio)));assert peak>.01
assert peak<1
wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac"
sf.write(wav,audio,rate,subtype='PCM_16')
shutil.copyfile(wav,raw/wav.name)
subprocess.run(['ffmpeg','-v','error','-y','-i',str(wav),'-c:a','flac','-compression_level','8',str(flac)],check=True)
decoded,check_rate=sf.read(flac,dtype='int16');master,_=sf.read(wav,dtype='int16')
assert check_rate==rate and np.array_equal(decoded,master)
tracks[record['pageId']]={**record,'file':wav.name,'flacFile':flac.name,'wavSha256':hashlib.sha256(wav.read_bytes()).hexdigest(),'sampleRate':rate,'channels':1,'frames':len(audio),
'durationMs':round(len(audio)*1000/rate),'textSha256':hashlib.sha256(record['text'].encode()).hexdigest(),
'flacSha256':hashlib.sha256(flac.read_bytes()).hexdigest(),'cues':cues}
if a.append_continuations:
output,_=sf.read(wav,dtype='int16')
assert np.array_equal(output[:len(original)],original),'Original take changed while appending'
tracks[record['pageId']]['originalFrames']=len(original)
tracks[record['pageId']]['originalPcmSha256']=hashlib.sha256(original.tobytes()).hexdigest()
print(f"Saved {wav.name}: {len(audio)/rate:.1f}s; lossless FLAC verified",flush=True)
manifest={'voice':a.voice,'speed':a.speed,'language':'en-gb','method':'Synthetic narration rendered during development; bundled file playback only.',
'speakers':{'Mara':{'voice':'bf_emma','speed':.82},'Narrator':{'voice':'bm_george','speed':.88}},
'modelSha256':hashlib.sha256(a.model.read_bytes()).hexdigest(),'voicesSha256':hashlib.sha256(a.voices.read_bytes()).hexdigest(),
'packages':{p:importlib.metadata.version(p) for p in ['kokoro-onnx','onnxruntime','soundfile','espeakng-loader']},'tracks':tracks}
(source/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
(raw/'narration_manifest.json').write_text(json.dumps({'tracks':tracks},ensure_ascii=False,indent=2)+'\n')
print(f'{len(tracks)} narration masters and runtime assets prepared.',flush=True)