#!/usr/bin/env python3 """ build_voice.py Build one Brian voice profile from ALL of his clips, not just a single reference. Chatterbox describes a voice with three things: 1. a voice-identity fingerprint used to choose what to say and how (voice encoder) 2. a voice-identity fingerprint used to render the actual sound (x-vector) 3. a short speech sample that sets delivery, energy and recording sound From one reference clip, (1) and (2) only capture what's in about 10 seconds of audio. This script measures (1) and (2) on every clip you give it (hundreds, across all the videos) and averages them, so the identity reflects Brian across the whole archive. (3) comes from one "anchor" clip you choose, because it sets the delivery style. The result is saved as a voice profile (.pt) that speak.py loads with --voice, which also skips re-processing a reference clip on every run. Usage: python build_voice.py --clips dataset_test refs --anchor refs\\clip1.wav --out voices\\brian.pt """ import os os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1") os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS", "1") import argparse import csv import json import random import sys import time import warnings from datetime import datetime from pathlib import Path warnings.filterwarnings("ignore") import numpy as np import soundfile as sf AUDIO_EXTS = {".wav", ".flac", ".mp3", ".ogg", ".m4a"} S3_SR = 16000 def collect_clips(sources, min_sim): """Gather clip paths with their recording group and optional speaker score.""" clips = [] for src in sources: src = Path(src) if src.is_file() and src.suffix.lower() in AUDIO_EXTS: clips.append({"path": src, "group": src.parent.name, "similarity": None}) continue if not src.is_dir(): print(f" skipping {src}: not found") continue report = src / "report.csv" if report.exists() and (src / "wavs").is_dir(): n = 0 with open(report, newline="", encoding="utf-8") as f: for r in csv.DictReader(f): if r.get("status") != "kept": continue try: similarity = float(r["similarity"]) if similarity < min_sim: continue except (KeyError, ValueError): similarity = None wav = src / "wavs" / f"{r['clip_id']}.wav" if wav.exists(): clips.append({"path": wav, "group": r.get("source") or src.name, "similarity": similarity}) n += 1 print(f" {src}: {n} dataset clips") else: found = sorted(f for f in src.rglob("*") if f.suffix.lower() in AUDIO_EXTS) clips.extend({"path": path, "group": src.name, "similarity": None} for path in found) print(f" {src}: {len(found)} audio files") # de-duplicate while keeping order seen, unique = set(), [] for c in clips: key = str(c["path"].resolve()) if key not in seen: seen.add(key) unique.append(c) return unique def select_balanced(candidates, max_clips, seed=0): """Round-robin across source recordings so one video cannot dominate the profile.""" groups = {} for candidate in candidates: groups.setdefault(candidate["group"], []).append(candidate) rng = random.Random(seed) group_names = sorted(groups) rng.shuffle(group_names) for group in groups.values(): rng.shuffle(group) selected = [] while len(selected) < max_clips: added = False for name in group_names: if groups[name] and len(selected) < max_clips: selected.append(groups[name].pop()) added = True if not added: break return selected def analyze_quality(wav): """Measure speech activity and clipping; these checks cannot identify music or speakers.""" frame_size = int(S3_SR * 0.05) frame_count = len(wav) // frame_size if frame_count == 0: return None framed = wav[:frame_count * frame_size].reshape(frame_count, frame_size) rms = np.sqrt(np.mean(np.square(framed), axis=1) + 1e-12) db = 20 * np.log10(rms + 1e-12) peak_db = float(db.max()) speech_ratio = float(np.mean(db > (peak_db - 35))) if peak_db > -80 else 0.0 clipped_ratio = float(np.mean(np.abs(wav) >= 0.999)) loudness = float(20 * np.log10(np.sqrt(np.mean(np.square(wav)) + 1e-12))) return {"speech_ratio": speech_ratio, "clipped_ratio": clipped_ratio, "loudness_dbfs": loudness} def load_16k(path, min_sec, max_sec): import librosa wav, _ = librosa.load(str(path), sr=S3_SR, mono=True) wav = wav.astype(np.float32) dur = len(wav) / S3_SR if dur < min_sec: return None return wav[: int(max_sec * S3_SR)] def build_voice_profile( model, model_kind, device, sources, anchor, out, max_clips=400, min_sim=0.65, min_sec=2.0, blend=1.0, seed=0, progress=None, ): """Build and save a profile using an already-loaded Chatterbox model.""" import torch import speak anchor = Path(anchor) out = Path(out) if not anchor.is_file(): raise ValueError(f"Anchor clip not found: {anchor}") if sf.info(str(anchor)).duration < 5.5: raise ValueError("The anchor clip must be longer than 5.5 seconds (7-15 s is best).") try: anchor_audio = load_16k(anchor, min_sec, 20.0) except Exception as e: raise ValueError(f"Could not read the anchor clip: {e}") from e anchor_quality = analyze_quality(anchor_audio) if anchor_audio is not None else None if (anchor_quality is None or anchor_quality["speech_ratio"] < 0.55 or anchor_quality["clipped_ratio"] > 0.0005 or anchor_quality["loudness_dbfs"] < -45): raise ValueError("The anchor failed audio quality checks. Choose a clear, audible clip with little silence or clipping.") candidates = collect_clips(sources, min_sim) clips = select_balanced(candidates, max_clips, seed) if len(clips) < 3: raise ValueError("Need at least 3 clips. Select more source clips or prepare more dataset audio.") previous_conds = model.conds profile_tmp = out.with_name(out.name + ".tmp") meta_path = out.with_suffix(".json") meta_tmp = meta_path.with_name(meta_path.name + ".tmp") try: if progress: progress("Preparing the anchor delivery…", 5) speak.prepare_voice(model, model_kind, anchor, exaggeration=0.5) conds = model.conds usable, rejected_quality = [], 0 for i, clip in enumerate(clips, 1): try: wav = load_16k(clip["path"], min_sec, 20.0) except Exception as e: print(f" skipping {clip['path'].name}: {e}") rejected_quality += 1 continue quality = analyze_quality(wav) if wav is not None else None if (quality is None or quality["speech_ratio"] < 0.55 or quality["clipped_ratio"] > 0.0005 or quality["loudness_dbfs"] < -45): rejected_quality += 1 continue similarity = clip["similarity"] match_weight = 0.5 + 0.5 * max(0.0, min(1.0, similarity if similarity is not None else 0.75)) quality_weight = 0.5 + 0.5 * quality["speech_ratio"] usable.append({"wav": wav, "path": clip["path"], "group": clip["group"], "similarity": similarity, "weight": match_weight * quality_weight}) if progress and i % 10 == 0: progress(f"Loading audio clips ({i}/{len(clips)})…", 10 + int(25 * i / len(clips))) if len(usable) < 3: raise ValueError("Fewer than 3 usable clips after loading. Check the selected sources.") weights = torch.tensor([item["weight"] for item in usable], dtype=torch.float32).view(-1, 1) ve_embs, xvecs = [], [] with torch.inference_mode(): for i, item in enumerate(usable, 1): wav_tensor = torch.from_numpy(item["wav"]).unsqueeze(0) ve = model.ve.embeds_from_wavs([item["wav"]], sample_rate=S3_SR, as_spk=True) ve_embs.append(torch.from_numpy(np.asarray(ve, dtype=np.float32)).reshape(1, -1)) x = model.s3gen.speaker_encoder.inference(wav_tensor.to(device)) x = torch.nn.functional.normalize(x.float().cpu(), dim=1) xvecs.append(x) if progress and (i % 10 == 0 or i == len(usable)): progress(f"Measuring voice identity ({i}/{len(usable)} clips)…", 35 + int(55 * i / len(usable))) normalized_weights = weights / weights.sum() ve_emb = torch.nn.functional.normalize( (torch.cat(ve_embs, dim=0) * normalized_weights).sum(dim=0, keepdim=True), dim=1 ) xvec = (torch.cat(xvecs, dim=0) * normalized_weights).sum(dim=0, keepdim=True) used_by_group = {} for item in usable: used_by_group[item["group"]] = used_by_group.get(item["group"], 0) + 1 b = float(np.clip(blend, 0.0, 1.0)) old_ve = conds.t3.speaker_emb.detach().float().cpu().view(1, -1) old_x = torch.nn.functional.normalize(conds.gen["embedding"].detach().float().cpu(), dim=1) new_ve = torch.nn.functional.normalize(b * ve_emb + (1 - b) * old_ve, dim=1) new_x = b * xvec + (1 - b) * old_x agree_ve = float((torch.nn.functional.normalize(old_ve, dim=1) * new_ve).sum()) agree_x = float((old_x * torch.nn.functional.normalize(new_x, dim=1)).sum()) conds.t3.speaker_emb = new_ve.to( device=conds.t3.speaker_emb.device, dtype=conds.t3.speaker_emb.dtype ).view_as(conds.t3.speaker_emb) conds.gen["embedding"] = new_x.to( device=conds.gen["embedding"].device, dtype=conds.gen["embedding"].dtype ) out.parent.mkdir(parents=True, exist_ok=True) info = { "model": model_kind, "anchor": str(anchor), "clips_used": len(usable), "clips_rejected_quality": rejected_quality, "source_groups": len(used_by_group), "clips_per_source": used_by_group, "anchor_quality": anchor_quality, "blend": b, "anchor_agreement": {"voice_encoder": round(agree_ve, 3), "xvector": round(agree_x, 3)}, "created": datetime.now().isoformat(timespec="seconds"), "sources": [str(source) for source in sources], } conds.save(profile_tmp) meta_tmp.write_text(json.dumps(info, indent=2), encoding="utf-8") os.replace(profile_tmp, out) os.replace(meta_tmp, meta_path) if progress: progress("Profile rebuilt successfully.", 100) return info finally: model.conds = previous_conds for temp_path in (profile_tmp, meta_tmp): try: temp_path.unlink() except FileNotFoundError: pass def main(): p = argparse.ArgumentParser(description="Build a voice profile from many clips.") p.add_argument("--clips", nargs="+", required=True, help="Dataset folders from prepare_dataset.py, folders of clips, or files") p.add_argument("--anchor", type=Path, required=True, help="One clean 7-15 s clip whose delivery and sound you want (e.g. refs\\clip1.wav)") p.add_argument("--out", type=Path, default=Path("voices") / "brian.pt") p.add_argument("--model", choices=["standard", "turbo"], default="standard", help="Must match the --model you use in speak.py") p.add_argument("--max-clips", type=int, default=400, help="Use at most this many clips (random sample); more = slower, little gain past ~400") p.add_argument("--min-sim", type=float, default=0.65, help="Only use dataset clips that matched Brian at least this strongly") p.add_argument("--min-sec", type=float, default=2.0) p.add_argument("--blend", type=float, default=1.0, help="1.0 = identity fully from all clips; 0.5 = half anchor, half all clips") p.add_argument("--device", default="auto") p.add_argument("--seed", type=int, default=0) args = p.parse_args() import speak # reuse model loading and fixes print("Collecting clips...") device = speak.pick_device(args.device) model = speak.load_model(args.model, device) t = time.time() try: info = build_voice_profile( model, args.model, device, args.clips, args.anchor, args.out, max_clips=args.max_clips, min_sim=args.min_sim, min_sec=args.min_sec, blend=args.blend, seed=args.seed, ) except ValueError as e: sys.exit(str(e)) print(f"\nVoice profile saved: {args.out} ({info['clips_used']} clips, {time.time() - t:.0f}s)") print(f"Anchor clip vs. whole-archive voice: {info['anchor_agreement']['voice_encoder']:.2f} / " f"{info['anchor_agreement']['xvector']:.2f} " "(closer to 1.00 = the anchor already sounds like typical Brian)") print(f'Try it: python speak.py "Hey guys, welcome back." --voice {args.out}' + (" --model turbo" if args.model == "turbo" else "")) if __name__ == "__main__": main()