File size: 4,071 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 76 77 78 79 80 | """Render a phrase set twice: tiny-voca's built-in source-filter output ("dsp") and the
same synthesis re-voiced by a tiny_voca.vocoder checkpoint ("vocoded").
Usage (kit or kit-v3 image, matching the voice model's frontend):
python scripts/render_pair.py --checkpoint models/x.pt --vocoder runs/vocoder-da-prior/vocoder.pt \
--set probes_da.jsonl --output out/pair-x
Uses the same code path as `python -m tiny_voca.infer --vocoder`. Output WAVs get one
uniform gain min(1, 0.99/peak), like render_set.py.
"""
import argparse
import json
import sys
from pathlib import Path
import soundfile as sf
import torch
sys.path.insert(0, '/opt/kit')
from tiny_voca.infer import load_model, match_frontend, phonemize, speak, vocode # noqa: E402
from tiny_voca.vocoder import load_vocoder # noqa: E402
from copy_synth import with_high_band # noqa: E402 (scripts/ is sys.path[0])
def cap_edges(model, frames):
"""Limit the predicted <bos>/<eos> pause to `frames` frames. CoRal clips start with
0.3-1.2 s of breath/room noise before speech (median 0.78 s), and the model learned it."""
probe = phonemize('a', model.config.profile)
edges = torch.tensor([probe.ids[probe.symbols.index(s)] for s in ('<bos>', '<eos>')])
original = model.predict_durations
def predict(hidden, mask, tokens, speed=1.0):
durations = original(hidden, mask, tokens, speed)
return torch.where(torch.isin(tokens, edges.to(tokens.device)), durations.clamp(max=frames), durations)
model.predict_durations = predict
def scaled(wave):
peak = float(wave.abs().max())
return (wave * min(1.0, 0.99 / peak) if peak > 0 else wave).numpy()
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--checkpoint', type=Path, required=True)
p.add_argument('--vocoder', 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('--max-edge-frames', type=int, help='cap the leading/trailing pause (10 ms frames)')
p.add_argument('--high-hz', type=float, help="override the vocoder prior's high-band start (inference sweep)")
p.add_argument('--high-gain', type=float, help="override the vocoder prior's high-band pulse share")
args = p.parse_args()
rows = [json.loads(l) for l in args.set.read_text(encoding='utf-8').splitlines() if l.strip()]
for sub in ('dsp', 'vocoded'):
(args.output / sub).mkdir(parents=True, exist_ok=True)
match_frontend(args.checkpoint)
model = load_model(args.checkpoint, 'cpu')
vocoder = load_vocoder(args.vocoder)
if args.high_hz is not None or args.high_gain is not None:
vocoder = with_high_band(vocoder, args.high_hz if args.high_hz is not None else vocoder.config.prior_high_hz or 2500.0,
args.high_gain if args.high_gain is not None else vocoder.config.prior_high_gain)
if args.max_edge_frames is not None:
cap_edges(model, args.max_edge_frames)
report = {'checkpoint': str(args.checkpoint), 'vocoder': str(args.vocoder), 'set': str(args.set),
'max_edge_frames': args.max_edge_frames, 'high_hz': args.high_hz, 'high_gain': args.high_gain, 'clips': []}
with torch.inference_mode():
for row in rows:
wave, phones, details = speak(model, row['text'], args.voice, seed=0)
voiced = vocode(model, wave, details, vocoder, args.voice)
sf.write(args.output / 'dsp' / f"{row['id']}.wav", scaled(wave), model.config.sample_rate, subtype='PCM_16')
sf.write(args.output / 'vocoded' / f"{row['id']}.wav", scaled(voiced), model.config.sample_rate, subtype='PCM_16')
report['clips'].append({'id': row['id'], 'text': row['text'], 'phones': list(phones.symbols)})
(args.output / 'render.json').write_text(json.dumps(report, ensure_ascii=False, indent=2))
print(f"rendered {len(rows)} phrases -> {args.output}/{{dsp,vocoded}}")
if __name__ == '__main__':
main()
|