Files
voice_copy/voice-changer/app/train.py
EJClaw b0460fdff7 Add Windows realtime voice changer (RVC via Applio) + set operator to 사금향
- voice-changer/: install.bat (uv + Python 3.12 + pinned Applio + torch cu128),
  VoiceChanger.exe launcher (mingw), tkinter GUI (model list, auto ±12 pitch
  across genders, mic/output/monitor devices, latency, noise gate),
  train.bat (preprocess/extract/train/index → models/<id>), examples.bat
  (Korean example models from KSS + Zeroth-Korean), build-release.sh
- consent-recorder: default OPERATOR_NAME=사금향

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:34:03 +09:00

166 lines
6.1 KiB
Python

"""녹음 폴더(wav)로 RVC 목소리 모델을 학습해서 models/<아이디>/ 에 넣는다.
train.bat <녹음 폴더> <모델 이름> <male|female> [--epochs 200] [--id 영문아이디]
녹음 폴더는 consent-recorder 의 `npm run cli -- export <디스코드 아이디> <폴더>` 결과(48kHz 모노, -18 LUFS)를 그대로 쓴다.
다른 곳에서 가져온 녹음이면 --normalize 를 붙여 같은 기준으로 평준화한다.
"""
import argparse
import datetime as dt
import os
import shutil
import subprocess
import sys
from pathlib import Path
from common import DATASETS, LOUDNORM, MODELS, TRAINING, ffmpeg, save_json, slug, use_engine
AUDIO_EXT = {".wav", ".flac", ".ogg", ".mp3", ".m4a", ".opus"}
def total_seconds(folder: Path) -> float:
import soundfile as sf
total = 0.0
for p in folder.rglob("*"):
if p.suffix.lower() in AUDIO_EXT:
try:
total += sf.info(str(p)).duration
except Exception:
pass
return total
def normalize(src: Path, dst: Path, sample_rate: int) -> Path:
"""javis_bot · 겜녹이와 같은 기준(-18 LUFS + 리미터)으로 맞춘 모노 wav 를 dst 에 만든다."""
dst.mkdir(parents=True, exist_ok=True)
files = [p for p in sorted(src.rglob("*")) if p.suffix.lower() in AUDIO_EXT]
for i, p in enumerate(files, 1):
out = dst / f"{i:05d}.wav"
if out.exists():
continue
r = subprocess.run(
[ffmpeg(), "-v", "error", "-y", "-i", str(p), "-ac", "1", "-ar", str(sample_rate), "-af", LOUDNORM, str(out)],
capture_output=True,
text=True,
)
if r.returncode != 0:
print(f" 건너뜀 {p.name}: {r.stderr.strip()[:200]}")
return dst
def gpu_arg() -> str:
import torch
if torch.cuda.is_available():
print(f"GPU: {torch.cuda.get_device_name(0)}")
return "0"
print("GPU 를 찾지 못해 CPU 로 학습합니다 (매우 느림).")
return "-"
def check(result: str, step: str) -> None:
print(result)
if "failed" in result.lower() or "error" in result.lower():
raise SystemExit(f"{step} 단계에서 실패했습니다. 위 로그를 확인해 주세요.")
def train(
dataset: Path,
name: str,
gender: str,
model_id: str,
epochs: int,
batch: int,
sample_rate: int,
do_normalize: bool,
extra_info: dict | None = None,
) -> Path:
dataset = dataset.resolve()
if not dataset.is_dir():
raise SystemExit(f"녹음 폴더가 없습니다: {dataset}")
secs = total_seconds(dataset)
print(f"녹음 길이: {secs / 60:.1f}분")
if secs < 60:
raise SystemExit("녹음이 1분보다 짧아서 학습할 수 없습니다. 최소 10분, 좋게는 20~30분을 모아 주세요.")
if secs < 600:
print("주의: 10분보다 짧아서 목소리가 덜 닮을 수 있습니다.")
if do_normalize:
print("평준화(-18 LUFS + 리미터) 중...")
dataset = normalize(dataset, DATASETS / f"{model_id}_norm", sample_rate)
use_engine()
import core # Applio
gpu = gpu_arg()
cores = max(1, (os.cpu_count() or 4) // 2)
print("1/4 자르기...")
check(core.run_preprocess_script(model_id, str(dataset), sample_rate, cores, "Automatic", False, 3.0, 0.3, "none"), "자르기")
print("2/4 음높이 · 특징 뽑기 (rmvpe + contentvec)...")
check(core.run_extract_script(model_id, "rmvpe", cores, gpu, sample_rate, "contentvec", None, 2), "특징 뽑기")
print(f"3/4 학습 ({epochs} epoch, batch {batch})...")
check(
core.run_train_script(
model_id,
save_every_epoch=10,
save_only_latest=True,
save_every_weights=False,
total_epoch=epochs,
sample_rate=sample_rate,
batch_size=batch,
gpu=gpu,
pretrained=True,
cleanup=False,
index_algorithm="Auto",
),
"학습",
)
print("4/4 모델 목록에 넣기...")
exp = TRAINING / model_id
weights = sorted(exp.glob(f"{model_id}_*e_*s.pth"), key=lambda p: p.stat().st_mtime)
if not weights:
raise SystemExit(f"학습 결과(.pth)를 찾지 못했습니다: {exp}")
out = MODELS / model_id
out.mkdir(parents=True, exist_ok=True)
shutil.copy2(weights[-1], out / "model.pth")
index = exp / f"{model_id}.index"
if index.is_file():
shutil.copy2(index, out / "model.index")
info = {
"name": name,
"gender": gender,
"source": f"직접 학습 ({secs / 60:.0f}분 녹음)",
"license": "",
"example": False,
"epochs": epochs,
"sample_rate": sample_rate,
"created": dt.datetime.now().isoformat(timespec="seconds"),
}
info.update(extra_info or {})
save_json(out / "info.json", info)
print(f"완료: {out} (음성 변환기 앱에서 '{name}' 을 고르면 됩니다)")
return out
def main(argv=None):
ap = argparse.ArgumentParser(description="녹음으로 RVC 목소리 모델 학습")
ap.add_argument("dataset", type=Path, help="녹음 wav 폴더")
ap.add_argument("name", help="앱에 보일 모델 이름 (한글 가능)")
ap.add_argument("gender", choices=["male", "female"], help="이 목소리의 성별")
ap.add_argument("--id", help="폴더용 영문 아이디 (기본: 이름에서 만들거나 날짜)")
ap.add_argument("--epochs", type=int, default=200)
ap.add_argument("--batch", type=int, default=8, help="RTX 5070 Ti 16GB 기준 8")
ap.add_argument("--sample-rate", type=int, default=48000, choices=[32000, 40000, 48000])
ap.add_argument("--normalize", action="store_true", help="-18 LUFS 평준화를 한 번 더 함 (export 결과가 아닌 녹음일 때)")
a = ap.parse_args(argv)
model_id = slug(a.id or a.name) or dt.datetime.now().strftime("voice_%Y%m%d_%H%M%S")
if (MODELS / model_id).exists():
raise SystemExit(f"같은 아이디의 모델이 이미 있습니다: {MODELS / model_id} (--id 로 다른 이름을 주세요)")
train(a.dataset, a.name, a.gender, model_id, a.epochs, a.batch, a.sample_rate, a.normalize)
if __name__ == "__main__":
sys.exit(main())