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