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>
This commit is contained in:
57
voice-changer/app/common.py
Normal file
57
voice-changer/app/common.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""경로와 Applio 엔진 불러오기. 다른 모듈은 이것부터 import 한다."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(os.environ.get("VC_ROOT") or Path(__file__).resolve().parent.parent)
|
||||
ENGINE = Path(os.environ.get("VC_ENGINE") or ROOT / "engine")
|
||||
MODELS = ROOT / "models"
|
||||
TRAINING = ROOT / "training"
|
||||
DATASETS = ROOT / "datasets"
|
||||
CONFIG = ROOT / "config"
|
||||
SETTINGS = CONFIG / "settings.json"
|
||||
|
||||
|
||||
def use_engine():
|
||||
"""Applio 코드가 상대 경로(rvc/models/...)를 쓰므로 엔진 폴더로 옮겨 가서 import 한다."""
|
||||
if not (ENGINE / "rvc").is_dir():
|
||||
raise SystemExit(f"엔진이 없습니다: {ENGINE}\ninstall.bat 을 먼저 실행해 주세요.")
|
||||
os.environ["APPLIO_LOGS_DIR"] = str(TRAINING)
|
||||
os.environ["APPLIO_CONFIG_DIR"] = str(CONFIG / "applio")
|
||||
# 학습·추출 하위 프로세스도 같은 엔진을 보도록
|
||||
os.environ["PYTHONPATH"] = os.pathsep.join([str(ENGINE), os.environ.get("PYTHONPATH", "")]).strip(os.pathsep)
|
||||
os.chdir(ENGINE)
|
||||
if str(ENGINE) not in sys.path:
|
||||
sys.path.insert(0, str(ENGINE))
|
||||
|
||||
|
||||
def slug(name: str) -> str:
|
||||
"""폴더·파일 이름용 영문 아이디. 한글 이름은 info.json 에만 둔다."""
|
||||
s = re.sub(r"[^A-Za-z0-9_-]+", "_", name).strip("_").lower()
|
||||
return s[:40]
|
||||
|
||||
|
||||
def load_json(path: Path, default):
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def save_json(path: Path, data) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def ffmpeg() -> str:
|
||||
"""Windows 는 엔진이 받아 둔 ffmpeg.exe, 그 밖에는 PATH 의 ffmpeg."""
|
||||
exe = ENGINE / "ffmpeg.exe"
|
||||
return str(exe) if exe.is_file() else "ffmpeg"
|
||||
|
||||
|
||||
# javis_bot · 겜녹이와 같은 기준: -18 LUFS 평준화 + 리미터 (consent-recorder export 와 같은 필터)
|
||||
LOUDNORM = "loudnorm=I=-18:TP=-1.5:LRA=11,alimiter=limit=0.89"
|
||||
168
voice-changer/app/examples.py
Normal file
168
voice-changer/app/examples.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""한국어 예시 모델 4개를 공개 데이터셋으로 학습한다 (게임PC GPU 로 한 번만 돌리면 됨).
|
||||
|
||||
- 여성 1: KSS (Korean Single Speaker Speech, 성우 1명, CC BY-NC-SA 4.0, 비상업)
|
||||
- 남성 1 · 남성 2 · 여성 2: Zeroth-Korean (OpenSLR 40, CC BY 4.0). 화자 이름 대신 화자 번호만 쓴다.
|
||||
|
||||
Zeroth 는 10GB 압축 파일이라 처음부터 흘려 읽다가 필요한 화자 녹음이 모이면 내려받기를 멈춘다.
|
||||
Zeroth 원본은 16kHz 라 KSS(44.1kHz)보다 고음이 덜 또렷하다. 그래서 32kHz 모델로 학습한다.
|
||||
|
||||
examples.bat # 4개 모두
|
||||
examples.bat --only kss --minutes 3 --epochs 1 # 빠른 확인용
|
||||
"""
|
||||
import argparse
|
||||
import io
|
||||
import sys
|
||||
import tarfile
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from common import DATASETS, MODELS
|
||||
|
||||
KSS_URL = "https://huggingface.co/datasets/Bingsu/KSS_Dataset/resolve/main/data/train-00000-of-00007.parquet"
|
||||
ZEROTH_URL = "https://www.openslr.org/resources/40/zeroth_korean.tar.gz"
|
||||
UA = {"User-Agent": "voice-changer-examples/1.0"}
|
||||
|
||||
|
||||
def _download(url: str, dst: Path) -> Path:
|
||||
if dst.is_file():
|
||||
return dst
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = dst.with_suffix(".part")
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60) as r, open(tmp, "wb") as f:
|
||||
total = int(r.headers.get("Content-Length") or 0)
|
||||
done = 0
|
||||
while chunk := r.read(1 << 20):
|
||||
f.write(chunk)
|
||||
done += len(chunk)
|
||||
if total:
|
||||
print(f"\r 내려받는 중 {done / total:5.1%}", end="", flush=True)
|
||||
print()
|
||||
tmp.replace(dst)
|
||||
return dst
|
||||
|
||||
|
||||
def prepare_kss(minutes: float) -> Path:
|
||||
import pyarrow.parquet as pq
|
||||
import soundfile as sf
|
||||
|
||||
out = DATASETS / "example_kss" / "raw"
|
||||
if out.is_dir() and any(out.iterdir()):
|
||||
return out
|
||||
print("KSS 받기 (약 540MB)...")
|
||||
pq_path = _download(KSS_URL, DATASETS / "_downloads" / "kss-00000.parquet")
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
total = 0.0
|
||||
n = 0
|
||||
pf = pq.ParquetFile(pq_path)
|
||||
for batch in pf.iter_batches(batch_size=64, columns=["audio"]):
|
||||
for a in batch.column("audio").to_pylist():
|
||||
data, sr = sf.read(io.BytesIO(a["bytes"]), dtype="float32")
|
||||
n += 1
|
||||
sf.write(out / f"kss_{n:05d}.wav", data, sr)
|
||||
total += len(data) / sr
|
||||
if total >= minutes * 60:
|
||||
print(f" KSS {total / 60:.1f}분 준비")
|
||||
return out
|
||||
print(f" KSS {total / 60:.1f}분 준비")
|
||||
return out
|
||||
|
||||
|
||||
def prepare_zeroth(want: dict[str, int], minutes: float) -> list[tuple[str, str, Path]]:
|
||||
"""want={'m': 2, 'f': 1} 처럼 성별마다 필요한 화자 수. 각 화자 minutes 분이 모이면 그 화자를 쓴다."""
|
||||
import soundfile as sf
|
||||
|
||||
done: list[tuple[str, str, Path]] = []
|
||||
for d in sorted((DATASETS).glob("example_zeroth_*")):
|
||||
meta = d / "speaker.txt"
|
||||
if meta.is_file():
|
||||
spk, sex = meta.read_text(encoding="utf-8").split()
|
||||
if want.get(sex, 0) > 0:
|
||||
want[sex] -= 1
|
||||
done.append((spk, sex, d / "raw"))
|
||||
if not any(v > 0 for v in want.values()):
|
||||
return done
|
||||
|
||||
print("Zeroth-Korean 을 흘려 읽는 중 (필요한 화자가 모이면 멈춤)...")
|
||||
sex_of: dict[str, str] = {}
|
||||
secs: dict[str, float] = {}
|
||||
files: dict[str, list[tuple[str, bytes]]] = {}
|
||||
read = 0
|
||||
with urllib.request.urlopen(urllib.request.Request(ZEROTH_URL, headers=UA), timeout=60) as r:
|
||||
tar = tarfile.open(fileobj=r, mode="r|gz")
|
||||
for m in tar:
|
||||
if m.name == "AUDIO_INFO":
|
||||
for line in tar.extractfile(m).read().decode("utf-8").splitlines()[1:]:
|
||||
parts = line.split("|")
|
||||
if len(parts) >= 3:
|
||||
sex_of[parts[0]] = parts[2]
|
||||
continue
|
||||
if not (m.isfile() and m.name.endswith(".flac")):
|
||||
continue
|
||||
spk = Path(m.name).name.split("_")[0]
|
||||
sex = sex_of.get(spk)
|
||||
if sex not in want or want[sex] <= 0 or secs.get(spk, 0) >= minutes * 60:
|
||||
continue
|
||||
data = tar.extractfile(m).read()
|
||||
read += len(data)
|
||||
try:
|
||||
secs[spk] = secs.get(spk, 0.0) + sf.info(io.BytesIO(data)).duration
|
||||
except Exception:
|
||||
continue
|
||||
files.setdefault(spk, []).append((Path(m.name).name, data))
|
||||
print(f"\r 읽은 녹음 {read / 1e6:,.0f}MB, 화자 {len(files)}명", end="", flush=True)
|
||||
if secs[spk] >= minutes * 60:
|
||||
d = DATASETS / f"example_zeroth_{spk}"
|
||||
(d / "raw").mkdir(parents=True, exist_ok=True)
|
||||
for fname, b in files.pop(spk):
|
||||
(d / "raw" / fname).write_bytes(b)
|
||||
(d / "speaker.txt").write_text(f"{spk} {sex}", encoding="utf-8")
|
||||
want[sex] -= 1
|
||||
done.append((spk, sex, d / "raw"))
|
||||
print(f"\n 화자 {spk}({'남' if sex == 'm' else '여'}) {secs[spk] / 60:.1f}분 준비")
|
||||
if not any(v > 0 for v in want.values()):
|
||||
break
|
||||
# 메모리 보호: 모으는 중인 화자가 너무 많으면 가장 적게 모인 화자를 버린다
|
||||
if len(files) > 12:
|
||||
drop = min(files, key=lambda s: secs.get(s, 0))
|
||||
files.pop(drop)
|
||||
secs[drop] = minutes * 60 # 다시 모으지 않음
|
||||
print()
|
||||
return done
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description="한국어 예시 모델 학습")
|
||||
ap.add_argument("--only", choices=["kss", "zeroth"], help="한쪽만")
|
||||
ap.add_argument("--minutes", type=float, default=20, help="화자마다 쓸 녹음 길이(분)")
|
||||
ap.add_argument("--epochs", type=int, default=200)
|
||||
ap.add_argument("--batch", type=int, default=8)
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
from train import train # 엔진 import 는 train 안에서
|
||||
|
||||
jobs = []
|
||||
if a.only in (None, "kss"):
|
||||
jobs.append(dict(dataset=prepare_kss(a.minutes), name="예시 여성 1 (KSS)", gender="female", model_id="example_kss",
|
||||
sample_rate=48000, extra_info={"source": "KSS Dataset (Kyubyong Park)", "license": "CC BY-NC-SA 4.0 (비상업)"}))
|
||||
if a.only in (None, "zeroth"):
|
||||
picked = prepare_zeroth({"m": 2, "f": 1}, a.minutes)
|
||||
n = {"m": 0, "f": 1} # 여성 1 은 KSS
|
||||
for spk, sex, raw in picked:
|
||||
n[sex] += 1
|
||||
g = "male" if sex == "m" else "female"
|
||||
jobs.append(dict(dataset=raw, name=f"예시 {'남성' if sex == 'm' else '여성'} {n[sex]} (Zeroth {spk})", gender=g,
|
||||
model_id=f"example_zeroth_{spk}", sample_rate=32000,
|
||||
extra_info={"source": f"Zeroth-Korean 화자 {spk} (OpenSLR 40)", "license": "CC BY 4.0"}))
|
||||
|
||||
for j in jobs:
|
||||
if (MODELS / j["model_id"] / "model.pth").is_file():
|
||||
print(f"이미 있음: {j['name']}")
|
||||
continue
|
||||
print(f"\n=== {j['name']} 학습 ===")
|
||||
info = dict(j.pop("extra_info"), example=True)
|
||||
train(j["dataset"], j["name"], j["gender"], j["model_id"], a.epochs, a.batch, j["sample_rate"], True, info)
|
||||
print("\n예시 모델 준비 끝.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
59
voice-changer/app/models.py
Normal file
59
voice-changer/app/models.py
Normal file
@@ -0,0 +1,59 @@
|
||||
"""models/<아이디>/ 안의 model.pth · model.index · info.json 을 목록으로 읽는다."""
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from common import MODELS, load_json
|
||||
|
||||
GENDERS = {"male": "남성", "female": "여성"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class VoiceModel:
|
||||
id: str
|
||||
name: str
|
||||
gender: str # male | female
|
||||
pth: Path
|
||||
index: Optional[Path]
|
||||
source: str
|
||||
license: str
|
||||
example: bool
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
tag = " · 예시" if self.example else ""
|
||||
return f"{self.name} ({GENDERS.get(self.gender, '?')}{tag})"
|
||||
|
||||
|
||||
def list_models(root: Path = MODELS) -> list[VoiceModel]:
|
||||
out = []
|
||||
if not root.is_dir():
|
||||
return out
|
||||
for d in sorted(root.iterdir()):
|
||||
pth = d / "model.pth"
|
||||
if not d.is_dir() or not pth.is_file():
|
||||
continue
|
||||
info = load_json(d / "info.json", {})
|
||||
idx = d / "model.index"
|
||||
out.append(
|
||||
VoiceModel(
|
||||
id=d.name,
|
||||
name=info.get("name") or d.name,
|
||||
gender=info.get("gender") if info.get("gender") in GENDERS else "male",
|
||||
pth=pth,
|
||||
index=idx if idx.is_file() else None,
|
||||
source=info.get("source", ""),
|
||||
license=info.get("license", ""),
|
||||
example=bool(info.get("example")),
|
||||
)
|
||||
)
|
||||
# 직접 만든 모델 먼저, 예시는 뒤로
|
||||
out.sort(key=lambda m: (m.example, m.name))
|
||||
return out
|
||||
|
||||
|
||||
def auto_pitch(my_gender: str, model_gender: str) -> int:
|
||||
"""성별이 다르면 한 옥타브(12반음) 올리거나 내린다. 같으면 0."""
|
||||
if my_gender == model_gender:
|
||||
return 0
|
||||
return 12 if model_gender == "female" else -12
|
||||
26
voice-changer/app/setup_engine.py
Normal file
26
voice-changer/app/setup_engine.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""install.bat 마지막 단계: 엔진이 쓰는 기본 모델(rmvpe · contentvec · 사전학습 가중치 · ffmpeg)을 받고 GPU 를 확인한다."""
|
||||
import sys
|
||||
|
||||
from common import use_engine
|
||||
|
||||
|
||||
def main():
|
||||
use_engine()
|
||||
import torch
|
||||
from rvc.lib.tools.prerequisites_download import prequisites_download_pipeline
|
||||
|
||||
print("엔진 기본 모델 받는 중 (약 2GB)...")
|
||||
prequisites_download_pipeline(True, True, True)
|
||||
if torch.cuda.is_available():
|
||||
name = torch.cuda.get_device_name(0)
|
||||
cap = torch.cuda.get_device_capability(0)
|
||||
x = torch.ones(1024, device="cuda") * 2 # Blackwell(sm_120) 커널이 실제로 도는지 확인
|
||||
assert float(x.sum()) == 2048.0
|
||||
print(f"GPU 확인: {name} (sm_{cap[0]}{cap[1]}), torch {torch.__version__}")
|
||||
else:
|
||||
print("주의: CUDA GPU 를 찾지 못했습니다. NVIDIA 드라이버(580 이상)를 확인해 주세요. CPU 로는 실시간 변환이 어렵습니다.")
|
||||
print("설치 끝.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
165
voice-changer/app/train.py
Normal file
165
voice-changer/app/train.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""녹음 폴더(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())
|
||||
313
voice-changer/app/voice_changer.py
Normal file
313
voice-changer/app/voice_changer.py
Normal file
@@ -0,0 +1,313 @@
|
||||
"""실시간 음성 변환기 (Windows 게임PC 용 화면).
|
||||
|
||||
마이크로 들어온 내 말소리를 고른 목소리 모델로 바꿔서 출력 장치로 내보낸다.
|
||||
디스코드 · 게임에 쓰려면 출력을 가상 케이블(VB-CABLE 의 "CABLE Input")로 두고,
|
||||
디스코드 입력 장치를 "CABLE Output" 으로 고른다.
|
||||
"""
|
||||
import multiprocessing as mp
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
from common import SETTINGS, load_json, save_json, use_engine
|
||||
from models import GENDERS, auto_pitch, list_models
|
||||
|
||||
LATENCY = {"낮음 (약 0.15초, GPU 여유 필요)": 128, "보통 (약 0.25초)": 250, "안정 (약 0.4초)": 400}
|
||||
|
||||
|
||||
def list_devices():
|
||||
"""(입력 이름→번호, 출력 이름→번호). 가상 케이블을 출력 맨 앞에 둔다."""
|
||||
from rvc.realtime.audio import list_audio_device
|
||||
|
||||
ins, outs = list_audio_device()
|
||||
|
||||
def is_virtual(d):
|
||||
n = d.name.lower()
|
||||
return "cable" in n or "virtual" in n or "vb-audio" in n
|
||||
|
||||
outs = sorted(outs, key=lambda d: not is_virtual(d))
|
||||
ins = sorted(ins, key=is_virtual) # 마이크를 앞에, 가상 케이블은 뒤에
|
||||
fmt = lambda d: f"{d.name} ({d.host_api})"
|
||||
return {fmt(d): d.index for d in ins}, {fmt(d): d.index for d in outs}
|
||||
|
||||
|
||||
class Converter:
|
||||
"""Applio 실시간 엔진(AudioCallbacks) 하나를 켜고 끈다."""
|
||||
|
||||
def __init__(self):
|
||||
self.callbacks = None
|
||||
|
||||
@property
|
||||
def running(self):
|
||||
return self.callbacks is not None
|
||||
|
||||
def start(self, model, pitch, in_id, out_id, monitor_id, chunk_ms, threshold, index_rate, on_status):
|
||||
from rvc.realtime.audio import resolve_sample_rate
|
||||
from rvc.realtime.callbacks import AudioCallbacks
|
||||
|
||||
sr = resolve_sample_rate(in_id, False, 48000)
|
||||
block = int(chunk_ms * sr / 1000)
|
||||
cb = AudioCallbacks(
|
||||
block_frame=block,
|
||||
cross_fade_overlap_size=0.05,
|
||||
extra_convert_size=2.5,
|
||||
model_path=str(model.pth),
|
||||
index_path=str(model.index) if model.index else "",
|
||||
f0_method="rmvpe",
|
||||
embedder_model="contentvec",
|
||||
silent_threshold=threshold,
|
||||
f0_up_key=pitch,
|
||||
index_rate=index_rate if model.index else 0.0,
|
||||
protect=0.33,
|
||||
volume_envelope=1.0,
|
||||
monitor=monitor_id is not None,
|
||||
audio_sample_rate=sr,
|
||||
)
|
||||
self.callbacks = cb
|
||||
try:
|
||||
cb.audio.start(
|
||||
input_device_id=in_id,
|
||||
output_device_id=out_id,
|
||||
output_monitor_id=monitor_id,
|
||||
block_frame=block,
|
||||
audio_sample_rate=sr,
|
||||
asio_input_channel=-1,
|
||||
asio_output_channel=-1,
|
||||
asio_output_monitor_channel=-1,
|
||||
)
|
||||
except Exception:
|
||||
self.stop()
|
||||
raise
|
||||
t0 = time.time()
|
||||
while not cb.vc.ready:
|
||||
if self.callbacks is not cb:
|
||||
raise RuntimeError("시작하는 중에 정지했습니다.")
|
||||
proc = getattr(cb.vc, "_process", None)
|
||||
if proc is not None and not proc.is_alive():
|
||||
self.stop()
|
||||
raise RuntimeError("모델을 불러오다 변환 작업이 멈췄습니다. 모델 파일을 확인해 주세요.")
|
||||
if time.time() - t0 > 300:
|
||||
self.stop()
|
||||
raise RuntimeError("모델을 5분 안에 불러오지 못했습니다.")
|
||||
on_status(f"모델 불러오는 중... {int(time.time() - t0)}초")
|
||||
time.sleep(0.5)
|
||||
|
||||
def set_pitch(self, pitch: int):
|
||||
if self.callbacks is not None:
|
||||
self.callbacks.audio.f0_up_key = pitch
|
||||
|
||||
def latency_ms(self) -> float:
|
||||
return float(getattr(self.callbacks.audio, "latency", 0) or 0) if self.callbacks else 0.0
|
||||
|
||||
def stop(self):
|
||||
cb, self.callbacks = self.callbacks, None
|
||||
if cb is None:
|
||||
return
|
||||
try:
|
||||
cb.audio.stop()
|
||||
finally:
|
||||
cb.vc.stop()
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, root: tk.Tk):
|
||||
self.root = root
|
||||
self.conv = Converter()
|
||||
self.events = queue.Queue() # 작업 스레드 → 화면 (tk 는 메인 스레드에서만 만진다)
|
||||
self.settings = load_json(SETTINGS, {})
|
||||
self.models = []
|
||||
root.title("실시간 음성 변환기")
|
||||
root.minsize(560, 520)
|
||||
root.protocol("WM_DELETE_WINDOW", self.close)
|
||||
|
||||
pad = dict(padx=10, pady=4)
|
||||
f = ttk.Frame(root)
|
||||
f.pack(fill="both", expand=True, padx=8, pady=8)
|
||||
|
||||
ttk.Label(f, text="목소리 모델").grid(row=0, column=0, sticky="w", **pad)
|
||||
self.model_list = tk.Listbox(f, height=8, exportselection=False)
|
||||
self.model_list.grid(row=1, column=0, columnspan=3, sticky="nsew", padx=10)
|
||||
self.model_list.bind("<<ListboxSelect>>", lambda e: self.on_model())
|
||||
ttk.Button(f, text="새로고침", command=self.load_models).grid(row=0, column=2, sticky="e", **pad)
|
||||
self.model_info = ttk.Label(f, text="", foreground="#555")
|
||||
self.model_info.grid(row=2, column=0, columnspan=3, sticky="w", **pad)
|
||||
|
||||
ttk.Label(f, text="내 목소리 성별").grid(row=3, column=0, sticky="w", **pad)
|
||||
self.my_gender = tk.StringVar(value=self.settings.get("my_gender", "male"))
|
||||
g = ttk.Frame(f)
|
||||
g.grid(row=3, column=1, columnspan=2, sticky="w")
|
||||
for k, v in GENDERS.items():
|
||||
ttk.Radiobutton(g, text=v, value=k, variable=self.my_gender, command=self.on_model).pack(side="left", padx=4)
|
||||
|
||||
ttk.Label(f, text="음높이 (반음)").grid(row=4, column=0, sticky="w", **pad)
|
||||
self.pitch = tk.IntVar(value=0)
|
||||
self.pitch_scale = tk.Scale(f, from_=-24, to=24, orient="horizontal", variable=self.pitch, command=lambda v: self.conv.set_pitch(int(float(v))))
|
||||
self.pitch_scale.grid(row=4, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
ttk.Label(f, text="성별이 다른 모델을 고르면 ±12 로 자동으로 맞춥니다. 켜 둔 채로 바꿔도 됩니다.", foreground="#555").grid(row=5, column=0, columnspan=3, sticky="w", padx=10)
|
||||
|
||||
self.in_dev, self.out_dev, self.mon_dev = tk.StringVar(), tk.StringVar(), tk.StringVar()
|
||||
self.use_monitor = tk.BooleanVar(value=self.settings.get("use_monitor", False))
|
||||
ttk.Label(f, text="마이크 (입력)").grid(row=6, column=0, sticky="w", **pad)
|
||||
self.in_box = ttk.Combobox(f, textvariable=self.in_dev, state="readonly")
|
||||
self.in_box.grid(row=6, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
ttk.Label(f, text="출력 (디스코드용은 CABLE Input)").grid(row=7, column=0, sticky="w", **pad)
|
||||
self.out_box = ttk.Combobox(f, textvariable=self.out_dev, state="readonly")
|
||||
self.out_box.grid(row=7, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
ttk.Checkbutton(f, text="내 귀로 듣기", variable=self.use_monitor).grid(row=8, column=0, sticky="w", **pad)
|
||||
self.mon_box = ttk.Combobox(f, textvariable=self.mon_dev, state="readonly")
|
||||
self.mon_box.grid(row=8, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
|
||||
ttk.Label(f, text="지연").grid(row=9, column=0, sticky="w", **pad)
|
||||
self.latency = tk.StringVar(value=self.settings.get("latency", "보통 (약 0.25초)"))
|
||||
ttk.Combobox(f, textvariable=self.latency, values=list(LATENCY), state="readonly").grid(row=9, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
ttk.Label(f, text="잡음 무시 (dB)").grid(row=10, column=0, sticky="w", **pad)
|
||||
self.threshold = tk.IntVar(value=self.settings.get("threshold", -60))
|
||||
tk.Scale(f, from_=-90, to=-20, orient="horizontal", variable=self.threshold).grid(row=10, column=1, columnspan=2, sticky="ew", padx=10)
|
||||
|
||||
b = ttk.Frame(f)
|
||||
b.grid(row=11, column=0, columnspan=3, pady=10)
|
||||
self.start_btn = ttk.Button(b, text="▶ 변환 시작", command=self.start)
|
||||
self.start_btn.pack(side="left", padx=6)
|
||||
self.stop_btn = ttk.Button(b, text="■ 정지", command=self.stop, state="disabled")
|
||||
self.stop_btn.pack(side="left", padx=6)
|
||||
self.status = ttk.Label(f, text="꺼짐")
|
||||
self.status.grid(row=12, column=0, columnspan=3, sticky="w", **pad)
|
||||
|
||||
f.columnconfigure(1, weight=1)
|
||||
f.rowconfigure(1, weight=1)
|
||||
self.load_models()
|
||||
self.load_devices()
|
||||
self.tick()
|
||||
|
||||
# ---- 목록 ----
|
||||
def load_models(self):
|
||||
self.models = list_models()
|
||||
self.model_list.delete(0, "end")
|
||||
for m in self.models:
|
||||
self.model_list.insert("end", m.label)
|
||||
if not self.models:
|
||||
self.model_info.config(text="모델이 없습니다. train.bat 로 학습하거나 examples.bat 로 예시 모델을 만들어 주세요.")
|
||||
return
|
||||
last = self.settings.get("model")
|
||||
i = next((n for n, m in enumerate(self.models) if m.id == last), None)
|
||||
self.model_list.selection_set(i or 0)
|
||||
self.on_model(keep_pitch=self.settings.get("pitch") if i is not None else None)
|
||||
|
||||
def load_devices(self):
|
||||
try:
|
||||
self.ins, self.outs = list_devices()
|
||||
except Exception as e:
|
||||
self.ins, self.outs = {}, {}
|
||||
self.status.config(text=f"오디오 장치를 읽지 못했습니다: {e}")
|
||||
self.in_box["values"] = list(self.ins)
|
||||
self.out_box["values"] = list(self.outs)
|
||||
self.mon_box["values"] = list(self.outs)
|
||||
for var, choices, key in ((self.in_dev, self.ins, "input"), (self.out_dev, self.outs, "output"), (self.mon_dev, self.outs, "monitor")):
|
||||
saved = self.settings.get(key)
|
||||
var.set(saved if saved in choices else next(iter(choices), ""))
|
||||
|
||||
def selected(self):
|
||||
sel = self.model_list.curselection()
|
||||
return self.models[sel[0]] if sel else None
|
||||
|
||||
def on_model(self, keep_pitch=None):
|
||||
m = self.selected()
|
||||
if not m:
|
||||
return
|
||||
p = keep_pitch if isinstance(keep_pitch, int) else auto_pitch(self.my_gender.get(), m.gender)
|
||||
self.pitch.set(p)
|
||||
self.conv.set_pitch(p)
|
||||
extra = " · ".join(x for x in (m.source, m.license, "검색 인덱스 있음" if m.index else "인덱스 없음") if x)
|
||||
self.model_info.config(text=extra)
|
||||
if self.conv.running:
|
||||
self.status.config(text="모델을 바꾸려면 정지 후 다시 시작해 주세요. (음높이는 바로 바뀝니다)")
|
||||
|
||||
# ---- 시작/정지 ----
|
||||
def start(self):
|
||||
m = self.selected()
|
||||
if not m:
|
||||
messagebox.showwarning("음성 변환기", "목소리 모델을 골라 주세요.")
|
||||
return
|
||||
if self.in_dev.get() not in self.ins or self.out_dev.get() not in self.outs:
|
||||
messagebox.showwarning("음성 변환기", "마이크와 출력 장치를 골라 주세요.")
|
||||
return
|
||||
mon = self.outs.get(self.mon_dev.get()) if self.use_monitor.get() else None
|
||||
if self.use_monitor.get() and mon is None:
|
||||
messagebox.showwarning("음성 변환기", "내 귀로 들을 장치를 골라 주세요.")
|
||||
return
|
||||
self.save_settings(m)
|
||||
self.start_btn.config(state="disabled")
|
||||
args = (m, self.pitch.get(), self.ins[self.in_dev.get()], self.outs[self.out_dev.get()], mon,
|
||||
LATENCY.get(self.latency.get(), 250), self.threshold.get(), 0.5)
|
||||
|
||||
def run():
|
||||
try:
|
||||
self.conv.start(*args, on_status=lambda s: self.events.put(("status", s)))
|
||||
self.events.put(("started", m))
|
||||
except Exception as e:
|
||||
self.events.put(("failed", e))
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
|
||||
def on_started(self, m):
|
||||
self.running_name = m.name
|
||||
self.stop_btn.config(state="normal")
|
||||
self.status.config(text=f"● 변환 중: {m.name}")
|
||||
|
||||
def on_failed(self, e):
|
||||
self.start_btn.config(state="normal")
|
||||
self.stop_btn.config(state="disabled")
|
||||
self.status.config(text="꺼짐")
|
||||
messagebox.showerror("음성 변환기", f"시작하지 못했습니다.\n{e}")
|
||||
|
||||
def stop(self):
|
||||
self.conv.stop()
|
||||
self.start_btn.config(state="normal")
|
||||
self.stop_btn.config(state="disabled")
|
||||
self.status.config(text="꺼짐")
|
||||
|
||||
def tick(self):
|
||||
while True:
|
||||
try:
|
||||
kind, val = self.events.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
if kind == "status":
|
||||
self.status.config(text=val)
|
||||
elif kind == "started":
|
||||
self.on_started(val)
|
||||
elif kind == "failed":
|
||||
self.on_failed(val)
|
||||
if self.conv.running and str(self.stop_btn["state"]) == "normal":
|
||||
self.status.config(text=f"● 변환 중: {self.running_name} · 처리 {self.conv.latency_ms():.0f}ms")
|
||||
self.root.after(200, self.tick)
|
||||
|
||||
def save_settings(self, m):
|
||||
self.settings.update(model=m.id, pitch=self.pitch.get(), my_gender=self.my_gender.get(), input=self.in_dev.get(),
|
||||
output=self.out_dev.get(), monitor=self.mon_dev.get(), use_monitor=self.use_monitor.get(),
|
||||
latency=self.latency.get(), threshold=self.threshold.get())
|
||||
save_json(SETTINGS, self.settings)
|
||||
|
||||
def close(self):
|
||||
self.conv.stop()
|
||||
self.root.destroy()
|
||||
|
||||
|
||||
def main():
|
||||
root = tk.Tk()
|
||||
try:
|
||||
use_engine()
|
||||
App(root)
|
||||
except SystemExit as e:
|
||||
root.withdraw()
|
||||
messagebox.showerror("음성 변환기", str(e))
|
||||
return 1
|
||||
root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
mp.freeze_support()
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user