#!/usr/bin/env python3 # OpenVoice v2's TONE-COLOUR CONVERTER, files in, files out — run by # scripts/voice.mjs (--engine-kind openvoice) in the venv `archilyzer voice # setup --engine openvoice` built. Never run by hand: the editor's # `voice-convert` op is the way in (common/controller/voiceFile.ts). # # What it does: the input's spectrogram goes through the converter's flow with # the SOURCE speaker's embedding (extracted from the input itself) swapped for # the TARGET's — extracted from a stock reference clip our own TTS engines made # (never a recording of a person; the controller refuses anything else). The # flow keeps the timing and the pitch contour; only the timbre moves. `--tau` # is the converter's temperature (0.3, the upstream default). # # Imports only the converter's own modules (models, mel_processing, utils): # the package's `api` pulls in its text front end and the watermarker, which # the converter does not need, so they are not installed. # # Several files (--batch) are one performance in parts: the source speaker is # embedded from all of them at once, the target once, the model loaded once. # # stdout: one JSON line {engine, sampleRate, seconds, files, engineMs}. import argparse import json import os import sys import time def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--code", required=True, help="the OpenVoice checkout (its openvoice/ package)") ap.add_argument("--ckpt", required=True) ap.add_argument("--config", required=True) ap.add_argument("--input", default="") ap.add_argument("--output", default="") ap.add_argument("--batch", default="", help="a JSON file: [{input, output}], one performance in several files") ap.add_argument("--target-ref", required=True, help="the stock target's reference clip") ap.add_argument("--target-se", default="", help="where the target's embedding is cached (.pt)") ap.add_argument("--tau", type=float, default=0.3) 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") sys.path.insert(0, a.code) import numpy as np import soundfile import torch import librosa from openvoice import utils from openvoice.mel_processing import spectrogram_torch from openvoice.models import SynthesizerTrn torch.set_num_threads(max(1, a.threads)) t0 = time.time() hps = utils.get_hparams_from_file(a.config) model = SynthesizerTrn( len(getattr(hps, "symbols", [])), hps.data.filter_length // 2 + 1, n_speakers=hps.data.n_speakers, **hps.model, ) model.eval() state = torch.load(a.ckpt, map_location="cpu", weights_only=False) model.load_state_dict(state["model"], strict=False) sr = hps.data.sampling_rate def spec_of(y): t = torch.FloatTensor(y).unsqueeze(0) return spectrogram_torch(t, hps.data.filter_length, sr, hps.data.hop_length, hps.data.win_length, center=False) # An embedding: the mean over ~10 s pieces (upstream splits by VAD; a # clean read needs no more than even pieces). def embedding(y): piece = sr * 10 gs = [] for at in range(0, max(1, len(y)), piece): seg = y[at : at + piece] if len(seg) < sr: # under a second says little about a voice if gs: continue with torch.no_grad(): gs.append(model.ref_enc(spec_of(seg).transpose(1, 2)).unsqueeze(-1)) return torch.stack(gs).mean(0) srcs = [librosa.load(i["input"], sr=sr, mono=True)[0] for i in items] if a.target_se and os.path.exists(a.target_se): tgt_se = torch.load(a.target_se, map_location="cpu", weights_only=False) else: ref, _ = librosa.load(a.target_ref, sr=sr, mono=True) tgt_se = embedding(ref) if a.target_se: tmp = a.target_se + ".part" torch.save(tgt_se, tmp) os.replace(tmp, a.target_se) # The source speaker, from every file of the performance at once (a short # part alone says little about a voice). src_se = embedding(np.concatenate(srcs)) total = 0.0 for item, src in zip(items, srcs): with torch.no_grad(): spec = spec_of(src) lengths = torch.LongTensor([spec.size(-1)]) out = model.voice_conversion(spec, lengths, sid_src=src_se, sid_tgt=tgt_se, tau=a.tau)[0][0, 0] audio = out.data.cpu().float().numpy() soundfile.write(item["output"], audio.astype(np.float32), sr, subtype="PCM_16") total += len(audio) / sr print(json.dumps({ "engine": "openvoice", "sampleRate": sr, "seconds": round(total, 3), "files": len(items), "engineMs": int((time.time() - t0) * 1000), })) return 0 if __name__ == "__main__": sys.exit(main())