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:
@@ -12,6 +12,10 @@
|
||||
|
||||
본인이 디스코드로 로그인해 녹음에 동의한 사람만 음성채널에서 따라가며 그 사람 목소리만 녹음합니다 (음성 모델 학습 데이터용). [`consent-recorder/README.md`](consent-recorder/README.md)
|
||||
|
||||
## 실시간 음성 변환기 (Windows 게임PC)
|
||||
|
||||
동의받은 녹음으로 RVC 목소리 모델을 학습하고, 마이크 소리를 그 목소리로 실시간으로 바꿔 디스코드 · 게임에 내보내는 exe 앱입니다. 모델 목록 선택, 성별이 다를 때 음높이 자동 보정, 한국어 예시 모델 학습 스크립트 포함. [`voice-changer/README.md`](voice-changer/README.md)
|
||||
|
||||
## 필요 사항
|
||||
|
||||
- Python 3.9+ (3.10~3.12 권장)
|
||||
|
||||
@@ -4,8 +4,9 @@ DISCORD_CLIENT_ID=
|
||||
DISCORD_CLIENT_SECRET=
|
||||
# 사이트 주소 (OAuth2 Redirects 에 <PUBLIC_URL>/callback 을 등록해야 함)
|
||||
PUBLIC_URL=https://voice.example.com
|
||||
# 동의 화면에 "누가 이 목소리 모델을 쓰는지"로 나오는 이름
|
||||
OPERATOR_NAME=
|
||||
# 동의 화면에 "누가 이 목소리 모델을 쓰는지"로 나오는 이름 (운영자 디스코드 계정 293719842274541579 의 닉네임)
|
||||
# 바꾸면 src/consent-text.ts 의 CONSENT_VERSION 도 올려서 모두에게 다시 동의를 받는다
|
||||
OPERATOR_NAME=사금향
|
||||
# 녹음할 디스코드 서버 아이디 (쉼표로 여러 개). 비우면 봇이 들어간 모든 서버
|
||||
ALLOWED_GUILD_IDS=
|
||||
HOST=127.0.0.1
|
||||
|
||||
@@ -50,7 +50,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env, needBot = true)
|
||||
host: env.HOST?.trim() || '127.0.0.1',
|
||||
port: Number(env.PORT || 8787),
|
||||
dataDir: path.resolve(env.DATA_DIR?.trim() || './data'),
|
||||
operatorName: env.OPERATOR_NAME?.trim() || '이 서비스 운영자',
|
||||
operatorName: env.OPERATOR_NAME?.trim() || '사금향',
|
||||
allowedGuildIds: new Set((env.ALLOWED_GUILD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)),
|
||||
channelNotice: (env.CHANNEL_NOTICE ?? '1') !== '0',
|
||||
discordApi: env.DISCORD_API?.trim() || 'https://discord.com/api/v10',
|
||||
|
||||
2
voice-changer/.gitattributes
vendored
Normal file
2
voice-changer/.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*.bat text eol=crlf
|
||||
*.ps1 text eol=crlf
|
||||
10
voice-changer/.gitignore
vendored
Normal file
10
voice-changer/.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
engine/
|
||||
env/
|
||||
tools/
|
||||
training/
|
||||
datasets/
|
||||
config/
|
||||
dist/
|
||||
models/*
|
||||
!models/.gitkeep
|
||||
__pycache__/
|
||||
82
voice-changer/README.md
Normal file
82
voice-changer/README.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# 실시간 음성 변환기 (Windows 게임PC)
|
||||
|
||||
마이크로 말하면 고른 목소리 모델로 바꿔서 바로 내보냅니다. 디스코드나 게임에서 그 목소리로 말할 수 있습니다.
|
||||
목소리 모델은 `consent-recorder` 로 동의받아 모은 녹음으로 이 PC 에서 직접 학습합니다 (RVC v2).
|
||||
|
||||
- 엔진: [Applio](https://github.com/IAHispano/Applio) (MIT, RVC 학습 · 실시간 변환). `scripts/install.ps1` 에 커밋을 고정해 둠
|
||||
- 기준 PC: RTX 5070 Ti 16GB (Blackwell) · DDR5 128GB · Ryzen 9 9950X3D · Windows 11
|
||||
- torch 2.11 + CUDA 12.8 (RTX 50 시리즈 지원). NVIDIA 드라이버 580 이상
|
||||
- 디스크: 설치 약 8GB(Python · torch · 엔진 기본 모델) + 모델마다 약 80MB + 학습 중간 파일. 예시 모델까지 만들면 15GB 정도 여유를 두세요
|
||||
|
||||
## 설치
|
||||
|
||||
1. 이 폴더를 원하는 곳에 풉니다 (경로에 한글이 없어도, 있어도 됩니다).
|
||||
2. `install.bat` 을 더블클릭합니다. uv, Python 3.12, 엔진, torch(CUDA 12.8), 엔진 기본 모델(rmvpe · contentvec · 사전학습 가중치 · ffmpeg)을 이 폴더 안에만 받습니다. 처음에는 10~20분 걸립니다.
|
||||
3. 마지막 줄에 `GPU 확인: NVIDIA GeForce RTX 5070 Ti (sm_120)` 가 나오면 끝입니다.
|
||||
4. 디스코드에서 쓰려면 가상 오디오 케이블 [VB-CABLE](https://vb-audio.com/Cable/) 을 설치합니다 (무료).
|
||||
|
||||
## 변환하기 — `VoiceChanger.exe`
|
||||
|
||||
1. 목소리 모델을 고릅니다. 직접 학습한 모델이 위에, 예시 모델이 아래에 나옵니다.
|
||||
2. **내 목소리 성별**을 고르면 성별이 다른 모델은 음높이를 ±12반음(한 옥타브)으로 자동으로 맞춥니다. 슬라이더로 더 맞출 수 있고, 켜 둔 채로 바꿔도 바로 적용됩니다.
|
||||
3. **마이크**에 내 마이크, **출력**에 `CABLE Input (VB-Audio Virtual Cable)` 을 고릅니다. 디스코드 음성 설정의 입력 장치를 `CABLE Output` 으로 바꿉니다.
|
||||
4. 내 귀로 확인하려면 **내 귀로 듣기**를 켜고 헤드셋을 고릅니다.
|
||||
5. **▶ 변환 시작**. 처음에는 모델을 불러오느라 몇 초 걸립니다. 아래에 처리 시간(ms)이 나옵니다.
|
||||
|
||||
- 지연: 보통(0.25초)이 기본입니다. RTX 5070 Ti 는 낮음(0.13초)도 됩니다. 소리가 끊기면 한 단계 올리세요.
|
||||
- 잡음 무시: 이 크기(dB)보다 작은 소리는 변환하지 않습니다. 키보드 소리가 들어가면 올리세요.
|
||||
- 설정은 `config/settings.json` 에 저장돼 다음에 그대로 열립니다.
|
||||
|
||||
## 목소리 모델 학습 — `train.bat`
|
||||
|
||||
동의 사이트 서버에서 학습 데이터를 꺼냅니다 (동의 중인 사람만 꺼내짐):
|
||||
|
||||
```bash
|
||||
cd consent-recorder
|
||||
npm run cli -- export <디스코드 아이디> ./dataset_<이름> # 48kHz 모노 wav, -18 LUFS + 리미터
|
||||
```
|
||||
|
||||
그 폴더를 게임PC 로 옮기고:
|
||||
|
||||
```bat
|
||||
train.bat D:\dataset_승한 "승한" male
|
||||
train.bat D:\dataset_지원 "지원" female --epochs 300
|
||||
```
|
||||
|
||||
- 순서: 자르기 → 음높이(rmvpe) · 특징(contentvec) 뽑기 → 학습(기본 200 epoch, batch 8) → 검색 인덱스 → `models\<아이디>\` 에 넣기
|
||||
- 녹음은 최소 10분, 좋게는 20~30분. 10분보다 짧으면 경고하고, 1분보다 짧으면 학습하지 않습니다
|
||||
- export 결과가 아닌 녹음이면 `--normalize` 를 붙입니다. javis_bot · 겜녹이와 같은 기준(-18 LUFS + 리미터)으로 맞춥니다
|
||||
- 학습 중간 파일은 `training\`, 평준화한 녹음은 `datasets\` 에 남습니다. 다 끝나면 지워도 됩니다
|
||||
|
||||
동의를 철회한 사람의 모델은 `models\<아이디>` 폴더와 `training\<아이디>` 폴더를 지웁니다. 녹음 서버의 녹음은 철회할 때 자동으로 지워지지만, 이 PC 에 옮긴 녹음 폴더와 모델은 직접 지워야 합니다.
|
||||
|
||||
## 한국어 예시 모델 — `examples.bat`
|
||||
|
||||
공개 데이터셋으로 예시 모델 4개를 이 PC 에서 학습합니다. RTX 5070 Ti 기준 몇 시간 걸리니 한 번만 돌리면 됩니다.
|
||||
|
||||
| 모델 | 데이터 | 라이선스 |
|
||||
|------|--------|----------|
|
||||
| 예시 여성 1 (KSS) | KSS Dataset, 성우 1명, 44.1kHz → 48kHz 모델 | CC BY-NC-SA 4.0 (비상업) |
|
||||
| 예시 남성 1 · 남성 2 · 여성 2 (Zeroth 화자 번호) | Zeroth-Korean (OpenSLR 40), 16kHz → 32kHz 모델 | CC BY 4.0 |
|
||||
|
||||
- 화자마다 녹음 20분을 씁니다. KSS 는 약 540MB, Zeroth 는 10GB 압축 파일을 흘려 읽다가 필요한 화자가 모이면 멈춥니다
|
||||
- Zeroth 원본이 16kHz 라 Zeroth 예시는 KSS 예시보다 고음이 덜 또렷합니다
|
||||
- 실존 인물(연예인 등) 목소리 모델은 넣지 않았습니다. 예시도 데이터셋 라이선스 범위(비상업, 출처 표기) 안에서만 쓰세요
|
||||
|
||||
## 폴더
|
||||
|
||||
```
|
||||
VoiceChanger.exe 실행기 (env\Scripts\pythonw.exe app\voice_changer.py 를 띄움, 소스 launcher\launcher.c)
|
||||
install.bat 설치 (scripts\install.ps1)
|
||||
train.bat 학습 (app\train.py)
|
||||
examples.bat 예시 모델 (app\examples.py)
|
||||
app\ 화면 · 학습 · 모델 목록 코드
|
||||
models\<아이디>\ model.pth · model.index · info.json(이름 · 성별 · 출처 · 라이선스)
|
||||
engine\ env\ tools\ 설치하면 생기는 폴더 (엔진 · Python · uv)
|
||||
```
|
||||
|
||||
## 배포 파일 만들기 (리눅스)
|
||||
|
||||
```bash
|
||||
voice-changer/scripts/build-release.sh # mingw 로 VoiceChanger.exe 를 빌드하고 dist/voice-changer-win.zip 을 만듦
|
||||
```
|
||||
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())
|
||||
8
voice-changer/examples.bat
Normal file
8
voice-changer/examples.bat
Normal file
@@ -0,0 +1,8 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0"
|
||||
if not exist "env\Scripts\python.exe" (echo 먼저 install.bat 을 실행해 주세요. & pause & exit /b 1)
|
||||
echo 한국어 예시 모델 4개를 공개 데이터셋으로 학습합니다. RTX 5070 Ti 기준 몇 시간 걸립니다.
|
||||
set PYTHONUTF8=1
|
||||
"env\Scripts\python.exe" app\examples.py %*
|
||||
pause
|
||||
6
voice-changer/install.bat
Normal file
6
voice-changer/install.bat
Normal file
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0"
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\install.ps1"
|
||||
if errorlevel 1 (echo. & echo 설치 실패. 위 메시지를 확인해 주세요.)
|
||||
pause
|
||||
29
voice-changer/launcher/launcher.c
Normal file
29
voice-changer/launcher/launcher.c
Normal file
@@ -0,0 +1,29 @@
|
||||
/* VoiceChanger.exe: 같은 폴더의 env\Scripts\pythonw.exe 로 app\voice_changer.py 를 띄우는 실행기.
|
||||
빌드: x86_64-w64-mingw32-gcc -O2 -municode -mwindows launcher.c -o VoiceChanger.exe */
|
||||
#include <windows.h>
|
||||
#include <wchar.h>
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE h, HINSTANCE p, PWSTR cmd, int show) {
|
||||
wchar_t dir[MAX_PATH], py[MAX_PATH], script[MAX_PATH], line[3 * MAX_PATH];
|
||||
DWORD n = GetModuleFileNameW(NULL, dir, MAX_PATH);
|
||||
if (n == 0 || n >= MAX_PATH) return 1;
|
||||
wchar_t *slash = wcsrchr(dir, L'\\');
|
||||
if (slash) *slash = 0;
|
||||
_snwprintf(py, MAX_PATH, L"%ls\\env\\Scripts\\pythonw.exe", dir);
|
||||
_snwprintf(script, MAX_PATH, L"%ls\\app\\voice_changer.py", dir);
|
||||
if (GetFileAttributesW(py) == INVALID_FILE_ATTRIBUTES) {
|
||||
MessageBoxW(NULL, L"아직 설치되지 않았습니다.\n같은 폴더의 install.bat 을 먼저 실행해 주세요.", L"음성 변환기", MB_ICONWARNING);
|
||||
return 1;
|
||||
}
|
||||
_snwprintf(line, 3 * MAX_PATH, L"\"%ls\" \"%ls\"", py, script);
|
||||
SetEnvironmentVariableW(L"PYTHONUTF8", L"1");
|
||||
STARTUPINFOW si = {sizeof(si)};
|
||||
PROCESS_INFORMATION pi;
|
||||
if (!CreateProcessW(py, line, NULL, NULL, FALSE, 0, NULL, dir, &si, &pi)) {
|
||||
MessageBoxW(NULL, L"음성 변환기를 시작하지 못했습니다. install.bat 을 다시 실행해 주세요.", L"음성 변환기", MB_ICONERROR);
|
||||
return 1;
|
||||
}
|
||||
CloseHandle(pi.hThread);
|
||||
CloseHandle(pi.hProcess);
|
||||
return 0;
|
||||
}
|
||||
0
voice-changer/models/.gitkeep
Normal file
0
voice-changer/models/.gitkeep
Normal file
17
voice-changer/scripts/build-release.sh
Executable file
17
voice-changer/scripts/build-release.sh
Executable file
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# VoiceChanger.exe 를 mingw 로 빌드하고 Windows 배포 zip 을 만든다. 엔진 · torch 는 install.bat 이 게임PC 에서 받는다.
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
out="${1:-$here/dist}"
|
||||
stage="$(mktemp -d "${TMPDIR:-$HOME/.tmp}/vc-release.XXXXXX")"
|
||||
trap 'rm -rf "$stage"' EXIT
|
||||
pkg="$stage/voice-changer"
|
||||
mkdir -p "$pkg/scripts" "$pkg/models" "$pkg/launcher" "$out"
|
||||
x86_64-w64-mingw32-gcc -O2 -municode -mwindows -finput-charset=UTF-8 -o "$pkg/VoiceChanger.exe" "$here/launcher/launcher.c"
|
||||
cp "$here"/*.bat "$here/README.md" "$pkg/"
|
||||
cp "$here/scripts/install.ps1" "$pkg/scripts/"
|
||||
cp "$here/launcher/launcher.c" "$pkg/launcher/"
|
||||
mkdir -p "$pkg/app" && cp "$here"/app/*.py "$pkg/app/"
|
||||
rm -f "$out/voice-changer-win.zip"
|
||||
(cd "$stage" && zip -qr "$out/voice-changer-win.zip" voice-changer)
|
||||
echo "$out/voice-changer-win.zip"
|
||||
63
voice-changer/scripts/install.ps1
Normal file
63
voice-changer/scripts/install.ps1
Normal file
@@ -0,0 +1,63 @@
|
||||
# 음성 변환기 설치: uv → Python 3.12 → Applio 엔진(고정 커밋) → torch(CUDA 12.8, RTX 50 지원) → 기본 모델
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ProgressPreference = "SilentlyContinue"
|
||||
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $Root
|
||||
|
||||
# Applio (MIT) 고정 커밋. 올릴 때는 이 값만 바꾸고 다시 install.bat
|
||||
$ApplioCommit = "6d5d9511b7e719b1f613362bc767e841ad72fa72"
|
||||
$UvVersion = "0.13.7"
|
||||
|
||||
$Tools = Join-Path $Root "tools"
|
||||
$Uv = Join-Path $Tools "uv.exe"
|
||||
$Engine = Join-Path $Root "engine"
|
||||
$VenvDir = Join-Path $Root "env"
|
||||
New-Item -ItemType Directory -Force $Tools | Out-Null
|
||||
|
||||
if (-not (Test-Path $Uv)) {
|
||||
Write-Host "[1/5] uv 받기..."
|
||||
$zip = Join-Path $Tools "uv.zip"
|
||||
Invoke-WebRequest "https://github.com/astral-sh/uv/releases/download/$UvVersion/uv-x86_64-pc-windows-msvc.zip" -OutFile $zip
|
||||
Expand-Archive $zip -DestinationPath $Tools -Force
|
||||
Remove-Item $zip
|
||||
} else { Write-Host "[1/5] uv 있음" }
|
||||
|
||||
$stamp = Join-Path $Engine ".commit"
|
||||
if (-not (Test-Path $stamp) -or (Get-Content $stamp) -ne $ApplioCommit) {
|
||||
Write-Host "[2/5] 엔진(Applio $($ApplioCommit.Substring(0,7))) 받기..."
|
||||
$zip = Join-Path $Tools "applio.zip"
|
||||
Invoke-WebRequest "https://github.com/IAHispano/Applio/archive/$ApplioCommit.zip" -OutFile $zip
|
||||
$tmp = Join-Path $Tools "applio_tmp"
|
||||
if (Test-Path $tmp) { Remove-Item -Recurse -Force $tmp }
|
||||
Expand-Archive $zip -DestinationPath $tmp -Force
|
||||
$src = Get-ChildItem $tmp | Select-Object -First 1
|
||||
# 받아 둔 기본 모델(rvc/models)은 남기고 코드만 바꾼다
|
||||
if (Test-Path $Engine) {
|
||||
Get-ChildItem $Engine -Exclude "rvc","ffmpeg.exe","ffprobe.exe" | Remove-Item -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Force $Engine | Out-Null
|
||||
Copy-Item -Recurse -Force (Join-Path $src.FullName "*") $Engine
|
||||
Remove-Item -Recurse -Force $tmp, $zip
|
||||
Set-Content $stamp $ApplioCommit
|
||||
} else { Write-Host "[2/5] 엔진 있음" }
|
||||
|
||||
$env:UV_PYTHON_INSTALL_DIR = Join-Path $Tools "python"
|
||||
$env:UV_CACHE_DIR = Join-Path $Tools "uv-cache"
|
||||
if (-not (Test-Path (Join-Path $VenvDir "Scripts\python.exe"))) {
|
||||
Write-Host "[3/5] Python 3.12 환경 만들기..."
|
||||
& $Uv venv --python 3.12 $VenvDir
|
||||
if ($LASTEXITCODE -ne 0) { throw "Python 환경을 만들지 못했습니다" }
|
||||
} else { Write-Host "[3/5] Python 환경 있음" }
|
||||
|
||||
Write-Host "[4/5] 패키지 설치 (torch CUDA 12.8 포함, 처음엔 약 4GB)..."
|
||||
& $Uv pip install --python (Join-Path $VenvDir "Scripts\python.exe") -r (Join-Path $Engine "requirements-engine.txt") pyarrow `
|
||||
--extra-index-url https://download.pytorch.org/whl/cu128 --index-strategy unsafe-best-match
|
||||
if ($LASTEXITCODE -ne 0) { throw "패키지 설치에 실패했습니다" }
|
||||
|
||||
Write-Host "[5/5] 기본 모델 받기 · GPU 확인..."
|
||||
& (Join-Path $VenvDir "Scripts\python.exe") (Join-Path $Root "app\setup_engine.py")
|
||||
if ($LASTEXITCODE -ne 0) { throw "기본 모델 받기 또는 GPU 확인에 실패했습니다" }
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "설치가 끝났습니다. VoiceChanger.exe 로 실행하세요."
|
||||
49
voice-changer/tests/test_models.py
Normal file
49
voice-changer/tests/test_models.py
Normal file
@@ -0,0 +1,49 @@
|
||||
"""모델 목록 · 자동 음높이 (엔진 없이 도는 부분). 실행: python -m unittest discover -s voice-changer/tests"""
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app"))
|
||||
from common import slug # noqa: E402
|
||||
from models import auto_pitch, list_models # noqa: E402
|
||||
|
||||
|
||||
def make(root: Path, mid: str, info: dict | None, index=True, pth=True):
|
||||
d = root / mid
|
||||
d.mkdir()
|
||||
if pth:
|
||||
(d / "model.pth").write_bytes(b"x")
|
||||
if index:
|
||||
(d / "model.index").write_bytes(b"x")
|
||||
if info is not None:
|
||||
(d / "info.json").write_text(json.dumps(info, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
class ModelsTest(unittest.TestCase):
|
||||
def test_list_models_orders_own_before_examples_and_skips_broken(self):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
root = Path(t)
|
||||
make(root, "example_kss", {"name": "예시 여성 1 (KSS)", "gender": "female", "example": True})
|
||||
make(root, "seunghan", {"name": "승한", "gender": "male"}, index=False)
|
||||
make(root, "broken", {"name": "pth 없음"}, pth=False)
|
||||
make(root, "noinfo", None)
|
||||
ms = list_models(root)
|
||||
self.assertEqual([m.id for m in ms], ["noinfo", "seunghan", "example_kss"])
|
||||
self.assertIsNone(ms[1].index)
|
||||
self.assertEqual(ms[1].label, "승한 (남성)")
|
||||
self.assertEqual(ms[2].label, "예시 여성 1 (KSS) (여성 · 예시)")
|
||||
|
||||
def test_auto_pitch_shifts_one_octave_across_genders(self):
|
||||
self.assertEqual(auto_pitch("male", "female"), 12)
|
||||
self.assertEqual(auto_pitch("female", "male"), -12)
|
||||
self.assertEqual(auto_pitch("male", "male"), 0)
|
||||
|
||||
def test_slug(self):
|
||||
self.assertEqual(slug("Seung Han!"), "seung_han")
|
||||
self.assertEqual(slug("승한"), "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
12
voice-changer/train.bat
Normal file
12
voice-changer/train.bat
Normal file
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0"
|
||||
if not exist "env\Scripts\python.exe" (echo 먼저 install.bat 을 실행해 주세요. & pause & exit /b 1)
|
||||
if "%~3"=="" (
|
||||
echo 사용법: train.bat ^<녹음 폴더^> ^<모델 이름^> ^<male^|female^> [--epochs 200]
|
||||
echo 예: train.bat D:\dataset\seunghan "승한" male
|
||||
pause & exit /b 1
|
||||
)
|
||||
set PYTHONUTF8=1
|
||||
"env\Scripts\python.exe" app\train.py %*
|
||||
pause
|
||||
Reference in New Issue
Block a user