commit 61b5162c260e4a0a84a555ae5406a8d5761cca0b
parent 87d47f3b4be1a2765f9aabf43ea1a3cf91a4b036
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 17:02:43 -0500
voice: seed-vc can follow the read's pitch -- --pitch source|contour runs the f0-conditioned 44.1 kHz model on the input's RMVPE curve, --semitones moves it; target is the old path unchanged
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
3 files changed, 139 insertions(+), 11 deletions(-)
diff --git a/scripts/voice.mjs b/scripts/voice.mjs
@@ -15,7 +15,9 @@
// its delay compensated (-D) so the timing holds.
// convert openvoice OpenVoice v2's tone-colour converter
// (scripts/voice_openvoice.py, torch on the CPU).
-// seed-vc Seed-VC v1's 22 kHz speech model
+// seed-vc Seed-VC v1's 22 kHz speech model, or with
+// --pitch source|contour its 44.1 kHz f0-conditioned
+// one, whose output follows the input's pitch
// (scripts/voice_seedvc.py, torch on the CPU).
// A convert engine is given --target-ref: a STOCK voice's reference clip,
// made by our own TTS engines (the controller refuses anything else).
@@ -27,7 +29,8 @@
// limiter, which would move the timing): to --lufs for enhance, to the
// input's own loudness for convert, either capped at -1 dBTP. Moved into
// place atomically. On stdout, one JSON line: {op, engine, sampleRate,
-// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}.
+// seconds, samples, engineMs, gainDb, inputLufs, outputLufs, more?}, and for
+// a followed pitch {pitch, semitones, f0: {targetHz, sourceHz, shiftSemitones}}.
//
// SCRATCH lives beside --output (`<output>.voice-<pid>/`), never in the OS
// temp dir (a RAM tmpfs on this machine), and is removed on every way out.
@@ -45,6 +48,10 @@
// --code <dir> the engine's pinned checkout [openvoice, seed-vc]
// --target-ref <wav> the stock target's reference clip [convert]
// --target-se <pt> where openvoice caches the target's embedding
+// --pitch <mode> target (default: the stock voice's own pitch), source
+// (the input's pitch) or contour (the input's intonation
+// at the stock voice's register) [seed-vc]
+// --semitones <n> moves a followed pitch, -12 to 12 [seed-vc, with --pitch source|contour]
// --model <f> the rnnoise model [rnnoise]
// --threads <n> CPU threads for torch (default 4)
// --lufs <x> enhance's level when params has no `lufs` (default -20)
@@ -101,6 +108,14 @@ if (!Array.isArray(extra) || !extra.every((x) => x && typeof x.input === "string
}
const ffmpeg = arg("--ffmpeg", process.env.FFMPEG_BIN ?? "ffmpeg");
const threads = String(Math.max(1, Number(arg("--threads", "4")) || 4));
+// The pitch a conversion lands on (seed-vc; scripts/voice_seedvc.py's header).
+const PITCH_MODES = ["target", "source", "contour"];
+const pitch = arg("--pitch", "target");
+const semitones = Number(arg("--semitones", "0"));
+if (!PITCH_MODES.includes(pitch)) fail(`--pitch is one of ${PITCH_MODES.join(", ")} (got '${pitch}')`);
+if (!Number.isFinite(semitones) || semitones < -12 || semitones > 12) fail(`--semitones is a number from -12 to 12 (got '${arg("--semitones", "")}')`);
+if (pitch !== "target" && kind !== "seed-vc") fail(`--pitch ${pitch} is seed-vc's: ${kind} has no pitch control`);
+if (semitones !== 0 && pitch === "target") fail("--semitones moves a followed pitch: it needs --pitch source or contour");
const lufs = typeof params.lufs === "number" ? params.lufs : Number(arg("--lufs", "-20"));
const out = path.resolve(output);
@@ -247,13 +262,27 @@ async function convertAll(items) {
"--threads", threads,
], { env });
} else {
- await run(python, [
+ const { stdout } = await run(python, [
path.join(import.meta.dirname, "voice_seedvc.py"),
"--code", code,
- "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
- "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
+ // A followed pitch is the f0-conditioned model's (44.1 kHz, its own
+ // vocoder, RMVPE): the optional files `voice setup --engine seed-vc
+ // --with f0` fetches (common/lib/voiceApps.ts SEEDVC_F0_FILES).
+ ...(pitch === "target"
+ ? [
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_small_wavenet_bigvgan_pruned.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_small_wavenet.yml"),
+ "--bigvgan", path.join(install, "bigvgan"),
+ ]
+ : [
+ "--dit", path.join(install, "DiT_seed_v2_uvit_whisper_base_f0_44k_bigvgan_pruned_ft_ema_v2.pth"),
+ "--config", path.join(install, "config_dit_mel_seed_uvit_whisper_base_f0_44k.yml"),
+ "--bigvgan", path.join(install, "bigvgan-44k"),
+ "--rmvpe", path.join(install, "rmvpe.pt"),
+ "--pitch", pitch,
+ "--semitones", String(semitones),
+ ]),
"--whisper", path.join(install, "whisper-small"),
- "--bigvgan", path.join(install, "bigvgan"),
"--campplus", path.join(install, "campplus_cn_common.bin"),
"--batch", batch, "--target-ref", ref,
"--steps", String(Math.round(Math.min(100, Math.max(1, num(params.steps, 10))))),
@@ -261,7 +290,15 @@ async function convertAll(items) {
"--ref-seconds", String(Math.min(25, Math.max(3, num(params.refSeconds, 10)))),
"--threads", threads,
], { env });
+ // A followed pitch: what the tracker heard and how far the curve was moved.
+ try {
+ const said = JSON.parse(stdout.trim().split("\n").pop() ?? "{}");
+ if (pitch !== "target" && said.f0 && typeof said.f0 === "object") return { pitch, semitones, f0: said.f0 };
+ } catch {
+ /* the result line is the wrapper's own */
+ }
}
+ return {};
}
// One static gain (enhance to --lufs, convert to the input's own loudness;
@@ -302,8 +339,9 @@ try {
const items = [];
for (const [k, item] of [{ input, output }, ...extra].entries()) items.push(await prepare(item, k));
const started = Date.now();
+ const engineSaid = {};
if (op === "enhance") for (const it of items) await enhanceOne(it);
- else await convertAll(items);
+ else Object.assign(engineSaid, await convertAll(items));
const engineMs = Date.now() - started;
const done = [];
for (const it of items) done.push(await finish(it));
@@ -319,6 +357,7 @@ try {
gainDb: first.gainDb,
inputLufs: first.inputLufs,
outputLufs: first.outputLufs,
+ ...engineSaid,
...(rest.length ? { more: rest } : {}),
};
process.stdout.write(JSON.stringify(result) + "\n");
diff --git a/scripts/voice.test.mjs b/scripts/voice.test.mjs
@@ -31,6 +31,13 @@ test("the argv is checked before anything runs", () => {
assert.match(run(["--op", "enhance", "--engine-kind", "seed-vc"]).stderr, /--engine-kind for enhance is one of rnnoise, deepfilternet/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise"]).stderr, /--input and --output are required/);
assert.match(run(["--op", "enhance", "--engine-kind", "rnnoise", "--input", "/a", "--output", "/b", "--params", "{"]).stderr, /--params must be JSON/);
+ // The pitch a conversion lands on is seed-vc's to follow, and semitones move a followed one.
+ const conv = (kind, ...more) => run(["--op", "convert", "--engine-kind", kind, "--input", "/a", "--output", "/b", ...more]);
+ assert.match(conv("seed-vc", "--pitch", "higher").stderr, /--pitch is one of target, source, contour \(got 'higher'\)/);
+ assert.match(conv("seed-vc", "--pitch", "source", "--semitones", "13").stderr, /--semitones is a number from -12 to 12 \(got '13'\)/);
+ assert.match(conv("seed-vc", "--semitones", "2").stderr, /--semitones moves a followed pitch: it needs --pitch source or contour/);
+ assert.match(conv("openvoice", "--pitch", "contour").stderr, /--pitch contour is seed-vc's: openvoice has no pitch control/);
+ for (const r of [conv("seed-vc", "--pitch", "higher"), conv("openvoice", "--pitch", "contour")]) assert.equal(r.status, 2);
});
test("rnnoise: 48 kHz mono, the input's exact length, aligned, the same every run", { skip: !ffmpeg && "ffmpeg absent" }, () => {
diff --git a/scripts/voice_seedvc.py b/scripts/voice_seedvc.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-# SEED-VC (v1, the 22 kHz speech model), files in, files out — run by
+# 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).
@@ -17,10 +17,28 @@
# 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.
+#
# 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}.
+# 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
@@ -46,11 +64,22 @@ def main() -> int:
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")
@@ -106,6 +135,34 @@ def main() -> int:
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)
@@ -148,8 +205,25 @@ def main() -> int:
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))
- prompt, *_ = model.length_regulator(s_ori, ylens=target2_len, n_quantizers=3, f0=None)
+ 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 and kept for the rest.
+ heard = {"move": None, "sourceHz": None}
+
+ def followed_f0(src16):
+ f0 = f0_of(src16)
+ med = median_log(f0)
+ if heard["move"] is None:
+ heard["sourceHz"] = round(float(np.exp(med)), 1) if med is not None else None
+ heard["move"] = (ref_median - med) if a.pitch == "contour" and med is not None and ref_median is not None else 0.0
+ voiced = f0 > 1
+ out = f0.copy()
+ out[voiced] = f0[voiced] * float(np.exp(heard["move"])) * 2 ** (a.semitones / 12)
+ return torch.from_numpy(out.astype(np.float32))[None]
def convert(src):
with torch.no_grad():
@@ -172,7 +246,8 @@ def main() -> int:
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=None)
+ 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]
@@ -208,6 +283,13 @@ def main() -> int:
"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