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

257 lines
12 KiB
Python

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