File size: 5,848 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
96
97
98
99
100
101
"""Vocoder pairs that match free-running TTS voicing (variant of tiny_voca.vocoder_pairs).

Free-running TTS marks every vowel frame voiced (TinyVoca.synthesize voiced_vowels; training
targets do the same). The decoder, the source-filter and the neural vocoder's pulse gate all
see those flags. tiny_voca.vocoder_pairs and train_vocoder use the recorded voicing instead,
where about 26% of this speaker's vowel frames are unvoiced (creak/breath; more at vowel ends).
Teacher-forced tests: forcing those frames voiced raises 1-2 kHz locking 0.53 -> 0.58, the
whole gap to TTS (AGENTS.md Round 4).

Here, for every clip:
  * the voice model runs with the recording's durations/pitch/energy and the vowel-forced
    voicing (decoder conditioning and source-filter voicing, as in training);
  * its Vocos log-mel is stored as float16 (same format as vocoder_pairs);
  * a slim copy of the feature file ({wave, prosody}) is written with prosody[:, 1] set to the
    same forced voicing and prosody[:, 0] to the dataset's continuous pitch curve, and
    pairs.jsonl points at it, so train_vocoder's pulse gate sees TTS voicing on both paired
    and real-spectrogram crops.

Usage (kit-v3 image, GPU or CPU):
  python scripts/make_pairs.py --checkpoint models/v3trim-en-gan-s100000.pt \
      --annotations data/v3trim-prepared/annotations/train.jsonl \
      --output data/vocoder-pairs-v3trim100k-vv/train --device cuda
Resumable: ids already in <output>/pairs.jsonl are skipped.
"""
import argparse
import hashlib
import json
import sys
from pathlib import Path

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


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument('--checkpoint', type=Path, required=True)
    p.add_argument('--annotations', type=Path, nargs='+', required=True)
    p.add_argument('--output', type=Path, required=True)
    p.add_argument('--device', default='cpu')
    p.add_argument('--limit', type=int)
    args = p.parse_args()
    match_frontend(str(args.checkpoint))
    model = load_model(str(args.checkpoint), args.device).eval()
    step = torch.load(args.checkpoint, map_location='cpu', weights_only=True).get('step')
    features = VocosMel().to(args.device)
    dataset = AnnotatedDataset([str(a) for a in args.annotations], model.config, cache=False, voiced_vowels=True)
    (args.output / 'features').mkdir(parents=True, exist_ok=True)
    manifest = args.output / 'pairs.jsonl'
    done = {json.loads(l)['id'] for l in manifest.read_text().splitlines()} if manifest.exists() else set()
    count = len(dataset) if args.limit is None else min(args.limit, len(dataset))
    forced_frames = total_frames = 0
    with open(manifest, 'a') as out, torch.no_grad():
        for index in range(count):
            row = dataset.rows[index]
            if row['id'] in done:
                continue
            item = dataset[index]
            batch = collate([item], args.device)
            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(index)
            wave = model.vocoder(acoustic, model.frequency(prosody[..., 0]), lengths, voiced=prosody[..., 1])
            mel = features(wave)[0].half().cpu()                                   # [frames + 1, bands]
            name = hashlib.sha256(row['id'].encode()).hexdigest()[:24] + '.pt'
            torch.save({'mel': mel}, args.output / name)
            source = (dataset.row_roots[index] / row['path']).resolve()
            stored = torch.load(source, map_location='cpu', weights_only=True)
            recorded = stored['prosody']
            forced = item['prosody'][:, 1].to(recorded.dtype)
            if forced.shape[0] != recorded.shape[0]:
                raise ValueError(f"{row['id']}: {forced.shape[0]} voicing frames vs {recorded.shape[0]} stored")
            forced_frames += int(((forced > 0.5) & (recorded[:, 1] <= 0.5)).sum())
            total_frames += forced.shape[0]
            slim = args.output / 'features' / name
            # Pitch: the dataset's continuous curve (same log(F0/200) units, octave errors cleaned,
            # unvoiced stretches interpolated), so newly voiced frames get a sensible pulse rate.
            pitch = item['prosody'][:, :1].to(recorded.dtype)
            torch.save({'wave': stored['wave'], 'prosody': torch.cat((pitch, forced[:, None], recorded[:, 2:]), 1)}, slim)
            out.write(json.dumps({'id': row['id'], 'speaker': row['speaker'], 'path': str(slim.resolve()),
                                  'pair': str((args.output / name).resolve()), 'recording': str(source),
                                  'frames': row['frames'], 'voice_checkpoint_step': step, 'voicing': 'vowels-forced'}) + '\n')
            if index % 500 == 0:
                out.flush()
                print(json.dumps({'done': index + 1, 'of': count}), flush=True)
    print(json.dumps({'complete': True, 'clips': count, 'manifest': str(manifest),
                      'frames_newly_voiced': forced_frames, 'frames': total_frames}), flush=True)


if __name__ == '__main__':
    main()