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
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}')
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)
67 gap = np.zeros(round(.10*rate), dtype=np.float32)
72 cursor += len(samples)
74 segments.append(dict(source=name, group=row[
'group'], start_frame=start,
75 end_frame=cursor, original_pcm_sha256=row[
'pcm_sha256']))
77 for name
in PROMPT_SOURCES:
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')}
99 """Every original contributes to both speaker identity vectors; only one voice is saved."""
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.')
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.')
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 = []
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())
155 print(json.dumps(report, indent=2), flush=
True)