File size: 3,786 Bytes
adabee1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | #!/usr/bin/env python3
"""Render each JSONL phrase with one loaded Danish tiny-voca checkpoint."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import time
import soundfile as sf
import torch
from tiny_voca.infer import load_model, match_frontend, speak
from wav_output import scale_for_wav
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--checkpoint', type=Path, required=True)
p.add_argument('--set', type=Path, required=True)
p.add_argument('--output', type=Path, required=True)
p.add_argument('--voice', default='DA1')
p.add_argument('--device', default='cpu')
args = p.parse_args()
rows = [json.loads(line) for line in args.set.read_text(encoding='utf-8').split('\n') if line.strip()]
if not rows or len({str(r['id']) for r in rows}) != len(rows):
raise SystemExit('Expected a nonempty set with unique IDs.')
for row in rows:
identifier = str(row['id'])
if Path(identifier).name != identifier or identifier in ('.', '..'):
raise SystemExit(f'Unsafe ID: {identifier!r}')
if row.get('lang', 'da') != 'da' or not str(row['text']).strip():
raise SystemExit(f'Invalid Danish phrase: {identifier}')
if args.output.exists() and any(args.output.iterdir()):
raise SystemExit('Use a new or empty output directory to avoid mixing checkpoints.')
args.output.mkdir(parents=True, exist_ok=True)
match_frontend(args.checkpoint)
model = load_model(args.checkpoint, args.device)
if model.config.language != 'da':
raise SystemExit('This renderer expects a Danish checkpoint.')
report = {'checkpoint': str(args.checkpoint.resolve()),
'checkpoint_sha256': hashlib.sha256(args.checkpoint.read_bytes()).hexdigest(),
'set': str(args.set.resolve()), 'set_sha256': hashlib.sha256(args.set.read_bytes()).hexdigest(),
'device': args.device, 'voice': args.voice, 'sample_rate': model.config.sample_rate,
'file_output_gain': 'min(1, 0.99/raw_peak); uniform gain only; no clipping or quiet-audio boost',
'complete': False, 'clips': []}
report_path = args.output / 'render.json'
try:
with torch.inference_mode():
for row in rows:
if args.device.startswith('cuda'):
torch.cuda.synchronize()
started = time.perf_counter()
wave, phones, _ = speak(model, row['text'], args.voice, seed=0)
if args.device.startswith('cuda'):
torch.cuda.synchronize()
elapsed = time.perf_counter() - started
if phones.unknown:
raise ValueError(f"Unknown phones for {row['id']}: {phones.unknown}")
output = args.output / (str(row['id']) + '.wav')
output_wave, gain_report = scale_for_wav(wave.numpy())
sf.write(output, output_wave, model.config.sample_rate, subtype='FLOAT')
seconds = len(wave) / model.config.sample_rate
report['clips'].append({'id': row['id'], 'text': row['text'],
'seconds': seconds, 'synthesis_seconds': elapsed,
'rtf': elapsed / seconds if seconds else None,
**gain_report,
'phones': list(phones.symbols)})
print(f"{row['id']}: {seconds:.3f}s -> {output}", flush=True)
report['complete'] = True
finally:
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + '\n', encoding='utf-8')
if __name__ == '__main__':
main()
|