Rise
The Vieneo Province
Loading...
Searching...
No Matches
erin_profile.py
Go to the documentation of this file.
1"""Create one Erin voice from the full, archived collection of original recordings."""
2import hashlib
3import json
4import os
5from pathlib import Path
6
7import numpy as np
8import soundfile as sf
9from scipy.signal import resample_poly
10from math import gcd
11
12PROMPT_SOURCES = [
13 'source_samples/Erin/goodmorningjason.wav',
14 'source_samples/E-10/monroe-tiaditcb.wav',
15 'source_samples/Erin/utilizingexternalpower.wav',
16 'source_samples/E-10/monroe-amc.wav',
17 'source_samples/Erin/cuttingpowertointernals.wav',
18 'source_samples/E-10/CabinPressure.wav',
19]
20
21
22def _atomic_json(path, value):
23 temporary = path.with_name(path.name + '.new')
24 temporary.write_text(json.dumps(value, indent=2), encoding='utf-8')
25 os.replace(temporary, path)
26
27
28def _write_wav(path, samples, rate):
29 temporary = path.with_name(path.stem + '.new.wav')
30 sf.write(temporary, samples, rate, subtype='PCM_16')
31 os.replace(temporary, path)
32
33
35 """Use the archived original inventory, never newly generated VMU speech."""
36 rows = json.loads((root/'sample_inventory.json').read_text(encoding='utf-8'))
37 if len(rows) != 145 or len({r['copy'] for r in rows}) != 145:
38 raise ValueError('Expected all 145 distinct original recordings.')
39 clips, segments, parts = {}, [], []
40 cursor, rate = 0, 22050
41 for row in rows:
42 name = row['copy'].replace('\\', '/')
43 path = (root/name).resolve()
44 if not path.is_relative_to((root/'source_samples').resolve()):
45 raise ValueError(f'Invalid source path: {name}')
46 # Verify originals against the original PCM hash before processing.
47 import wave
48 with wave.open(str(path), 'rb') as wav:
49 pcm = wav.readframes(wav.getnframes())
50 if hashlib.sha256(pcm).hexdigest() != row['pcm_sha256']:
51 raise ValueError(f'Original recording changed: {name}')
52 samples, source_rate = sf.read(path, dtype='float32', always_2d=True)
53 samples = samples.mean(axis=1)
54 if source_rate != rate:
55 factor = gcd(source_rate, rate)
56 samples = resample_poly(samples, rate//factor, source_rate//factor)
57 samples -= samples.mean()
58 peak = float(np.max(np.abs(samples)))
59 rms = float(np.sqrt(np.mean(samples*samples)))
60 if not np.isfinite(samples).all() or peak < 1e-6:
61 raise ValueError(f'Invalid or empty audio: {name}')
62 samples *= min(10**(-23/20)/max(rms, 1e-8), .85/peak)
63 fade = min(66, len(samples)//10)
64 samples[:fade] *= np.linspace(0, 1, fade)
65 samples[-fade:] *= np.linspace(1, 0, fade)
66 if parts:
67 gap = np.zeros(round(.10*rate), dtype=np.float32)
68 parts.append(gap)
69 cursor += len(gap)
70 start = cursor
71 parts.append(samples)
72 cursor += len(samples)
73 clips[name] = samples
74 segments.append(dict(source=name, group=row['group'], start_frame=start,
75 end_frame=cursor, original_pcm_sha256=row['pcm_sha256']))
76 prompt_parts = []
77 for name in PROMPT_SOURCES:
78 if prompt_parts:
79 prompt_parts.append(np.zeros(round(.16*rate), dtype=np.float32))
80 prompt_parts.append(clips[name])
81 prompt = np.concatenate(prompt_parts)
82 if not 5 < len(prompt)/rate <= 10:
83 raise ValueError('The shared style reference must fit the engine\'s ten-second limit.')
84 references = root/'references'
85 references.mkdir(exist_ok=True)
86 _write_wav(references/'Erin.wav', prompt, rate)
87 _write_wav(references/'Erin_All_Recordings.wav', np.concatenate(parts), rate)
88 profiles = {'Erin': dict(reference='references/Erin.wav',
89 reference_seconds=round(len(prompt)/rate, 6), style_sources=PROMPT_SOURCES,
90 corpus_reference='references/Erin_All_Recordings.wav', corpus_sample_rate=rate,
91 sources=[segment['source'] for segment in segments], segments=segments,
92 source_count=len(segments),
93 aggregation='equal mean of normalized per-recording embeddings in both speaker encoders')}
94 _atomic_json(root/'profiles.json', profiles)
95 return profiles
96
97
98def build_voice_profile(root, model):
99 """Every original contributes to both speaker identity vectors; only one voice is saved."""
100 import torch
101 import torch.nn.functional as F
102 profile = json.loads((root/'profiles.json').read_text(encoding='utf-8'))['Erin']
103 corpus, rate = sf.read(root/profile['corpus_reference'], dtype='float32')
104 if rate != profile['corpus_sample_rate'] or corpus.ndim != 1:
105 raise ValueError('Unexpected corpus format.')
106 clips = []
107 previous_end = 0
108 for segment in profile['segments']:
109 start, end = segment['start_frame'], segment['end_frame']
110 if not previous_end <= start < end <= len(corpus):
111 raise ValueError('Invalid corpus boundaries.')
112 previous_end = end
113 samples = corpus[start:end]
114 factor = gcd(rate, 16000)
115 samples = resample_poly(samples, 16000//factor, rate//factor).astype(np.float32)
116 clips.append(samples)
117 if len(clips) != 145 or len(clips) != profile['source_count']:
118 raise ValueError('The profile must include all 145 original recordings.')
119 if {s['source'] for s in profile['segments']} != set(profile['sources']):
120 raise ValueError('Source coverage mismatch.')
121 print(f'Building Erin from all {len(clips)} original recordings...', flush=True)
122 with torch.inference_mode():
123 model.prepare_conditionals(str(root/profile['reference']))
124 utterance_embeddings = model.ve.embeds_from_wavs(clips, sample_rate=16000,
125 as_spk=False, batch_size=32)
126 speaker = model.ve.utt_to_spk_embed(utterance_embeddings)
127 model.conds.t3.speaker_emb = torch.from_numpy(speaker).unsqueeze(0).to(model.device)
128 decoder_embeddings = []
129 # Process separately so padding of short phrases cannot bias the vectors.
130 for index, samples in enumerate(clips, 1):
131 vector = model.s3gen.speaker_encoder.inference(
132 torch.from_numpy(samples).unsqueeze(0).to(model.device))
133 decoder_embeddings.append(F.normalize(vector, dim=1))
134 if index % 25 == 0 or index == len(clips):
135 print(f'Encoded {index}/{len(clips)} recordings.', flush=True)
136 all_decoder = torch.cat(decoder_embeddings)
137 model.conds.gen['embedding'] = F.normalize(all_decoder.mean(dim=0, keepdim=True), dim=1)
138 assert utterance_embeddings.shape[0] == all_decoder.shape[0] == 145
139 assert torch.isfinite(model.conds.t3.speaker_emb).all()
140 assert torch.isfinite(model.conds.gen['embedding']).all()
141 voices = root/'voices'
142 voices.mkdir(exist_ok=True)
143 temporary = voices/'Erin.new.pt'
144 model.conds.save(temporary)
145 os.replace(temporary, voices/'Erin.pt')
146 report = dict(voice='Erin', original_recordings=145,
147 source_groups={group:sum(s['group']==group for s in profile['segments'])
148 for group in sorted({s['group'] for s in profile['segments']})},
149 t3_recordings_encoded=int(utterance_embeddings.shape[0]),
150 decoder_recordings_encoded=int(all_decoder.shape[0]),
151 aggregation=profile['aggregation'],
152 corpus_sha256=hashlib.sha256((root/profile['corpus_reference']).read_bytes()).hexdigest(),
153 voice_sha256=hashlib.sha256((voices/'Erin.pt').read_bytes()).hexdigest())
154 _atomic_json(root/'profile-build.json', report)
155 print(json.dumps(report, indent=2), flush=True)
156
157
158if __name__ == '__main__':
159 import argparse
160 parser = argparse.ArgumentParser(description=__doc__)
161 parser.add_argument('--prepare-references', action='store_true')
162 args = parser.parse_args()
163 if not args.prepare_references:
164 parser.error('Use --prepare-references to recreate references from the archived originals; use erin.py --setup to build the voice.')
165 prepare_references(Path(__file__).resolve().parent)
SCRIPT_CONTROL SCRIPT_STATE const void int
_atomic_json(path, value)
build_voice_profile(root, model)
prepare_references(root)
_write_wav(path, samples, rate)