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

140 lines
7.3 KiB
Python

#!/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)