File size: 5,366 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | """Teacher-forced synthesis next to copy synthesis, for the same validation recordings.
The voice model runs with each recording's own durations, pitch, voicing and energy (the
tiny_voca.vocoder_pairs path, voicing passed as in training), and its source-filter waveform
is voiced by a tiny_voca.vocoder. The same vocoder also re-voices the recording's own
spectrogram (copy synthesis). Pulse locking on the outputs splits the remaining buzz:
copy -> the vocoder's share;
tf_vocoded -> plus the voice model's spectrum (pitch and timing are the recording's);
free-running TTS (render_pair) -> plus the predicted prosody.
Usage (kit-v3 image, CPU):
python scripts/tf_synth.py --checkpoint models/v3trim-en-gan-s100000.pt \
--vocoder models/vocoder-da-hb-s80000.pt \
--annotations data/v3trim-prepared/annotations/validation.jsonl --ids out/val120.jsonl \
--output out/tf-v3trim-s100000-vochb80k
Writes <output>/{real,copy,tf_dsp,tf_vocoded}/<id>.wav (FLOAT) and tf.json.
"""
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.data import AnnotatedDataset, collate # noqa: E402
from tiny_voca.infer import load_model, match_frontend # noqa: E402
from tiny_voca.losses import VocosMel # 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 main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--checkpoint', type=Path, required=True)
p.add_argument('--vocoder', type=Path, required=True)
p.add_argument('--annotations', type=Path, required=True)
p.add_argument('--ids', type=Path, help='jsonl whose ids select the clips (default: all)')
p.add_argument('--output', type=Path, required=True)
p.add_argument('--high-hz', type=float)
p.add_argument('--high-gain', type=float)
p.add_argument('--voiced-vowels', action='store_true',
help='mark every vowel frame voiced, as training targets and free-running TTS do (default: recorded voicing)')
args = p.parse_args()
match_frontend(str(args.checkpoint))
model = load_model(str(args.checkpoint), 'cpu').eval()
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)
features = VocosMel()
dataset = AnnotatedDataset([str(args.annotations)], model.config, cache=False, voiced_vowels=args.voiced_vowels)
keep = None
if args.ids:
keep = {json.loads(l)['id'] for l in args.ids.read_text(encoding='utf-8').splitlines() if l.strip()}
subs = ('real', 'copy', 'tf_dsp', 'tf_vocoded')
for sub in subs:
(args.output / sub).mkdir(parents=True, exist_ok=True)
hop, rate, done = model.config.hop, model.config.sample_rate, []
with torch.inference_mode():
for index, row in enumerate(dataset.rows):
if keep is not None and row['id'] not in keep:
continue
batch = collate([dataset[index]], 'cpu')
prosody = batch['prosody']
hidden, mask = model.encode(batch['tokens'], batch['stress'], batch['token_lengths'], batch['speakers'],
batch.get('emotions'), batch.get('intensities'))
frames, frame_mask, lengths = model.expand(hidden, batch['durations'], mask, batch['speakers'],
batch.get('emotions'), batch.get('intensities'))
prosody_hidden, _ = model.predict_prosody(frames, frame_mask)
acoustic = model.decode(prosody_hidden, prosody, frame_mask)
torch.manual_seed(0)
dsp = model.vocoder(acoustic, model.frequency(prosody[..., 0]), lengths, voiced=prosody[..., 1])[0]
count = int(lengths[0])
real = batch['wave'][0, :count * hop].float()
f0 = model.frequency(prosody[0, :count, 0])[None].float()
voiced = (prosody[0, :count, 1] > 0.5).float()[None]
outputs = {'real': real, 'tf_dsp': dsp[:count * hop]}
for name, source in (('copy', real), ('tf_vocoded', dsp[:count * hop])):
torch.manual_seed(0)
mel = features(source[None]).transpose(1, 2)
outputs[name] = vocoder(mel, f0, voiced)[0, :count * hop]
for name in subs:
sf.write(args.output / name / f"{row['id']}.wav", outputs[name].numpy(), rate, subtype='FLOAT')
done.append(row['id'])
(args.output / 'tf.json').write_text(json.dumps({'checkpoint': str(args.checkpoint), 'vocoder': str(args.vocoder),
'annotations': str(args.annotations), 'high_hz': args.high_hz,
'high_gain': args.high_gain, 'voiced_vowels': args.voiced_vowels, 'clips': done}, indent=2))
print(f'teacher-forced {len(done)} clips -> {args.output}/{{{",".join(subs)}}}')
if __name__ == '__main__':
main()
|