#!/usr/bin/env python3 # SEED-VC (v1: the 22 kHz speech model, or the 44.1 kHz f0-conditioned one), files in, files out — run by # scripts/voice.mjs (--engine-kind seed-vc) in the venv `archilyzer voice # setup --engine seed-vc` built. Never run by hand: the editor's # `voice-convert` op is the way in (common/controller/voiceFile.ts). # # What it does (upstream inference.py, trimmed to the one model and made to # load every file from the install dir, offline): the input's content features # (Whisper-small's encoder) are length-regulated to the input's own frame count # — so the timing is the input's — and a diffusion transformer generates the # mel in the TARGET's timbre, prompted with a stock reference clip our own TTS # engines made (never a recording of a person; the controller refuses anything # else). BigVGAN turns the mel back into audio. Long inputs go in ~30 s windows # with a crossfade, as upstream does. # # `dac` (descript-audio-codec) is imported by the length regulator for a # quantizer this model does not use; it is stubbed rather than installed (it # pulls in a training stack). # # PITCH (--pitch). The 22 kHz model is given no pitch at all: it speaks every # input at the TARGET's own pitch and narrows the range (measured 2026-11-11: # inputs with a median f0 of 128 to 237 Hz all came out at 196-199 Hz) — the # read's intonation is thrown away. `--pitch target` is that, unchanged. The # other two run upstream's f0-conditioned model (`inference.py --f0-condition`: # 44.1 kHz, a 128-band BigVGAN, RMVPE as the pitch tracker — voice.mjs passes # those files as --dit/--config/--bigvgan and --rmvpe): the input's f0 curve # conditions the content, so the output's pitch FOLLOWS the read. # source the input's f0 as it is: the output is at the pitch it was read at. # contour the input's curve moved, as a whole, so its median lands on the # target reference's median (upstream's --auto-f0-adjust): every rise # and fall is kept, the register is the stock voice's. # --semitones then moves the followed curve up or down (2^(n/12)). In a batch # the contour's move is measured ONCE, on the first file (the take), and used # for the rest (its parts): a part must sit where it sits in the whole. A file # with no voiced frame (silence, a breath) has no median to measure: it leaves # the move unset, and the first file that has one sets it. # # Several files (--batch) are converted one after another, the model and the # target's features made once. # # stdout: one JSON line {engine, sampleRate, seconds, files, engineMs, pitch, # semitones, f0?: {targetHz, sourceHz, shiftSemitones}} — f0 is the medians # RMVPE heard in the reference and the first file, and the whole move applied. import argparse import json import math import os import sys import time import types def pitch_move(move, source_hz, median, ref_median, pitch, semitones): """The followed curve's factor for one file, and the batch's state after it. `move` is the batch's shift in log-f0 (None: not measured yet), `median` this file's median log-f0 (None: no voiced frame), `ref_median` the reference's. The shift is measured ONCE, on the first file with a voiced frame — contour: the reference's median less the file's; source: 0 — and a file before it (unvoiced: nothing in it is multiplied anyway) leaves it unset rather than locking it at 0. Returns (move, source_hz, factor). """ if move is None and median is not None: source_hz = round(math.exp(median), 1) move = (ref_median - median) if pitch == "contour" and ref_median is not None else 0.0 return move, source_hz, math.exp(move or 0.0) * 2 ** (semitones / 12) def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--code", required=True, help="the seed-vc checkout") ap.add_argument("--dit", required=True) ap.add_argument("--config", required=True) ap.add_argument("--whisper", required=True, help="a dir with whisper-small's config, preprocessor config and weights") ap.add_argument("--bigvgan", required=True, help="a dir with BigVGAN's config.json and bigvgan_generator.pt") ap.add_argument("--campplus", required=True) ap.add_argument("--input", default="") ap.add_argument("--output", default="") ap.add_argument("--batch", default="", help="a JSON file: [{input, output}], converted one after another, the model loaded once") ap.add_argument("--target-ref", required=True, help="the stock target's reference clip") ap.add_argument("--steps", type=int, default=10, help="diffusion steps") ap.add_argument("--cfg-rate", type=float, default=0.7) ap.add_argument("--ref-seconds", type=float, default=10.0, help="how much of the reference prompts the model: each window is 30 s less this, so less is faster") ap.add_argument("--pitch", choices=["target", "source", "contour"], default="target", help="target: the stock voice's own pitch (the 22 kHz model); source / contour: the input's f0 conditions the 44.1 kHz f0 model") ap.add_argument("--semitones", type=float, default=0.0, help="moves the followed f0 (source, contour); -12 to 12") ap.add_argument("--rmvpe", default="", help="rmvpe.pt, the pitch tracker (source, contour)") ap.add_argument("--threads", type=int, default=4) a = ap.parse_args() items = json.load(open(a.batch)) if a.batch else [{"input": a.input, "output": a.output}] if not items or not all(i.get("input") and i.get("output") for i in items): ap.error("--input and --output, or --batch") follow = a.pitch != "target" if follow and not a.rmvpe: ap.error("--pitch source|contour needs --rmvpe") if not follow and a.semitones != 0: ap.error("--semitones moves a followed pitch: it needs --pitch source or contour") if not -12 <= a.semitones <= 12: ap.error("--semitones is between -12 and 12") os.environ.setdefault("HF_HUB_OFFLINE", "1") os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") sys.path.insert(0, a.code) # The unused quantizer's import (see the header). dac = types.ModuleType("dac") dac_nn = types.ModuleType("dac.nn") dac_q = types.ModuleType("dac.nn.quantize") class VectorQuantize: # noqa: D401 - a stub def __init__(self, *args, **kwargs): raise RuntimeError("vector quantization is not available in this install") dac_q.VectorQuantize = VectorQuantize sys.modules.update({"dac": dac, "dac.nn": dac_nn, "dac.nn.quantize": dac_q}) import numpy as np import soundfile import torch import torchaudio import librosa import yaml from modules.commons import build_model, load_checkpoint, recursive_munch from modules.campplus.DTDNN import CAMPPlus from modules.bigvgan import bigvgan from modules.audio import mel_spectrogram from transformers import AutoFeatureExtractor, WhisperModel torch.set_num_threads(max(1, a.threads)) device = torch.device("cpu") t0 = time.time() config = yaml.safe_load(open(a.config, "r")) model_params = recursive_munch(config["model_params"]) model_params.dit_type = "DiT" model = build_model(model_params, stage="DiT") model, _, _, _ = load_checkpoint(model, None, a.dit, load_only_params=True, ignore_modules=[], is_distributed=False) for key in model: model[key].eval() model[key].to(device) model.cfm.estimator.setup_caches(max_batch_size=1, max_seq_length=8192) campplus = CAMPPlus(feat_dim=80, embedding_size=192) campplus.load_state_dict(torch.load(a.campplus, map_location="cpu")) campplus.eval() vocoder = bigvgan.BigVGAN.from_pretrained(a.bigvgan, use_cuda_kernel=False) vocoder.remove_weight_norm() vocoder = vocoder.eval() whisper = WhisperModel.from_pretrained(a.whisper, torch_dtype=torch.float32, local_files_only=True) del whisper.decoder whisper.eval() feat = AutoFeatureExtractor.from_pretrained(a.whisper, local_files_only=True) # The pitch tracker (source, contour): f0 in Hz per 10 ms of 16 kHz audio, # 0 where unvoiced. A long input goes in 30 s pieces, each heard with a # second of context either side — RMVPE over half an hour at once is GBs. f0_of = None if follow: from modules.rmvpe import RMVPE rmvpe = RMVPE(a.rmvpe, is_half=False, device=device) PIECE, CTX, HOP16 = 16000 * 30, 16000, 160 def f0_of(w16): w16 = w16.squeeze(0).cpu().numpy() n = len(w16) if n <= PIECE + 2 * CTX: return rmvpe.infer_from_audio(w16, thred=0.03) out, at = [], 0 while at < n: lo, end = max(0, at - CTX), min(n, at + PIECE) f = rmvpe.infer_from_audio(w16[lo : min(n, end + CTX)], thred=0.03) first = (at - lo) // HOP16 out.append(f[first:] if end == n else f[first : first + (end - at) // HOP16]) at = end return np.concatenate(out) def median_log(f0): v = f0[f0 > 1] return float(np.median(np.log(v))) if len(v) else None def semantic(w16): inputs = feat([w16.squeeze(0).cpu().numpy()], return_tensors="pt", return_attention_mask=True, sampling_rate=16000) x = whisper._mask_input_features(inputs.input_features, attention_mask=inputs.attention_mask) with torch.no_grad(): out = whisper.encoder(x.to(whisper.encoder.dtype), head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True) s = out.last_hidden_state.to(torch.float32) return s[:, : w16.size(-1) // 320 + 1] sp = config["preprocess_params"]["spect_params"] sr = config["preprocess_params"]["sr"] mel_args = { "n_fft": sp["n_fft"], "win_size": sp["win_length"], "hop_size": sp["hop_length"], "num_mels": sp["n_mels"], "sampling_rate": sr, "fmin": sp.get("fmin", 0), "fmax": None if sp.get("fmax", "None") == "None" else 8000, "center": False, } to_mel = lambda x: mel_spectrogram(x, **mel_args) # noqa: E731 hop = sp["hop_length"] max_context = sr // hop * 30 overlap_frames = 16 overlap_wave = overlap_frames * hop def crossfade(a1, a2, n): fo = np.cos(np.linspace(0, np.pi / 2, n)) ** 2 fi = np.cos(np.linspace(np.pi / 2, 0, n)) ** 2 if len(a2) < n: a2[:n] = a2[:n] * fi[: len(a2)] + (a1[-n:] * fo)[: len(a2)] else: a2[:n] = a2[:n] * fi + a1[-n:] * fo return a2 # The target, once: its content features, mel and style. ref = librosa.load(a.target_ref, sr=sr, mono=True)[0] with torch.no_grad(): refa = torch.tensor(ref[: int(sr * a.ref_seconds)]).unsqueeze(0).float() ref16 = torchaudio.functional.resample(refa, sr, 16000) s_ori = semantic(ref16) mel2 = to_mel(refa) target2_len = torch.LongTensor([mel2.size(2)]) fb = torchaudio.compliance.kaldi.fbank(ref16, num_mel_bins=80, dither=0, sample_frequency=16000) fb = fb - fb.mean(dim=0, keepdim=True) style = campplus(fb.unsqueeze(0)) f0_ref = f0_of(ref16) if follow else None prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3, f0=torch.from_numpy(f0_ref)[None] if follow else None) window = max_context - mel2.size(2) ref_median = median_log(f0_ref) if follow else None # What was heard and done, for the result line; `move` is the contour's # shift in log-f0, measured on the first file that has a voiced frame and # kept for the rest (None until then: a file with none has nothing to move). heard = {"move": None, "sourceHz": None} def followed_f0(src16): f0 = f0_of(src16) heard["move"], heard["sourceHz"], factor = pitch_move(heard["move"], heard["sourceHz"], median_log(f0), ref_median, a.pitch, a.semitones) voiced = f0 > 1 out = f0.copy() out[voiced] = f0[voiced] * factor return torch.from_numpy(out.astype(np.float32))[None] def convert(src): with torch.no_grad(): source = torch.tensor(src).unsqueeze(0).float() src16 = torchaudio.functional.resample(source, sr, 16000) if src16.size(-1) <= 16000 * 30: s_alt = semantic(src16) else: lap = 5 parts, buffer, at = [], None, 0 while at < src16.size(-1): if buffer is None: chunk = src16[:, at : at + 16000 * 30] else: chunk = torch.cat([buffer, src16[:, at : at + 16000 * (30 - lap)]], dim=-1) s = semantic(chunk) parts.append(s if at == 0 else s[:, 50 * lap :]) buffer = chunk[:, -16000 * lap :] at += 30 * 16000 if at == 0 else chunk.size(-1) - 16000 * lap s_alt = torch.cat(parts, dim=1) mel = to_mel(source) # The input's own frame count: the timing is the input's. cond, *_ = model.length_regulator(s_alt, ylens=torch.LongTensor([mel.size(2)]), n_quantizers=3, f0=followed_f0(src16) if follow else None) done, chunks, prev = 0, [], None while done < cond.size(1): c = cond[:, done : done + window] last = done + window >= cond.size(1) cat = torch.cat([prompt, c], dim=1) vc = model.cfm.inference(cat, torch.LongTensor([cat.size(1)]), mel2, style, None, a.steps, inference_cfg_rate=a.cfg_rate) vc = vc[:, :, mel2.size(-1) :] wave = vocoder(vc.float()).squeeze()[None, :] if done == 0: if last: chunks.append(wave[0].cpu().numpy()) break chunks.append(wave[0, :-overlap_wave].cpu().numpy()) prev = wave[0, -overlap_wave:] elif last: chunks.append(crossfade(prev.cpu().numpy(), wave[0].cpu().numpy(), overlap_wave)) break else: chunks.append(crossfade(prev.cpu().numpy(), wave[0, :-overlap_wave].cpu().numpy(), overlap_wave)) prev = wave[0, -overlap_wave:] done += vc.size(2) - overlap_frames return np.concatenate(chunks).astype(np.float32) total = 0.0 for item in items: audio = convert(librosa.load(item["input"], sr=sr, mono=True)[0]) soundfile.write(item["output"], np.clip(audio, -1, 1), sr, subtype="PCM_16") total += len(audio) / sr print(json.dumps({ "engine": "seed-vc", "sampleRate": sr, "seconds": round(total, 3), "files": len(items), "engineMs": int((time.time() - t0) * 1000), "pitch": a.pitch, "semitones": a.semitones, **({"f0": { "targetHz": round(float(np.exp(ref_median)), 1) if ref_median is not None else None, "sourceHz": heard["sourceHz"], "shiftSemitones": round(12 * (heard["move"] or 0.0) / float(np.log(2)) + a.semitones, 2), }} if follow else {}), })) return 0 if __name__ == "__main__": sys.exit(main())