Download recipe/scripts/make_pairs.py from gowombat/tiny-voca-da: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/scripts/make_pairs.py
- Command line
-
hf download hf://gowombat/tiny-voca-da/recipe/scripts/make_pairs.py
-
curl -L -o make_pairs.py https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/scripts/make_pairs.py
5.85 kB
| """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() | |