Files
2026-11-14 08:55:48 +01:00

76 lines
3.9 KiB
Python

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