Compare commits

11 Commits

Author SHA1 Message Date
EJClaw
f45d349f96 consent-recorder: let each consenter pick which servers to record in
The site lists only servers the bot and the user share (single-member REST
fetch, no privileged intent). Consent requires at least one server; the
choice can be changed later and removed servers stop recording at once.
Consent text mentions the server choice, so CONSENT_VERSION is bumped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:53:14 +09:00
EJClaw
3a40645b12 voice-changer: upgrade cleanup deletes only files shipped by earlier builds
secure-dir.ps1 Prepare used to delete every root file (and whole scripts/app/launcher/uninstall
dirs) when upgrading. It now removes only the named files of earlier distributions (plus the
uninstall logs, which run elevated) and empty dirs; any other file stays and is only re-owned
by Administrators with inherited permissions.

Windows 11 VM: 21b4278 install + root sample.wav, models\keep.wav, scripts\note.txt ->
upgrade -> SHA256 unchanged for all three (also after silent uninstall).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:22:44 +09:00
EJClaw
c62bd9cf39 voice-changer: lock install folder ownership, migrate old mic backup, refresh comm modes on upgrade
- installer/secure-dir.ps1 (run elevated from tmp):
  CheckParent: refuse folders whose nearest existing parent is not a drive root or owned by
  Administrators/SYSTEM/TrustedInstaller.
  Prepare (before files are copied): owner Administrators + protected DACL (SY/BA full, Users RX),
  verify, abort setup on failure; refuse links pointing outside the folder; on upgrade delete the
  old executable parts (scripts/app/launcher/uninstall/root files) that 21b4278 left user-writable.
  Finish: Users modify only on data dirs; verify every admin-run file is admin-owned and not
  user-writable, otherwise skip APO registration and engine download.
- mic-apo.ps1: migrate config\mic-apo-backup.json to apo\ with value validation (CLSID/mode GUID/
  DWORD only, own CLSID stripped), never record our own APO as the original value, upgrade the
  DEFAULT-only mode list written by 21b4278 to DEFAULT/COMMUNICATIONS/SPEECH/MEDIA, remove the
  old config\mic-apo.json.

Windows 11 VM: user-precreated folder -> owner BA, basic-user WRITE_DAC/WRITE_OWNER/grant/icacls/
write/rename all ERROR_ACCESS_DENIED; user-owned parent refused (CheckParent exit 20);
21b4278 install -> upgrade: backup migrated, modes refreshed, Communications capture 440 Hz,
uninstall restores FxProperties to the pre-install state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:01:36 +09:00
EJClaw
ffc553851a voice-changer: fix review findings (install-folder ACL, scoped uninstall delete, comm-mode APO, reconnect)
- installer: lock the install folder (admins/SYSTEM full, Users read) and grant Users modify only on
  data dirs (models/training/datasets/config/cache/env/engine/tools); download the engine as the
  original (non-elevated) user; refuse non-empty folders; uninstall deletes only app-managed dirs
- mic-apo.ps1: backup/list/log moved to admin-only apo\; register SFX for DEFAULT, COMMUNICATIONS,
  SPEECH and MEDIA when the endpoint has no mode list; admin TEMP for Add-Type; run log + trap
- app: '마이크 다시 연결' launches one elevated PowerShell via ShellExecuteExW(runas) with
  double-quoted -File args and waits for its exit code; shows apo\mic-apo.log on failure
- tests: reconnect argument splitting (Korean/space/quote/drive root)

Verified on the Windows 11 VM: basic-user token gets ERROR_ACCESS_DENIED on scripts/apo/exe/
uninstall/app and write access only on data dirs; Communications-category capture receives the
converted signal (440 Hz); reconnect exits 0 from a Korean+space install path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:00:20 +09:00
EJClaw
21b4278b77 voice-changer: one-click installer, mic APO instead of virtual cable, keep all files in install folder
- apo/: VoiceChangerAPO.dll (SFX APO on the real mic, built with mingw). When the app converts,
  the mic's own stream carries the converted voice; otherwise it passes the real voice through.
  Shared-memory protocol in vccore.h, Python side app/mic_bridge.py
- scripts/mic-apo.ps1: register/unregister on every capture endpoint with admin value rights only
  (no ACL changes unless FxProperties is missing), originals backed up and restored
- app: mic is the conversion target (WASAPI names), no output device, '마이크 다시 연결' button,
  44.1k<->48k streaming resample, caches/temp redirected into <install>/cache
- installer/VoiceChanger.iss (Inno Setup): choose install folder, register APO, download engine
  into that folder, uninstall restores mic settings and asks before deleting models
- install.ps1: uv python --no-bin --no-registry, temp/caches inside the folder, uv cache clean
- tests: C core compiled with gcc against the Python bridge; converter pump 44.1k round trip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:33:15 +09:00
EJClaw
ab599c0751 voice-changer: always stream at 48kHz, redo interrupted example extraction
- Applio's realtime engine treats incoming audio as 48kHz; opening a 44.1kHz
  device at its default rate skewed pitch and timing. Streams now always open
  at 48kHz (MME/DirectSound resample, WASAPI auto_convert), with a clear error
  if a device refuses it.
- KSS/Zeroth example datasets write a completion marker (with minutes) last;
  a partial folder from an interrupted run is wiped and re-extracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:41:06 +09:00
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
EJClaw
8da3e713d0 consent-recorder: fix review findings
- /delete discards the in-progress utterance before deleting files
- keep the current channel even when the bot itself fills it (joinable=false)
- bind OAuth state to the browser via a short-lived cookie
- reject consent submitted from a page showing an older consent version
- regression tests for all four

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:47:07 +09:00
EJClaw
6e0801ea1c Add consent site + consent-only follow recorder bot
Discord OAuth login -> explicit consent (3 checkboxes, versioned text) ->
bot follows consenting users into voice channels and records only their
per-user streams. Revoke stops recording immediately and optionally deletes
files; consent log kept; export to training wav only for active consents.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:43:06 +09:00
EJClaw
0abadfb7e2 Merge remote-tracking branch 'origin/main' into codex/owner/voice_copy 2026-11-11 11:21:03 +09:00
EJClaw
d1b95bdc6d chore: initialize paired workspace 2026-07-30 01:37:20 +09:00
49 changed files with 6011 additions and 0 deletions

View File

@@ -8,6 +8,14 @@
- 지원 언어: 한국어 · English · 中文 · 日本語 · 독일어 · 프랑스어 · 러시아어 · 포르투갈어 · 스페인어 · 이탈리아어
- UI: 파일 업로드 또는 마이크 녹음 → 전사 입력 → 합성할 텍스트 입력 → 생성/재생/다운로드
## 녹음 동의 사이트 + 따라가며 녹음하는 봇
본인이 디스코드로 로그인해 녹음에 동의한 사람만 음성채널에서 따라가며 그 사람 목소리만 녹음합니다 (음성 모델 학습 데이터용). [`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 권장)

View File

@@ -0,0 +1,16 @@
# 디스코드 개발자 포털 (https://discord.com/developers/applications) 에서 만든 앱 값
DISCORD_BOT_TOKEN=
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
# 사이트 주소 (OAuth2 Redirects 에 <PUBLIC_URL>/callback 을 등록해야 함)
PUBLIC_URL=https://voice.example.com
# 동의 화면에 "누가 이 목소리 모델을 쓰는지"로 나오는 이름 (운영자 디스코드 계정 293719842274541579 의 닉네임)
# 바꾸면 src/consent-text.ts 의 CONSENT_VERSION 도 올려서 모두에게 다시 동의를 받는다
OPERATOR_NAME=사금향
# 녹음할 디스코드 서버 아이디 (쉼표로 여러 개). 비우면 봇이 들어간 모든 서버
ALLOWED_GUILD_IDS=
HOST=127.0.0.1
PORT=8787
DATA_DIR=./data
# 봇이 음성채널에 들어갈 때 그 채널 채팅에 녹음 안내를 남김 (1/0)
CHANNEL_NOTICE=1

4
consent-recorder/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
node_modules/
dist/
data/
.env

View File

@@ -0,0 +1,52 @@
# 녹음 동의 사이트 + 따라가며 녹음하는 봇
본인이 직접 사이트에서 **디스코드로 로그인하고 녹음 동의**를 누른 사람만, 디스코드 음성채널에 따라 들어가 **그 사람 목소리만** 녹음합니다.
녹음은 나중에 그 사람 목소리 모델(RVC 등)을 학습하는 데이터로 씁니다.
## 동작
- 사이트 (`src/site.ts`): 디스코드 로그인(OAuth2 `identify` 권한만) → 동의 문구 + 체크 3개(계정 주인 · AI 음성 모델 용도 이해 · 만 14세 이상)를 모두 직접 체크해야 동의.
**녹음할 서버**도 같이 고른다 (봇과 내가 함께 들어가 있는 서버만 보이고, 하나 이상 골라야 동의). 동의한 뒤에도 사이트에서 언제든 바꿀 수 있고, 뺀 서버에서는 바로 녹음을 멈춘다.
내 상태(동의 여부 · 지금 녹음 중인 채널 · 녹음 개수/길이), 동의 철회(녹음 파일 같이 삭제 기본), 녹음 파일만 삭제, 로그아웃.
- 봇 (`src/bot.ts`): 동의한 사람이 **녹음할 서버로 고른 서버**의 음성채널에 들어가면 따라 들어가고, 옮기면 따라 옮기고, 동의자가 모두 나가면 나간다.
서버마다 음성 연결은 하나라서 한 서버에서 동의자가 여러 채널에 흩어져 있으면 지금 채널 유지 → 방금 움직인 사람 → 동의자가 많은 채널 순으로 고른다 (`src/follow.ts`).
- 녹음 (`src/recorder.ts`): 디스코드가 사람별로 따로 보내는 음성 스트림 중 **동의한 사람 것만 구독**한다. 동의 안 한 사람의 소리는 받지도 저장하지도 않는다.
말이 0.8초 끊길 때마다 파일 하나(최대 30초, 0.5초 미만 버림), Opus 그대로 `data/recordings/<아이디>/<날짜>/<id>.ogg`. 말하는 도중 철회하면 쓰던 파일도 버린다.
- 알림: 봇이 채널에 들어가면 그 채널 채팅에 녹음 안내(누구 목소리만 녹음하는지 + 사이트 주소)를 남기고, 봇 상태를 "🔴 동의한 사람 녹음 중"으로 바꾼다.
- 동의 기록: `consent_log` 테이블에 동의 · 철회 · 삭제 · 내보내기를 시각과 문구 버전으로 남긴다. 동의 문구를 바꾸면 `src/consent-text.ts` 의 `CONSENT_VERSION` 을 올린다 → 예전 동의자는 다시 동의할 때까지 녹음하지 않는다.
- 보안: OAuth state 는 로그인을 시작한 브라우저 쿠키와 맞춰 확인, 동의 제출은 화면의 문구 버전이 지금 버전과 같을 때만, 세션 · state 는 해시로만 저장, 디스코드 액세스 토큰은 저장하지 않음, 모든 form 에 CSRF 토큰 + Origin 확인, 클릭재킹 차단(`frame-ancestors 'none'`, `X-Frame-Options: DENY`), https 쿠키는 `__Host-` + Secure.
- 디스코드 음성 종단간 암호화(DAVE)는 `@discordjs/voice` 0.19 + `@snazzah/davey` 로 지원.
## 준비 (디스코드 개발자 포털)
1. https://discord.com/developers/applications 에서 앱 만들기
2. **Bot** 탭: 토큰 발급 → `DISCORD_BOT_TOKEN`. Privileged Intent 는 필요 없음
3. **OAuth2** 탭: Client ID / Client Secret → `DISCORD_CLIENT_ID` / `DISCORD_CLIENT_SECRET`, Redirects 에 `<PUBLIC_URL>/callback` 추가
4. 봇 초대: OAuth2 URL Generator 에서 scope `bot`, 권한 `View Channels` · `Connect` · `Send Messages`(녹음 안내용)
## 실행
```bash
cd consent-recorder
npm install
cp .env.example .env # 값 채우기
npm run build
npm start # 사이트 http://HOST:PORT + 봇
```
사이트는 기본 `127.0.0.1:8787` 에 뜬다. 바깥에서는 리버스 프록시(NPMplus 등)로 https 도메인을 붙인다 (`PUBLIC_URL` 은 https 여야 함).
## 학습 데이터 꺼내기
```bash
npm run cli -- status # 동의자 · 녹음 양
npm run cli -- export <디스코드 아이디> ./dataset # 48kHz 모노 wav, -18 LUFS 평준화 + 리미터 (ffmpeg 필요)
```
`export` 는 **지금 동의 중인 사람만** 내보낸다 (철회했거나 문구가 바뀐 사람은 거절). 철회한 사람의 이미 학습된 모델은 이 프로그램 밖에 있으므로 운영자가 직접 지워야 한다.
## 테스트
```bash
npm test # 가짜 디스코드 OAuth 서버로 로그인(state 쿠키) → 동의(문구 버전) → 철회/삭제, CSRF · 클릭재킹, 채널 고르기 · 정원 찬 채널 유지, 동의자만 녹음 · 삭제 시 진행 중 녹음 폐기
```

1138
consent-recorder/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
{
"name": "voice-copy-consent-recorder",
"version": "0.1.0",
"private": true,
"description": "디스코드 로그인으로 본인 동의를 받은 사람만 따라가 목소리를 녹음하는 봇 + 동의 사이트",
"type": "module",
"main": "dist/main.js",
"engines": { "node": ">=22.13" },
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"start": "node dist/main.js",
"cli": "node dist/cli.js",
"test": "node --import tsx --test test/*.test.ts"
},
"dependencies": {
"@discordjs/voice": "^0.19.2",
"discord.js": "^14.27.0"
},
"devDependencies": {
"@types/node": "^22.18.0",
"tsx": "^4.20.6",
"typescript": "^5.9.3"
}
}

207
consent-recorder/src/bot.ts Normal file
View File

@@ -0,0 +1,207 @@
import {
entersState,
getVoiceConnection,
joinVoiceChannel,
VoiceConnectionStatus,
type VoiceConnection,
} from '@discordjs/voice';
import { ActivityType, ChannelType, Client, GatewayIntentBits, PermissionFlagsBits, type Guild, type VoiceBasedChannel } from 'discord.js';
import type { Config } from './config.js';
import type { Store } from './db.js';
import { pickChannel, type Presence } from './follow.js';
import { Recorder } from './recorder.js';
/**
* 동의한 사람을 따라 음성채널에 들어가 그 사람 목소리만 녹음하는 봇.
* 서버마다 음성 연결은 하나라서, 한 서버 안에서 동의자가 여러 채널에 흩어져 있으면 한 채널만 따라간다 (follow.ts).
*/
export class FollowBot {
readonly client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
private recorders = new Map<string, Recorder>();
/** 서버별로 순서대로 처리 (들어가는 중에 또 움직여도 꼬이지 않게) */
private queue = new Map<string, Promise<void>>();
constructor(
private cfg: Config,
private store: Store,
) {
this.client.once('clientReady', () => {
console.log(`[bot] 로그인: ${this.client.user?.tag}`);
this.updatePresence();
for (const g of this.client.guilds.cache.values()) this.schedule(g);
});
this.client.on('voiceStateUpdate', (oldS, newS) => {
const me = this.client.user?.id;
// 누가 봇을 끊거나 다른 채널로 옮김: 정리하고 다시 판단 (동의자가 있는 채널로 돌아감)
const rec = this.recorders.get(newS.guild.id);
if (newS.id === me && rec && newS.channelId !== rec.channelId) this.drop(newS.guild.id);
if (newS.id === me || this.store.isConsentedIn(newS.id, newS.guild.id) || this.recorders.has(newS.guild.id)) {
if (oldS.channelId && oldS.channelId !== newS.channelId) this.recorders.get(oldS.guild.id)?.stopUser(newS.id);
this.schedule(newS.guild, newS.id);
}
});
this.client.on('guildCreate', (g) => this.schedule(g));
}
async start(): Promise<void> {
await this.client.login(this.cfg.botToken);
}
async stop(): Promise<void> {
for (const gid of [...this.recorders.keys()]) this.drop(gid);
for (const g of this.client.guilds.cache.values()) getVoiceConnection(g.id)?.destroy();
await this.client.destroy();
}
/** 사이트에서 동의 · 철회 · 녹음할 서버를 바꾼 직후: 그 사람이 있는 서버를 바로 다시 판단 */
consentChanged(userId: string): void {
for (const [gid, r] of this.recorders) if (!this.store.isConsentedIn(userId, gid)) r.stopUser(userId);
for (const g of this.client.guilds.cache.values()) {
if (g.voiceStates.cache.get(userId)?.channelId || this.recorders.has(g.id)) this.schedule(g, userId);
}
}
/** 이 사람의 진행 중인 녹음을 버린다 (구독도 끊음. 다시 말하면 동의 상태대로 새로 녹음) */
discardActive(userId: string): void {
for (const r of this.recorders.values()) r.stopUser(userId);
}
/** 봇이 들어가 있고 이 사람도 들어가 있는 서버 (사이트에서 녹음할 서버로 고를 수 있는 곳) */
async userGuilds(userId: string): Promise<{ id: string; name: string }[]> {
const guilds = [...this.client.guilds.cache.values()].filter((g) => this.allowedGuild(g));
const found = await Promise.all(
guilds.map((g) =>
g.members.fetch(userId).then(
() => ({ id: g.id, name: g.name }),
() => null, // 이 서버에 없는 사람 (Unknown Member)
),
),
);
return found.filter((g): g is { id: string; name: string } => !!g).sort((a, b) => a.name.localeCompare(b.name, 'ko'));
}
/** 이 사람을 지금 녹음 중인 채널 이름 */
recordingNow(userId: string): string | null {
for (const [gid, r] of this.recorders) {
const g = this.client.guilds.cache.get(gid);
if (g?.voiceStates.cache.get(userId)?.channelId === r.channelId) return g.channels.cache.get(r.channelId)?.name ?? '음성채널';
}
return null;
}
private schedule(guild: Guild, preferUserId?: string): void {
const prev = this.queue.get(guild.id) ?? Promise.resolve();
const next = prev.then(() => this.reconcile(guild, preferUserId)).catch((e) => console.error(`[bot] ${guild.name} 처리 오류`, e));
this.queue.set(guild.id, next);
}
private allowedGuild(guild: Guild): boolean {
return !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id);
}
private canJoin(ch: VoiceBasedChannel): boolean {
const me = ch.guild.members.me;
if (!me || ch.type === ChannelType.GuildStageVoice) return false;
const p = ch.permissionsFor(me);
return !!p?.has(PermissionFlagsBits.ViewChannel) && p.has(PermissionFlagsBits.Connect) && ch.joinable;
}
/**
* 동의자가 있는 채널 목록. 봇이 이미 들어가 있는 채널은 입장 가능 여부를 다시 보지 않는다
* (봇이 들어가 정원이 차면 joinable 이 false 가 되어 나갔다 들어오기를 반복하던 것)
*/
consentedPresence(guild: Guild): Presence[] {
const current = this.recorders.get(guild.id)?.channelId ?? null;
const out: Presence[] = [];
for (const vs of guild.voiceStates.cache.values()) {
if (!vs.channelId || vs.id === this.client.user?.id || vs.member?.user.bot) continue;
if (!this.store.isConsentedIn(vs.id, guild.id)) continue;
const ch = vs.channel;
if (ch && (ch.id === current || this.canJoin(ch))) out.push({ userId: vs.id, channelId: vs.channelId });
}
return out;
}
private async reconcile(guild: Guild, preferUserId?: string): Promise<void> {
const current = this.recorders.get(guild.id)?.channelId ?? null;
const want = this.allowedGuild(guild) ? pickChannel(current, this.consentedPresence(guild), preferUserId) : null;
if (want === current) return;
this.drop(guild.id);
if (!want) {
console.log(`[bot] ${guild.name}: 동의한 사람이 없어 나감`);
this.updatePresence();
return;
}
const ch = guild.channels.cache.get(want) as VoiceBasedChannel | undefined;
if (!ch) return;
console.log(`[bot] ${guild.name}: "${ch.name}" 채널로 따라 들어감`);
const conn = joinVoiceChannel({
channelId: ch.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
selfDeaf: false, // 들어야 녹음할 수 있다
selfMute: true,
daveEncryption: true,
});
try {
await entersState(conn, VoiceConnectionStatus.Ready, 20_000);
} catch (e) {
console.error(`[bot] ${guild.name}: 음성채널 연결 실패`, e);
conn.destroy();
return;
}
this.watch(guild, conn);
const rec = new Recorder(this.store, this.cfg.dataDir, conn, guild.id, ch.id, (uid) => {
return guild.voiceStates.cache.get(uid)?.channelId === ch.id && this.store.isConsentedIn(uid, guild.id);
});
this.recorders.set(guild.id, rec);
this.updatePresence();
if (this.cfg.channelNotice) await this.notice(ch);
}
private watch(guild: Guild, conn: VoiceConnection): void {
conn.on('error', (e) => console.error('[bot] 음성 연결 오류', e));
conn.on(VoiceConnectionStatus.Disconnected, async () => {
try {
await Promise.race([
entersState(conn, VoiceConnectionStatus.Signalling, 5_000),
entersState(conn, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch {
// 강퇴 · 채널 삭제 등: 정리하고 다시 판단 (동의자가 남아 있으면 다시 따라감)
if (getVoiceConnection(guild.id) === conn) conn.destroy();
this.drop(guild.id);
this.schedule(guild);
}
});
}
/** 음성채널 채팅에 녹음 안내 (권한이 없으면 건너뜀) */
private async notice(ch: VoiceBasedChannel): Promise<void> {
const ids = this.consentedPresence(ch.guild).filter((p) => p.channelId === ch.id).map((p) => `<@${p.userId}>`);
const text =
`🔴 **녹음 안내** — 이 채널에서 녹음에 동의한 사람(${ids.join(', ') || '동의자'})의 목소리만 따로 녹음합니다. ` +
`다른 분의 목소리는 녹음하지 않습니다. 동의 확인 · 철회: ${this.cfg.publicUrl}`;
try {
if ('send' in ch && typeof ch.send === 'function') await ch.send({ content: text, allowedMentions: { parse: [] } });
} catch (e: any) {
console.warn(`[bot] 녹음 안내를 남기지 못함 (${ch.name}): ${e?.message ?? e}`);
}
}
private drop(guildId: string): void {
const r = this.recorders.get(guildId);
if (!r) return;
r.close();
this.recorders.delete(guildId);
getVoiceConnection(guildId)?.destroy();
}
private updatePresence(): void {
const recording = this.recorders.size > 0;
this.client.user?.setPresence({
status: recording ? 'dnd' : 'online',
activities: [{ type: ActivityType.Custom, name: recording ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중', state: recording ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중' }],
});
}
}

View File

@@ -0,0 +1,56 @@
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { loadDotEnv } from './config.js';
import { Store } from './db.js';
/**
* node dist/cli.js status 동의한 사람 · 녹음 양
* node dist/cli.js export <아이디> <폴더> 학습용 wav 로 내보내기 (지금 동의한 사람만)
*/
loadDotEnv(path.resolve('.env'));
const dataDir = path.resolve(process.env.DATA_DIR?.trim() || './data');
const store = new Store(path.join(dataDir, 'consent.db'));
const [cmd, ...args] = process.argv.slice(2);
function fmtMin(ms: number): string {
return `${(ms / 60000).toFixed(1)}분`;
}
if (cmd === 'status') {
const rows = store.db.prepare('SELECT * FROM consents ORDER BY consented_at').all() as any[];
if (!rows.length) console.log('동의 기록이 없습니다');
for (const r of rows) {
const s = store.recordingStats(r.user_id);
const state = store.isConsented(r.user_id) ? '동의' : r.revoked_at ? '철회' : '문구 바뀜(재동의 필요)';
console.log(`${r.user_id}\t${r.display_name || r.username}\t${state}\t녹음 ${s.count}개 · ${fmtMin(s.total_ms)}`);
}
} else if (cmd === 'export') {
const [userId, out] = args;
if (!userId || !out) {
console.error('사용법: export <디스코드 아이디> <내보낼 폴더>');
process.exit(2);
}
// 학습 데이터는 지금 동의 중인 사람 것만 꺼낼 수 있다
if (!store.isConsented(userId)) {
console.error(`${userId} 는 지금 녹음 · 학습에 동의한 상태가 아닙니다. 내보내지 않습니다.`);
process.exit(1);
}
const rows = store.recordings(userId);
fs.mkdirSync(out, { recursive: true });
let ok = 0;
for (const r of rows) {
if (!fs.existsSync(r.path)) continue;
const dst = path.join(out, `${r.id}.wav`);
// 48kHz 모노 · -18 LUFS 평준화 · 리미터
const p = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', r.path, '-ac', '1', '-ar', '48000', '-af', 'loudnorm=I=-18:TP=-1.5:LRA=11,alimiter=limit=0.89', dst]);
if (p.status === 0) ok++;
else console.warn(`변환 실패 ${r.path}: ${p.stderr?.toString().trim()}`);
}
store.log(userId, 'export', Date.now(), `${ok} files -> ${path.resolve(out)}`);
const total = rows.reduce((a, r) => a + r.duration_ms, 0);
console.log(`${ok}/${rows.length}개 내보냄 (${fmtMin(total)}) → ${path.resolve(out)}`);
} else {
console.log('명령: status | export <디스코드 아이디> <폴더>');
}
store.close();

View File

@@ -0,0 +1,59 @@
import fs from 'node:fs';
import path from 'node:path';
export interface Config {
botToken: string;
clientId: string;
clientSecret: string;
/** 사이트 바깥 주소 (끝 / 없음). OAuth 돌아올 주소는 <publicUrl>/callback */
publicUrl: string;
host: string;
port: number;
dataDir: string;
operatorName: string;
/** 비어 있으면 봇이 들어간 모든 서버 */
allowedGuildIds: Set<string>;
channelNotice: boolean;
/** 테스트에서 가짜 디스코드 API 로 바꿀 때만 */
discordApi: string;
discordAuthorizeUrl: string;
}
/** KEY=VALUE 형식 .env (따옴표 · 주석 지원, 이미 있는 환경 변수는 덮어쓰지 않음) */
export function loadDotEnv(file: string): void {
if (!fs.existsSync(file)) return;
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
const m = /^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line);
if (!m || line.trimStart().startsWith('#')) continue;
let v = m[2];
if (/^(['"]).*\1$/.test(v)) v = v.slice(1, -1);
if (process.env[m[1]] === undefined) process.env[m[1]] = v;
}
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env, needBot = true): Config {
const req = (k: string) => {
const v = env[k]?.trim();
if (!v) throw new Error(`환경 변수 ${k} 가 비어 있습니다 (.env.example 참고)`);
return v;
};
const publicUrl = req('PUBLIC_URL').replace(/\/+$/, '');
const u = new URL(publicUrl);
if (u.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(u.hostname)) {
throw new Error('PUBLIC_URL 은 https 여야 합니다 (localhost 만 예외)');
}
return {
botToken: needBot ? req('DISCORD_BOT_TOKEN') : env.DISCORD_BOT_TOKEN?.trim() ?? '',
clientId: req('DISCORD_CLIENT_ID'),
clientSecret: req('DISCORD_CLIENT_SECRET'),
publicUrl,
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() || '사금향',
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',
discordAuthorizeUrl: env.DISCORD_AUTHORIZE_URL?.trim() || 'https://discord.com/oauth2/authorize',
};
}

View File

@@ -0,0 +1,22 @@
/**
* 동의 문구. 문구를 바꾸면 CONSENT_VERSION 을 올린다.
* 버전이 바뀌면 예전 버전에 동의한 사람은 "동의 안 함"으로 보고 녹음하지 않는다 (새 문구에 다시 동의해야 함).
*/
export const CONSENT_VERSION = '2026-11-11.2';
export function consentItems(operator: string): string[] {
return [
'녹음 봇은 내가 동의한 뒤 <b>내가 고른 서버</b>의 디스코드 음성채널에 들어가면 따라 들어와, 그 채널에서 <b>내 목소리만</b> 따로 녹음합니다. 녹음할 서버는 이 사이트에서 언제든 바꿀 수 있습니다. 같은 채널의 다른 사람 목소리는 녹음하지 않습니다.',
`녹음한 목소리로 <b>내 목소리를 흉내 내는 AI 음성 모델</b>을 만듭니다. <b>${operator}</b>이(가) 이 모델로 자기 말소리를 실시간으로 내 목소리처럼 바꿔 디스코드 · 게임 등에서 쓸 수 있습니다.`,
'봇이 채널에 들어오면 채널 채팅에 녹음 안내가 남고, 봇 상태가 "녹음 중"으로 바뀝니다.',
'언제든 이 사이트에서 동의를 철회할 수 있습니다. 철회하면 바로 녹음을 멈추고, 고르면 지금까지의 녹음 파일도 지웁니다. 이미 만든 음성 모델 삭제는 운영자에게 요청하면 지웁니다.',
'녹음 파일은 운영자 서버에만 보관하며 다른 곳에 공개하거나 팔지 않습니다.',
];
}
/** 동의할 때 하나씩 직접 체크해야 하는 항목 (form 이름 → 문구) */
export const CONSENT_CHECKS: Record<string, string> = {
self: '나는 지금 로그인한 디스코드 계정의 주인이며, 내 목소리에 대해 동의합니다.',
model: '내 목소리로 AI 음성 모델을 만들고 위 운영자가 내 목소리처럼 말하는 데 쓰는 것을 이해하고 동의합니다.',
age: '나는 만 14세 이상입니다.',
};

230
consent-recorder/src/db.ts Normal file
View File

@@ -0,0 +1,230 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { CONSENT_VERSION } from './consent-text.js';
export interface DiscordUser {
id: string;
username: string;
global_name?: string | null;
}
export interface ConsentRow {
user_id: string;
username: string;
display_name: string | null;
version: string;
consented_at: number;
revoked_at: number | null;
}
export interface RecordingRow {
id: string;
user_id: string;
guild_id: string;
channel_id: string;
started_at: number;
duration_ms: number;
path: string;
}
export interface SessionRow {
user_id: string;
username: string;
display_name: string | null;
csrf: string;
expires_at: number;
}
const SESSION_MS = 7 * 24 * 3600 * 1000;
const STATE_MS = 10 * 60 * 1000;
export const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
export class Store {
readonly db: DatabaseSync;
constructor(file: string) {
if (file !== ':memory:') fs.mkdirSync(path.dirname(file), { recursive: true });
this.db = new DatabaseSync(file);
this.db.exec(`
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS consents (
user_id TEXT PRIMARY KEY,
username TEXT NOT NULL,
display_name TEXT,
version TEXT NOT NULL,
consented_at INTEGER NOT NULL,
revoked_at INTEGER
);
-- 동의 · 철회 · 삭제 기록 (지우지 않는다: 언제 무엇에 동의했는지 증거)
CREATE TABLE IF NOT EXISTS consent_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
action TEXT NOT NULL,
version TEXT,
at INTEGER NOT NULL,
detail TEXT
);
-- 동의한 사람이 녹음을 허락한 서버 (사이트에서 직접 고른다)
CREATE TABLE IF NOT EXISTS consent_guilds (
user_id TEXT NOT NULL,
guild_id TEXT NOT NULL,
PRIMARY KEY (user_id, guild_id)
);
CREATE TABLE IF NOT EXISTS recordings (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
started_at INTEGER NOT NULL,
duration_ms INTEGER NOT NULL,
path TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS recordings_user ON recordings(user_id, started_at);
CREATE TABLE IF NOT EXISTS sessions (
id_hash TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
username TEXT NOT NULL,
display_name TEXT,
csrf TEXT NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS oauth_states (
state_hash TEXT PRIMARY KEY,
expires_at INTEGER NOT NULL
);
`);
}
// ---- 동의 ----
/** 지금 문구(CONSENT_VERSION)에 동의했고 철회하지 않은 사람만 true */
isConsented(userId: string): boolean {
const r = this.getConsent(userId);
return !!r && r.revoked_at === null && r.version === CONSENT_VERSION;
}
/** 동의했고 이 서버를 녹음할 서버로 골랐을 때만 true */
isConsentedIn(userId: string, guildId: string): boolean {
return this.isConsented(userId) && !!this.db.prepare('SELECT 1 FROM consent_guilds WHERE user_id = ? AND guild_id = ?').get(userId, guildId);
}
consentGuilds(userId: string): string[] {
return (this.db.prepare('SELECT guild_id FROM consent_guilds WHERE user_id = ? ORDER BY guild_id').all(userId) as { guild_id: string }[]).map((r) => r.guild_id);
}
/** 녹음할 서버를 통째로 바꾼다 (빈 목록이면 어디서도 녹음하지 않음) */
setConsentGuilds(userId: string, guildIds: string[], now = Date.now()): void {
const ids = [...new Set(guildIds)].sort();
this.db.exec('BEGIN');
try {
this.db.prepare('DELETE FROM consent_guilds WHERE user_id = ?').run(userId);
const ins = this.db.prepare('INSERT INTO consent_guilds (user_id, guild_id) VALUES (?, ?)');
for (const g of ids) ins.run(userId, g);
this.db.exec('COMMIT');
} catch (e) {
this.db.exec('ROLLBACK');
throw e;
}
this.log(userId, 'guilds', now, ids.join(','));
}
getConsent(userId: string): ConsentRow | undefined {
return this.db.prepare('SELECT * FROM consents WHERE user_id = ?').get(userId) as ConsentRow | undefined;
}
consentedUserIds(): string[] {
return (
this.db.prepare('SELECT user_id FROM consents WHERE revoked_at IS NULL AND version = ?').all(CONSENT_VERSION) as { user_id: string }[]
).map((r) => r.user_id);
}
consent(user: DiscordUser, now = Date.now()): void {
this.db
.prepare(
`INSERT INTO consents (user_id, username, display_name, version, consented_at, revoked_at) VALUES (?, ?, ?, ?, ?, NULL)
ON CONFLICT(user_id) DO UPDATE SET username = excluded.username, display_name = excluded.display_name,
version = excluded.version, consented_at = excluded.consented_at, revoked_at = NULL`,
)
.run(user.id, user.username, user.global_name ?? null, CONSENT_VERSION, now);
this.log(user.id, 'consent', now);
}
revoke(userId: string, now = Date.now()): void {
this.db.prepare('UPDATE consents SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').run(now, userId);
this.log(userId, 'revoke', now);
}
log(userId: string, action: string, now = Date.now(), detail: string | null = null): void {
this.db.prepare('INSERT INTO consent_log (user_id, action, version, at, detail) VALUES (?, ?, ?, ?, ?)').run(userId, action, CONSENT_VERSION, now, detail);
}
consentLog(userId: string): { action: string; version: string; at: number; detail: string | null }[] {
return this.db.prepare('SELECT action, version, at, detail FROM consent_log WHERE user_id = ? ORDER BY id').all(userId) as any;
}
// ---- 녹음 ----
addRecording(r: RecordingRow): void {
this.db
.prepare('INSERT INTO recordings (id, user_id, guild_id, channel_id, started_at, duration_ms, path) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(r.id, r.user_id, r.guild_id, r.channel_id, r.started_at, r.duration_ms, r.path);
}
recordings(userId: string): RecordingRow[] {
return this.db.prepare('SELECT * FROM recordings WHERE user_id = ? ORDER BY started_at').all(userId) as unknown as RecordingRow[];
}
recordingStats(userId: string): { count: number; total_ms: number } {
const r = this.db.prepare('SELECT COUNT(*) AS count, COALESCE(SUM(duration_ms), 0) AS total_ms FROM recordings WHERE user_id = ?').get(userId) as any;
return { count: Number(r.count), total_ms: Number(r.total_ms) };
}
/** 이 사람 녹음 파일과 기록을 모두 지운다. 지운 파일 수 */
deleteRecordings(userId: string, now = Date.now()): number {
const rows = this.recordings(userId);
for (const r of rows) fs.rmSync(r.path, { force: true });
this.db.prepare('DELETE FROM recordings WHERE user_id = ?').run(userId);
this.log(userId, 'delete_recordings', now, String(rows.length));
return rows.length;
}
// ---- 로그인 세션 (쿠키에는 무작위 값, DB 에는 해시만) ----
newState(now = Date.now()): string {
const state = crypto.randomBytes(24).toString('base64url');
this.db.prepare('DELETE FROM oauth_states WHERE expires_at < ?').run(now);
this.db.prepare('INSERT INTO oauth_states (state_hash, expires_at) VALUES (?, ?)').run(sha256(state), now + STATE_MS);
return state;
}
/** 한 번만 쓸 수 있다 */
takeState(state: string, now = Date.now()): boolean {
const r = this.db.prepare('DELETE FROM oauth_states WHERE state_hash = ? AND expires_at >= ?').run(sha256(state), now);
return Number(r.changes) === 1;
}
newSession(user: DiscordUser, now = Date.now()): string {
const sid = crypto.randomBytes(32).toString('base64url');
this.db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now);
this.db
.prepare('INSERT INTO sessions (id_hash, user_id, username, display_name, csrf, expires_at) VALUES (?, ?, ?, ?, ?, ?)')
.run(sha256(sid), user.id, user.username, user.global_name ?? null, crypto.randomBytes(24).toString('base64url'), now + SESSION_MS);
return sid;
}
session(sid: string, now = Date.now()): SessionRow | undefined {
const r = this.db.prepare('SELECT user_id, username, display_name, csrf, expires_at FROM sessions WHERE id_hash = ?').get(sha256(sid)) as SessionRow | undefined;
return r && r.expires_at >= now ? r : undefined;
}
endSession(sid: string): void {
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(sha256(sid));
}
close(): void {
this.db.close();
}
}

View File

@@ -0,0 +1,21 @@
/** 음성채널에 있는 사람 하나 */
export interface Presence {
userId: string;
channelId: string;
}
/**
* 봇이 이 서버에서 있어야 할 음성채널.
* - 동의한 사람이 지금 채널에 남아 있으면 그대로 (계속 옮겨 다니지 않음)
* - 아니면 방금 움직인 동의자의 채널, 그다음 동의자가 가장 많은 채널
* - 동의자가 아무도 없으면 null (나감)
*/
export function pickChannel(current: string | null, consented: Presence[], preferUserId?: string): string | null {
if (!consented.length) return null;
if (current && consented.some((p) => p.channelId === current)) return current;
const pref = preferUserId && consented.find((p) => p.userId === preferUserId);
if (pref) return pref.channelId;
const count = new Map<string, number>();
for (const p of consented) count.set(p.channelId, (count.get(p.channelId) ?? 0) + 1);
return [...count.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0][0];
}

View File

@@ -0,0 +1,32 @@
import path from 'node:path';
import { FollowBot } from './bot.js';
import { loadConfig, loadDotEnv } from './config.js';
import { Store } from './db.js';
import { createSite } from './site.js';
loadDotEnv(path.resolve('.env'));
const cfg = loadConfig();
const store = new Store(path.join(cfg.dataDir, 'consent.db'));
const bot = new FollowBot(cfg, store);
const site = createSite(cfg, store, {
consentChanged: (id) => bot.consentChanged(id),
discardActive: (id) => bot.discardActive(id),
recordingNow: (id) => bot.recordingNow(id),
userGuilds: (id) => bot.userGuilds(id),
});
site.listen(cfg.port, cfg.host, () => console.log(`[site] ${cfg.publicUrl} (http://${cfg.host}:${cfg.port})`));
await bot.start();
let stopping = false;
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
process.on(sig, async () => {
if (stopping) return;
stopping = true;
console.log('[main] 끄는 중 (녹음 중인 파일 저장)');
site.close();
await bot.stop().catch(() => undefined);
store.close();
process.exit(0);
});
}

130
consent-recorder/src/ogg.ts Normal file
View File

@@ -0,0 +1,130 @@
import fs from 'node:fs';
// 출처: game_voice_recorder app/src/core/discord/ogg.ts (같은 작성자)
// Ogg Opus 파일 쓰기 (RFC 7845). 디스코드에서 받은 Opus 패킷을 다시 인코딩하지 않고 그대로 담는다.
const CRC_TABLE = (() => {
const t = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let r = i << 24;
for (let j = 0; j < 8; j++) r = r & 0x80000000 ? (r << 1) ^ 0x04c11db7 : r << 1;
t[i] = r >>> 0;
}
return t;
})();
function crc32(buf: Buffer): number {
let crc = 0;
for (let i = 0; i < buf.length; i++) crc = ((crc << 8) ^ CRC_TABLE[((crc >>> 24) & 0xff) ^ buf[i]]) >>> 0;
return crc >>> 0;
}
/** Opus 패킷 TOC 로 48kHz 기준 샘플 수 계산 */
export function opusSamples(packet: Buffer): number {
if (!packet.length) return 0;
const toc = packet[0];
const config = toc >> 3;
let frame: number;
if (config < 12) frame = [480, 960, 1920, 2880][config & 3];
else if (config < 16) frame = [480, 960][config & 1];
else frame = [120, 240, 480, 960][config & 3];
const c = toc & 3;
const count = c === 0 ? 1 : c === 3 ? (packet[1] ?? 0) & 0x3f : 2;
return frame * count;
}
/** 20ms 무음 Opus 프레임 (디스코드가 말이 끝날 때 보내는 것과 같은 값) */
export const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);
export class OggOpusWriter {
private fd: number;
private serial = (Math.random() * 0xffffffff) >>> 0;
private seq = 0;
private granule = 0n;
private packets: Buffer[] = [];
private closed = false;
/** 담긴 오디오 길이 (48kHz 샘플) */
samples = 0;
bytes = 0;
constructor(
readonly path: string,
channels = 2,
) {
this.fd = fs.openSync(path, 'w');
const head = Buffer.alloc(19);
head.write('OpusHead', 0, 'ascii');
head[8] = 1;
head[9] = channels;
head.writeUInt16LE(0, 10); // pre-skip
head.writeUInt32LE(48000, 12);
head.writeInt16LE(0, 16);
head[18] = 0;
this.writePage([head], 0n, 0x02);
const vendor = Buffer.from('voice_copy', 'ascii');
const tags = Buffer.alloc(8 + 4 + vendor.length + 4);
tags.write('OpusTags', 0, 'ascii');
tags.writeUInt32LE(vendor.length, 8);
vendor.copy(tags, 12);
tags.writeUInt32LE(0, 12 + vendor.length);
this.writePage([tags], 0n, 0);
}
write(packet: Buffer): void {
if (this.closed) return;
this.packets.push(packet);
this.samples += opusSamples(packet);
if (this.packets.length >= 50) this.flush(false);
}
private flush(last: boolean): void {
if (!this.packets.length && !last) return;
this.granule = BigInt(this.samples);
this.writePage(this.packets, this.granule, last ? 0x04 : 0);
this.packets = [];
}
private writePage(packets: Buffer[], granule: bigint, flags: number): void {
const lacing: number[] = [];
for (const p of packets) {
let n = p.length;
while (n >= 255) {
lacing.push(255);
n -= 255;
}
lacing.push(n);
}
if (lacing.length > 255) {
// 한 페이지 최대 255 세그먼트. 넘으면 나눠 쓴다 (50패킷이면 생기지 않음)
const half = Math.ceil(packets.length / 2);
this.writePage(packets.slice(0, half), granule, flags & 0x02);
this.writePage(packets.slice(half), granule, flags & 0x04);
return;
}
const header = Buffer.alloc(27 + lacing.length);
header.write('OggS', 0, 'ascii');
header[4] = 0;
header[5] = flags;
header.writeBigInt64LE(granule, 6);
header.writeUInt32LE(this.serial, 14);
header.writeUInt32LE(this.seq++, 18);
header.writeUInt32LE(0, 22);
header[26] = lacing.length;
for (let i = 0; i < lacing.length; i++) header[27 + i] = lacing[i];
const page = Buffer.concat([header, ...packets]);
page.writeUInt32LE(crc32(page), 22);
fs.writeSync(this.fd, page);
this.bytes += page.length;
}
close(): void {
if (this.closed) return;
this.flush(true);
this.closed = true;
fs.closeSync(this.fd);
}
get durationMs(): number {
return Math.round(this.samples / 48);
}
}

View File

@@ -0,0 +1,136 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { EndBehaviorType, type VoiceConnection } from '@discordjs/voice';
import type { Store } from './db.js';
import { OggOpusWriter, SILENCE_FRAME } from './ogg.js';
const FRAME = 960; // 20ms @48kHz
const SILENCE_MS = 800; // 말이 0.8초 끊기면 한 파일 끝
const MAX_SEC = 30; // 한 파일 최대 30초
const MIN_MS = 500; // 0.5초보다 짧으면 버림 (키 소리 · 끊긴 패킷)
/** 수신기가 꺼낸 Opus 패킷 → RTP 순번 · 타임스탬프 (패킷 도착이 몰려도 말 사이에 무음이 끼지 않게) */
const rtpOf = new WeakMap<Buffer, { seq: number; ts: number }>();
function tapRtp(receiver: unknown): void {
const r = receiver as { parsePacket?: (buf: Buffer, ...rest: unknown[]) => Buffer | undefined; __rtp?: boolean };
if (r.__rtp || typeof r.parsePacket !== 'function') return;
const orig = r.parsePacket.bind(r);
r.parsePacket = (buf: Buffer, ...rest: unknown[]) => {
const packet = orig(buf, ...rest);
if (packet && buf.length >= 12) rtpOf.set(packet, { seq: buf.readUInt16BE(2), ts: buf.readUInt32BE(4) });
return packet;
};
r.__rtp = true;
}
class Utterance {
readonly writer: OggOpusWriter;
readonly id = `${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}`;
readonly startedAt = Date.now();
private rtpBase: number | null = null;
private lastSeq = 0;
constructor(dir: string) {
fs.mkdirSync(dir, { recursive: true });
this.writer = new OggOpusWriter(path.join(dir, `${this.id}.ogg`));
}
/** 말 사이 짧은 쉼(디스코드는 패킷을 안 보냄)을 RTP 타임스탬프로 무음 프레임으로 채운다 */
place(packet: Buffer): void {
const rtp = rtpOf.get(packet);
let fill = 0;
if (rtp && this.rtpBase !== null) {
const d = (rtp.seq - this.lastSeq) & 0xffff;
if (d === 0 || d > 0x8000) return; // 중복 · 늦게 온 패킷
const behind = ((rtp.ts - this.rtpBase) >>> 0) - this.writer.samples;
if (behind >= FRAME / 2 && behind <= SILENCE_MS * 48) fill = Math.round(behind / FRAME);
else if (behind > SILENCE_MS * 48 || behind < -48000) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0;
}
if (rtp) {
if (this.rtpBase === null) this.rtpBase = (rtp.ts - this.writer.samples) >>> 0;
this.lastSeq = rtp.seq;
}
for (let i = 0; i < fill; i++) this.writer.write(SILENCE_FRAME);
this.writer.write(packet);
}
}
/**
* 한 음성 연결에서 동의한 사람만 사람별로 따로 녹음한다.
* 동의하지 않은 사람의 음성 스트림은 구독하지 않으므로 받지도 저장하지도 않는다.
*/
export class Recorder {
private active = new Map<string, Utterance>();
private onSpeak = (userId: string) => this.subscribe(userId);
constructor(
private store: Store,
private dataDir: string,
private connection: VoiceConnection,
readonly guildId: string,
readonly channelId: string,
/** 지금 이 채널에 있고 동의한 사람인지 (말할 때마다 다시 확인) */
private allowed: (userId: string) => boolean,
) {
tapRtp(connection.receiver);
connection.receiver.speaking.on('start', this.onSpeak);
}
private subscribe(userId: string): void {
const recv = this.connection.receiver;
if (recv.subscriptions.has(userId) || !this.allowed(userId)) return;
const stream = recv.subscribe(userId, { end: { behavior: EndBehaviorType.AfterSilence, duration: SILENCE_MS } });
stream.on('data', (packet: Buffer) => {
if (!this.allowed(userId)) return this.stopUser(userId); // 녹음 도중 철회 · 채널 이동
let u = this.active.get(userId);
if (!u) {
u = new Utterance(path.join(this.dataDir, 'recordings', userId, new Date().toISOString().slice(0, 10)));
this.active.set(userId, u);
}
u.place(packet);
if (u.writer.samples >= MAX_SEC * 48000) this.finish(userId);
});
stream.once('end', () => this.finish(userId));
stream.once('close', () => this.finish(userId));
stream.on('error', (e) => console.warn(`[rec] 수신 오류 ${userId}`, e));
}
/** 이 사람 녹음을 바로 멈추고 쓰던 파일은 버린다 (철회 · 채널을 나감) */
stopUser(userId: string): void {
this.connection.receiver.subscriptions.get(userId)?.destroy();
const u = this.active.get(userId);
if (!u) return;
this.active.delete(userId);
u.writer.close();
fs.rmSync(u.writer.path, { force: true });
}
private finish(userId: string): void {
const u = this.active.get(userId);
if (!u) return;
this.active.delete(userId);
u.writer.close();
if (u.writer.durationMs < MIN_MS || !this.allowed(userId)) {
fs.rmSync(u.writer.path, { force: true });
return;
}
this.store.addRecording({
id: u.id,
user_id: userId,
guild_id: this.guildId,
channel_id: this.channelId,
started_at: u.startedAt,
duration_ms: u.writer.durationMs,
path: u.writer.path,
});
}
/** 지금 녹음 중인 파일을 모두 저장하고 연결 수신을 끊는다 */
close(): void {
this.connection.receiver.speaking.off('start', this.onSpeak);
for (const id of [...this.active.keys()]) this.finish(id);
for (const s of this.connection.receiver.subscriptions.values()) s.destroy();
}
}

View File

@@ -0,0 +1,292 @@
import crypto from 'node:crypto';
import http from 'node:http';
import type { Config } from './config.js';
import { CONSENT_CHECKS, CONSENT_VERSION, consentItems } from './consent-text.js';
import type { DiscordUser, SessionRow, Store } from './db.js';
export interface SiteHooks {
/** 동의 · 철회 직후. 봇이 바로 따라 들어가거나 녹음을 멈춘다 */
consentChanged(userId: string): void;
/** 이 사람의 진행 중인 녹음을 저장하지 않고 버린다 (파일 삭제 직전) */
discardActive(userId: string): void;
/** 이 사람이 지금 녹음되고 있는 채널 이름 (없으면 null) */
recordingNow(userId: string): string | null;
/** 봇과 이 사람이 함께 들어가 있는 서버 (녹음할 서버로 고를 수 있는 곳) */
userGuilds(userId: string): Promise<{ id: string; name: string }[]>;
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
const CSS = `
:root{color-scheme:light dark;--fg:#1d1d1f;--bg:#f5f5f7;--card:#fff;--muted:#6e6e73;--accent:#5865f2;--danger:#d93025;--ok:#188038}
@media (prefers-color-scheme:dark){:root{--fg:#f5f5f7;--bg:#111214;--card:#1e1f22;--muted:#a1a1a6}}
*{box-sizing:border-box}body{margin:0;font:16px/1.6 system-ui,-apple-system,"Apple SD Gothic Neo","Malgun Gothic",sans-serif;background:var(--bg);color:var(--fg)}
main{max-width:640px;margin:0 auto;padding:32px 20px}h1{font-size:24px;margin:0 0 8px}h2{font-size:18px;margin:24px 0 8px}
.card{background:var(--card);border-radius:14px;padding:20px 22px;margin:16px 0;box-shadow:0 1px 3px rgba(0,0,0,.08)}
.muted{color:var(--muted);font-size:14px}ul{padding-left:20px}li{margin:6px 0}
label.check{display:flex;gap:10px;align-items:flex-start;margin:10px 0}label.check input{margin-top:5px;width:18px;height:18px;flex-shrink:0}
button,.btn{display:inline-block;border:0;border-radius:10px;padding:11px 18px;font:inherit;font-weight:600;cursor:pointer;text-decoration:none;background:var(--accent);color:#fff}
button.danger{background:var(--danger)}button.ghost{background:transparent;color:var(--muted);padding:6px 0}
.status{font-weight:700}.status.on{color:var(--ok)}.status.off{color:var(--muted)}.rec{color:var(--danger);font-weight:700}
.err{background:#fde7e9;color:#8a1c1c;border-radius:10px;padding:10px 14px}
form.inline{display:inline}fieldset{border:0;padding:0;margin:12px 0}legend{font-weight:700;padding:0}
`;
function page(title: string, body: string): string {
return `<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(title)}</title><link rel="stylesheet" href="/style.css"></head><body><main>${body}</main></body></html>`;
}
function fmtTime(ts: number): string {
return new Date(ts).toLocaleString('ko-KR', { timeZone: 'Asia/Seoul' });
}
function fmtDur(ms: number): string {
const s = Math.round(ms / 1000);
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
return h ? `${h}시간 ${m}분` : m ? `${m}분 ${s % 60}초` : `${s}초`;
}
function cookies(req: http.IncomingMessage): Record<string, string> {
const out: Record<string, string> = {};
for (const part of (req.headers.cookie ?? '').split(';')) {
const i = part.indexOf('=');
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
}
return out;
}
async function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {
const chunks: Buffer[] = [];
let size = 0;
for await (const c of req) {
size += (c as Buffer).length;
if (size > 16 * 1024) throw new HttpError(413, '요청이 너무 큽니다');
chunks.push(c as Buffer);
}
return new URLSearchParams(Buffer.concat(chunks).toString('utf8'));
}
class HttpError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
}
}
export function createSite(cfg: Config, store: Store, hooks: SiteHooks): http.Server {
const secure = cfg.publicUrl.startsWith('https://');
const redirectUri = `${cfg.publicUrl}/callback`;
const cookieName = secure ? '__Host-sid' : 'sid';
const stateCookie = secure ? '__Host-oauth_state' : 'oauth_state';
const cookie = (name: string, value: string, maxAge: number) =>
`${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure ? '; Secure' : ''}`;
const setSid = (sid: string, maxAge: number) => cookie(cookieName, sid, maxAge);
const send = (res: http.ServerResponse, status: number, body: string, type = 'text/html; charset=utf-8', extra: Record<string, string | string[]> = {}) => {
res.writeHead(status, {
'Content-Type': type,
'Cache-Control': 'no-store',
// 다른 사이트가 이 페이지를 몰래 띄워 동의 버튼을 누르게 하지 못하게 (클릭재킹)
'Content-Security-Policy': "default-src 'none'; style-src 'self'; img-src 'self' https://cdn.discordapp.com; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
...extra,
});
res.end(body);
};
const redirect = (res: http.ServerResponse, to: string, extra: Record<string, string | string[]> = {}) => {
res.writeHead(303, { Location: to, 'Cache-Control': 'no-store', ...extra });
res.end();
};
function currentSession(req: http.IncomingMessage): { sid: string; s: SessionRow } | null {
const sid = cookies(req)[cookieName];
if (!sid) return null;
const s = store.session(sid);
return s ? { sid, s } : null;
}
/** 로그인 + CSRF 확인. 다른 사이트에서 보낸 form 으로 동의 · 철회되지 않게 */
async function authedForm(req: http.IncomingMessage): Promise<{ s: SessionRow; form: URLSearchParams; sid: string }> {
const cur = currentSession(req);
if (!cur) throw new HttpError(401, '로그인이 필요합니다');
const origin = req.headers.origin;
if (origin && origin !== new URL(cfg.publicUrl).origin) throw new HttpError(403, '잘못된 요청입니다');
const form = await readForm(req);
if (form.get('csrf') !== cur.s.csrf) throw new HttpError(403, '페이지가 오래되었습니다. 새로고침한 뒤 다시 해 주세요');
return { ...cur, form };
}
function landing(error?: string): string {
return page(
'목소리 녹음 동의',
`<h1>목소리 녹음 동의</h1>
<p class="muted">AI 음성 모델을 만들기 위해 디스코드 음성채널에서 <b>본인이 직접 동의한 사람</b>의 목소리만 녹음합니다.</p>
${error ? `<p class="err">${esc(error)}</p>` : ''}
<div class="card"><h2>어떻게 쓰이나요</h2><ul>${consentItems(esc(cfg.operatorName)).map((t) => `<li>${t}</li>`).join('')}</ul></div>
<p><a class="btn" href="/login">디스코드로 로그인</a></p>
<p class="muted">로그인은 내 디스코드 아이디와 이름만 확인합니다 (identify 권한). 동의는 로그인한 뒤 따로 누릅니다.</p>`,
);
}
/** 녹음할 서버 체크박스 (봇과 함께 있는 서버만) */
function guildChecks(guilds: { id: string; name: string }[], picked: Set<string>): string {
if (!guilds.length) return '<p class="err">봇이 들어가 있는 디스코드 서버에 함께 들어가 있지 않습니다. 서버에 들어간 뒤 새로고침해 주세요.</p>';
return `<fieldset><legend>녹음할 서버</legend><p class="muted">고른 서버의 음성채널에서만 봇이 따라 들어와 녹음합니다.</p>
${guilds.map((g) => `<label class="check"><input type="checkbox" name="guild" value="${esc(g.id)}"${picked.has(g.id) ? ' checked' : ''}><span>${esc(g.name)}</span></label>`).join('')}</fieldset>`;
}
/** form 에서 고른 서버. 봇과 함께 있지 않은 서버를 보내면 거절 */
async function pickedGuilds(s: SessionRow, form: URLSearchParams): Promise<string[]> {
const mine = new Set((await hooks.userGuilds(s.user_id)).map((g) => g.id));
const picked = [...new Set(form.getAll('guild'))];
if (picked.some((g) => !mine.has(g))) throw new HttpError(400, '고를 수 없는 서버입니다. 새로고침한 뒤 다시 해 주세요');
return picked;
}
async function home(s: SessionRow, error?: string): Promise<string> {
const guilds = await hooks.userGuilds(s.user_id);
const picked = new Set(store.consentGuilds(s.user_id));
const pickedNames = guilds.filter((g) => picked.has(g.id)).map((g) => esc(g.name));
const c = store.getConsent(s.user_id);
const on = store.isConsented(s.user_id);
const stats = store.recordingStats(s.user_id);
const live = on ? hooks.recordingNow(s.user_id) : null;
const name = esc(s.display_name || s.username);
const csrf = `<input type="hidden" name="csrf" value="${esc(s.csrf)}">`;
const stale = c && c.revoked_at === null && c.version !== CONSENT_VERSION;
const status = on
? `<p class="status on">● 녹음 동의함</p><p class="muted">${fmtTime(c!.consented_at)}에 동의 (문구 버전 ${esc(c!.version)})</p>
${live ? `<p class="rec">🔴 지금 “${esc(live)}” 채널에서 내 목소리를 녹음하고 있습니다</p>` : '<p class="muted">지금은 녹음하고 있지 않습니다. 고른 서버의 음성채널에 들어가면 봇이 따라 들어옵니다.</p>'}
<p>녹음할 서버: <b>${pickedNames.length ? pickedNames.join(', ') : '없음 (어디서도 녹음하지 않음)'}</b></p>`
: `<p class="status off">○ 녹음하지 않음</p>${
stale ? '<p class="muted">동의 문구가 바뀌어서 다시 동의해야 녹음합니다.</p>' : c?.revoked_at ? `<p class="muted">${fmtTime(c.revoked_at)}에 동의를 철회했습니다.</p>` : ''
}`;
const consentForm = on
? `<div class="card"><h2>녹음할 서버 바꾸기</h2><form method="post" action="/guilds">${csrf}
${guildChecks(guilds, picked)}${guilds.length ? '<button type="submit">저장</button>' : ''}</form></div>
<div class="card"><h2>동의 철회</h2><p>철회하면 바로 녹음을 멈추고 봇이 나를 따라오지 않습니다.</p>
<form method="post" action="/revoke">${csrf}
<label class="check"><input type="checkbox" name="delete" value="1" checked><span>지금까지 녹음된 내 목소리 파일도 모두 삭제</span></label>
<button class="danger" type="submit">동의 철회</button></form></div>`
: `<div class="card"><h2>녹음 동의</h2><ul>${consentItems(esc(cfg.operatorName)).map((t) => `<li>${t}</li>`).join('')}</ul>
<form method="post" action="/consent">${csrf}<input type="hidden" name="version" value="${esc(CONSENT_VERSION)}">
${guildChecks(guilds, picked)}
${Object.entries(CONSENT_CHECKS).map(([k, t]) => `<label class="check"><input type="checkbox" name="${k}" value="1" required><span>${esc(t)}</span></label>`).join('')}
${guilds.length ? '<button type="submit">위 내용에 동의하고 녹음 시작</button>' : ''}</form></div>`;
return page(
'목소리 녹음 동의',
`<h1>${name}님</h1><p class="muted">디스코드 아이디 ${esc(s.user_id)}</p>
${error ? `<p class="err">${esc(error)}</p>` : ''}
<div class="card">${status}<p>녹음된 내 목소리: <b>${stats.count}개 · ${fmtDur(stats.total_ms)}</b></p>
${stats.count ? `<form method="post" action="/delete" class="inline">${csrf}<button class="danger" type="submit">녹음 파일 모두 삭제</button></form>` : ''}</div>
${consentForm}
<form method="post" action="/logout">${csrf}<button class="ghost" type="submit">로그아웃</button></form>`,
);
}
async function oauthUser(code: string): Promise<DiscordUser> {
const tok = await fetch(`${cfg.discordApi}/oauth2/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: redirectUri, client_id: cfg.clientId, client_secret: cfg.clientSecret }),
});
if (!tok.ok) throw new HttpError(400, `디스코드 로그인 실패 (토큰 ${tok.status})`);
const { access_token } = (await tok.json()) as { access_token?: string };
if (!access_token) throw new HttpError(400, '디스코드 로그인 실패 (토큰 없음)');
const me = await fetch(`${cfg.discordApi}/users/@me`, { headers: { Authorization: `Bearer ${access_token}` } });
if (!me.ok) throw new HttpError(400, `디스코드 로그인 실패 (사용자 ${me.status})`);
const u = (await me.json()) as DiscordUser;
if (!u?.id || !/^\d{5,25}$/.test(u.id)) throw new HttpError(400, '디스코드 사용자 정보가 올바르지 않습니다');
// 액세스 토큰은 아이디 확인에만 쓰고 저장하지 않는다
return { id: u.id, username: String(u.username ?? ''), global_name: u.global_name ?? null };
}
async function handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
const url = new URL(req.url ?? '/', 'http://x');
const route = `${req.method} ${url.pathname}`;
switch (route) {
case 'GET /style.css':
return send(res, 200, CSS, 'text/css; charset=utf-8', { 'Cache-Control': 'public, max-age=3600' });
case 'GET /health':
return send(res, 200, JSON.stringify({ ok: true }), 'application/json');
case 'GET /': {
const cur = currentSession(req);
return send(res, 200, cur ? await home(cur.s) : landing());
}
case 'GET /login': {
// state 를 이 브라우저 쿠키에도 넣어 둔다: 남이 받은 callback 주소를 열어도 그 사람 계정으로 로그인되지 않게
const state = store.newState();
const q = new URLSearchParams({ client_id: cfg.clientId, response_type: 'code', redirect_uri: redirectUri, scope: 'identify', state });
return redirect(res, `${cfg.discordAuthorizeUrl}?${q}`, { 'Set-Cookie': cookie(stateCookie, state, 600) });
}
case 'GET /callback': {
const state = url.searchParams.get('state') ?? '';
const code = url.searchParams.get('code') ?? '';
const clear = { 'Set-Cookie': cookie(stateCookie, '', 0) };
if (url.searchParams.get('error')) return send(res, 400, landing('디스코드 로그인을 취소했습니다.'), undefined, clear);
const mine = cookies(req)[stateCookie] ?? '';
const sameBrowser = mine.length === state.length && state.length > 0 && crypto.timingSafeEqual(Buffer.from(mine), Buffer.from(state));
if (!sameBrowser || !store.takeState(state)) return send(res, 400, landing('로그인 요청이 만료되었습니다. 다시 로그인해 주세요.'), undefined, clear);
if (!code) return send(res, 400, landing('디스코드 로그인 실패 (code 없음)'));
const user = await oauthUser(code);
const sid = store.newSession(user);
return redirect(res, '/', { 'Set-Cookie': [setSid(sid, 7 * 24 * 3600), cookie(stateCookie, '', 0)] });
}
case 'POST /consent': {
const { s, form } = await authedForm(req);
const missing = Object.keys(CONSENT_CHECKS).filter((k) => form.get(k) !== '1');
if (missing.length) return send(res, 400, await home(s, '모든 항목에 직접 체크해야 동의할 수 있습니다.'));
// 예전 문구를 띄워 둔 화면에서 낸 동의는 받지 않는다
if (form.get('version') !== CONSENT_VERSION) return send(res, 409, await home(s, '동의 문구가 바뀌었습니다. 바뀐 내용을 읽고 다시 동의해 주세요.'));
const guilds = await pickedGuilds(s, form);
if (!guilds.length) return send(res, 400, await home(s, '녹음할 서버를 하나 이상 골라 주세요.'));
store.setConsentGuilds(s.user_id, guilds);
store.consent({ id: s.user_id, username: s.username, global_name: s.display_name });
hooks.consentChanged(s.user_id);
return redirect(res, '/');
}
case 'POST /guilds': {
const { s, form } = await authedForm(req);
if (!store.isConsented(s.user_id)) return send(res, 400, await home(s, '먼저 녹음에 동의해 주세요.'));
store.setConsentGuilds(s.user_id, await pickedGuilds(s, form));
hooks.consentChanged(s.user_id); // 빠진 서버에서는 바로 녹음을 멈추고, 더한 서버에는 따라 들어간다
return redirect(res, '/');
}
case 'POST /revoke': {
const { s, form } = await authedForm(req);
store.revoke(s.user_id);
hooks.consentChanged(s.user_id); // 봇이 먼저 녹음을 멈춘 뒤 파일을 지운다
if (form.get('delete') === '1') store.deleteRecordings(s.user_id);
return redirect(res, '/');
}
case 'POST /delete': {
const { s } = await authedForm(req);
hooks.discardActive(s.user_id); // 지금 녹음 중인 파일도 저장하지 않고 버린 뒤 지운다
store.deleteRecordings(s.user_id);
return redirect(res, '/');
}
case 'POST /logout': {
const { sid } = await authedForm(req);
store.endSession(sid);
return redirect(res, '/', { 'Set-Cookie': setSid('', 0) });
}
default:
return send(res, 404, page('없는 페이지', '<h1>없는 페이지입니다</h1><p><a href="/">처음으로</a></p>'));
}
}
return http.createServer((req, res) => {
handle(req, res).catch((e) => {
const status = e instanceof HttpError ? e.status : 500;
if (!(e instanceof HttpError)) console.error('[site] 오류', e);
if (!res.headersSent) send(res, status, landing(e instanceof HttpError ? e.message : '서버 오류가 났습니다. 잠시 뒤 다시 해 주세요.'));
else res.end();
});
});
}

View File

@@ -0,0 +1,57 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { ChannelType } from 'discord.js';
import { FollowBot } from '../src/bot.ts';
import { loadConfig } from '../src/config.ts';
import { Store } from '../src/db.ts';
/** 정원이 찬 채널 A(봇이 들어가 있음, joinable=false)와 같은 상태의 채널 B */
function fakeGuild() {
const guild: any = { id: 'g', members: { me: {} }, voiceStates: { cache: new Map() } };
const channel = (id: string) => ({ id, guild, type: ChannelType.GuildVoice, joinable: false, permissionsFor: () => ({ has: () => true }) });
const A = channel('A');
const B = channel('B');
guild.voiceStates.cache.set('u1', { id: 'u1', channelId: 'A', channel: A, member: { user: { bot: false } } });
guild.voiceStates.cache.set('u2', { id: 'u2', channelId: 'B', channel: B, member: { user: { bot: false } } });
return guild;
}
test('봇이 들어가 정원이 찬 지금 채널의 동의자는 그대로 따라간다 (나갔다 들어오기 반복 X)', async () => {
const store = new Store(':memory:');
store.consent({ id: 'u1', username: 'a' });
store.consent({ id: 'u2', username: 'b' });
store.setConsentGuilds('u1', ['g']);
store.setConsentGuilds('u2', ['g']);
const cfg = loadConfig({ PUBLIC_URL: 'http://localhost', DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' }, false);
const bot = new FollowBot(cfg, store);
const guild = fakeGuild();
assert.deepEqual(bot.consentedPresence(guild), []); // 들어가 있지 않으면 꽉 찬 채널은 못 들어감
(bot as any).recorders.set('g', { channelId: 'A' });
assert.deepEqual(bot.consentedPresence(guild), [{ userId: 'u1', channelId: 'A' }]); // 지금 채널 A 는 유지, 꽉 찬 B 는 제외
(bot as any).recorders.clear();
await bot.client.destroy();
store.close();
});
test('녹음할 서버로 고르지 않은 서버에서는 동의자라도 따라가지 않는다', async () => {
const store = new Store(':memory:');
store.consent({ id: 'u1', username: 'a' });
store.consent({ id: 'u2', username: 'b' });
store.setConsentGuilds('u1', ['g']);
store.setConsentGuilds('u2', ['other']);
const cfg = loadConfig({ PUBLIC_URL: 'http://localhost', DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' }, false);
const bot = new FollowBot(cfg, store);
const guild = fakeGuild();
(bot as any).recorders.set('g', { channelId: 'A' });
assert.deepEqual(bot.consentedPresence(guild), [{ userId: 'u1', channelId: 'A' }]);
// 서버를 빼면 진행 중인 녹음도 멈춘다
const stopped: string[] = [];
(bot as any).recorders.set('g', { channelId: 'A', stopUser: (id: string) => stopped.push(id) });
store.setConsentGuilds('u1', []);
bot.consentChanged('u1');
assert.deepEqual(stopped, ['u1']);
assert.deepEqual(bot.consentedPresence(guild), []);
(bot as any).recorders.clear();
await bot.client.destroy();
store.close();
});

View File

@@ -0,0 +1,202 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { after, before, test } from 'node:test';
import { loadConfig } from '../src/config.ts';
import { CONSENT_VERSION } from '../src/consent-text.ts';
import { Store } from '../src/db.ts';
import { pickChannel } from '../src/follow.ts';
import { createSite } from '../src/site.ts';
const USER = { id: '123456789012345678', username: 'haneul', global_name: '하늘' };
let discord: http.Server;
let site: http.Server;
let store: Store;
let base = '';
let tmp = '';
const changed: string[] = [];
const events: string[] = [];
before(async () => {
tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-consent-'));
// 가짜 디스코드 OAuth API
discord = http.createServer((req, res) => {
let body = '';
req.on('data', (c) => (body += c));
req.on('end', () => {
if (req.url === '/oauth2/token' && req.method === 'POST') {
const f = new URLSearchParams(body);
if (f.get('code') !== 'good-code' || f.get('client_secret') !== 'sec') return res.writeHead(400).end('{}');
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ access_token: 'at' }));
}
if (req.url === '/users/@me' && req.headers.authorization === 'Bearer at') {
return res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(USER));
}
res.writeHead(404).end();
});
});
await new Promise<void>((r) => discord.listen(0, '127.0.0.1', r));
const dport = (discord.address() as any).port;
store = new Store(path.join(tmp, 'consent.db'));
site = http.createServer();
await new Promise<void>((r) => site.listen(0, '127.0.0.1', r));
const port = (site.address() as any).port;
site.close();
base = `http://127.0.0.1:${port}`;
const cfg = loadConfig(
{ PUBLIC_URL: base, DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec', DATA_DIR: tmp, OPERATOR_NAME: '승한', DISCORD_API: `http://127.0.0.1:${dport}` },
false,
);
site = createSite(cfg, store, {
consentChanged: (id) => changed.push(id),
discardActive: (id) => events.push(`discard:${id}:${store.recordingStats(id).count}`),
recordingNow: () => null,
userGuilds: async () => [
{ id: 'g1', name: '첫째 서버' },
{ id: 'g2', name: '둘째 서버' },
],
});
await new Promise<void>((r) => site.listen(port, '127.0.0.1', r));
});
after(() => {
site.close();
discord.close();
store.close();
fs.rmSync(tmp, { recursive: true, force: true });
});
const get = (p: string, cookie = '') => fetch(base + p, { redirect: 'manual', headers: cookie ? { cookie } : {} });
const post = (p: string, cookie: string, form: Record<string, string> | string[][]) =>
fetch(base + p, { method: 'POST', redirect: 'manual', headers: { cookie, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(form) });
async function login(): Promise<{ cookie: string; csrf: string }> {
const l = await get('/login');
assert.equal(l.status, 303);
const auth = new URL(l.headers.get('location')!);
assert.equal(auth.origin + auth.pathname, 'https://discord.com/oauth2/authorize');
assert.equal(auth.searchParams.get('scope'), 'identify');
assert.equal(auth.searchParams.get('redirect_uri'), `${base}/callback`);
const state = auth.searchParams.get('state')!;
const stateCookie = l.headers.get('set-cookie')!.split(';')[0];
assert.equal(stateCookie, `oauth_state=${state}`);
// 로그인을 시작하지 않은 브라우저(state 쿠키 없음 · 다른 값)에서 연 callback 은 거절 (state 는 그대로 남음)
assert.equal((await get(`/callback?code=good-code&state=${state}`)).status, 400);
assert.equal((await get(`/callback?code=good-code&state=${state}`, 'oauth_state=other')).status, 400);
const cb = await get(`/callback?code=good-code&state=${state}`, stateCookie);
assert.equal(cb.status, 303);
const cookie = cb.headers.get('set-cookie')!.split(';')[0];
assert.match(cookie, /^sid=/);
// state 는 한 번만 쓸 수 있다
assert.equal((await get(`/callback?code=good-code&state=${state}`, stateCookie)).status, 400);
const home = await (await get('/', cookie)).text();
assert.match(home, /하늘님/);
const csrf = /name="csrf" value="([^"]+)"/.exec(home)![1];
return { cookie, csrf };
}
test('디스코드 로그인 → 모든 항목 체크해야 동의 → 철회하면 녹음 파일 삭제', async () => {
assert.equal((await get('/callback?code=good-code&state=forged')).status, 400);
const { cookie, csrf } = await login();
assert.equal(store.isConsented(USER.id), false);
// CSRF 없거나 틀리면 거절
assert.equal((await post('/consent', cookie, { self: '1', model: '1', age: '1' })).status, 403);
assert.equal((await post('/consent', cookie, { csrf: 'x', self: '1', model: '1', age: '1' })).status, 403);
// 다른 사이트에서 보낸 요청 거절
const cross = await fetch(base + '/consent', {
method: 'POST', redirect: 'manual',
headers: { cookie, origin: 'https://evil.example', 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ csrf, self: '1', model: '1', age: '1' }),
});
assert.equal(cross.status, 403);
// 항목 하나라도 빠지면 거절
assert.equal((await post('/consent', cookie, { csrf, self: '1', model: '1' })).status, 400);
assert.equal(store.isConsented(USER.id), false);
// 예전 문구 화면에서 낸 동의(버전 없음 · 다른 버전)는 거절
assert.equal((await post('/consent', cookie, { csrf, self: '1', model: '1', age: '1' })).status, 409);
assert.equal((await post('/consent', cookie, { csrf, version: 'old', self: '1', model: '1', age: '1' })).status, 409);
assert.equal(store.isConsented(USER.id), false);
const page0 = await (await get('/', cookie)).text();
const version = /name="version" value="([^"]+)"/.exec(page0)![1];
assert.equal(version, CONSENT_VERSION);
// 봇과 함께 있는 서버만 고를 수 있고, 하나 이상 골라야 동의된다
assert.match(page0, /name="guild" value="g1"[^>]*><span>첫째 서버/);
const ok = { csrf, version, self: '1', model: '1', age: '1' };
assert.equal((await post('/consent', cookie, ok)).status, 400);
assert.equal((await post('/consent', cookie, { ...ok, guild: 'other' })).status, 400);
assert.equal(store.isConsented(USER.id), false);
assert.equal((await post('/consent', cookie, [...Object.entries(ok), ['guild', 'g1'], ['guild', 'g2']])).status, 303);
assert.equal(store.isConsented(USER.id), true);
assert.deepEqual(store.consentGuilds(USER.id), ['g1', 'g2']);
assert.deepEqual(changed, [USER.id]);
assert.match(await (await get('/', cookie)).text(), /녹음 동의함[\s\S]*녹음할 서버: <b>첫째 서버, 둘째 서버/);
// 녹음할 서버 바꾸기: 뺀 서버는 녹음하지 않는다. 다 빼면 어디서도 녹음하지 않음
assert.equal((await post('/guilds', cookie, { csrf, guild: 'other' })).status, 400);
assert.equal((await post('/guilds', cookie, { csrf, guild: 'g2' })).status, 303);
assert.deepEqual(changed, [USER.id, USER.id]);
assert.equal(store.isConsentedIn(USER.id, 'g1'), false);
assert.equal(store.isConsentedIn(USER.id, 'g2'), true);
assert.equal((await post('/guilds', cookie, { csrf })).status, 303);
assert.equal(store.isConsentedIn(USER.id, 'g2'), false);
assert.match(await (await get('/', cookie)).text(), /녹음할 서버: <b>없음/);
assert.equal((await post('/guilds', cookie, { csrf, guild: 'g1' })).status, 303);
// 녹음 파일 하나 있다고 치고 철회 + 삭제
const f = path.join(tmp, 'recordings', USER.id, 'a.ogg');
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, 'x');
store.addRecording({ id: 'a', user_id: USER.id, guild_id: 'g', channel_id: 'c', started_at: 1, duration_ms: 1500, path: f });
assert.match(await (await get('/', cookie)).text(), /1개 · 2초/);
// 파일 삭제: 진행 중인 녹음을 먼저 버린 뒤(그때는 아직 1개) 저장 파일을 지운다
assert.equal((await post('/delete', cookie, { csrf })).status, 303);
assert.deepEqual(events, [`discard:${USER.id}:1`]);
assert.equal(fs.existsSync(f), false);
fs.writeFileSync(f, 'x');
store.addRecording({ id: 'b', user_id: USER.id, guild_id: 'g', channel_id: 'c', started_at: 1, duration_ms: 1500, path: f });
assert.equal((await post('/revoke', cookie, { csrf, delete: '1' })).status, 303);
assert.equal(store.isConsented(USER.id), false);
assert.equal(fs.existsSync(f), false);
assert.equal(store.recordingStats(USER.id).count, 0);
assert.deepEqual(store.consentLog(USER.id).map((l) => l.action), ['guilds', 'consent', 'guilds', 'guilds', 'guilds', 'delete_recordings', 'revoke', 'delete_recordings']);
// 철회한 뒤에는 서버를 바꿀 수 없다
assert.equal((await post('/guilds', cookie, { csrf, guild: 'g1' })).status, 400);
// 로그아웃하면 세션 끝
assert.equal((await post('/logout', cookie, { csrf })).status, 303);
assert.doesNotMatch(await (await get('/', cookie)).text(), /하늘님/);
});
test('클릭재킹 막기 헤더', async () => {
const r = await get('/');
assert.equal(r.headers.get('x-frame-options'), 'DENY');
assert.match(r.headers.get('content-security-policy')!, /frame-ancestors 'none'/);
});
test('문구 버전이 바뀌면 예전 동의는 녹음하지 않는다', () => {
const s = new Store(':memory:');
s.consent({ id: '1', username: 'a' });
assert.equal(s.isConsented('1'), true);
s.db.prepare("UPDATE consents SET version = 'old'").run();
assert.equal(s.isConsented('1'), false);
assert.deepEqual(s.consentedUserIds(), []);
s.close();
});
test('따라갈 채널 고르기', () => {
assert.equal(pickChannel(null, []), null);
assert.equal(pickChannel('A', []), null);
const ps = [
{ userId: 'u1', channelId: 'A' },
{ userId: 'u2', channelId: 'B' },
{ userId: 'u3', channelId: 'B' },
];
assert.equal(pickChannel('A', ps, 'u2'), 'A'); // 지금 채널에 동의자가 남아 있으면 그대로
assert.equal(pickChannel(null, ps, 'u1'), 'A'); // 방금 움직인 사람
assert.equal(pickChannel(null, ps), 'B'); // 동의자 많은 채널
assert.equal(pickChannel('C', ps), 'B');
});

View File

@@ -0,0 +1,89 @@
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
import { test } from 'node:test';
import { Store } from '../src/db.ts';
import { Recorder } from '../src/recorder.ts';
/** @discordjs/voice 수신기 흉내: speaking 'start' 이벤트 + 사람별 스트림 */
function fakeConnection() {
const subscriptions = new Map<string, PassThrough>();
const receiver = {
speaking: new EventEmitter(),
subscriptions,
subscribe(userId: string) {
const s = new PassThrough({ objectMode: true });
s.on('close', () => subscriptions.delete(userId));
subscriptions.set(userId, s);
return s;
},
};
return { receiver } as any;
}
const OPUS_20MS = Buffer.from([0x78, 0x01, 0x02, 0x03]); // TOC config 15 = 20ms 프레임 1개 (960 샘플)
test('동의한 사람만 구독해서 저장하고, 철회하면 쓰던 파일을 버린다', async () => {
const tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-rec-'));
const store = new Store(':memory:');
store.consent({ id: 'yes', username: 'y' });
const conn = fakeConnection();
const rec = new Recorder(store, tmp, conn, 'g', 'c', (uid) => store.isConsented(uid));
conn.receiver.speaking.emit('start', 'no'); // 동의 안 한 사람
assert.equal(conn.receiver.subscriptions.has('no'), false);
conn.receiver.speaking.emit('start', 'yes');
const s = conn.receiver.subscriptions.get('yes')!;
for (let i = 0; i < 50; i++) s.write(OPUS_20MS); // 1초
await new Promise((r) => setImmediate(r));
s.end();
await new Promise((r) => setImmediate(r));
const rows = store.recordings('yes');
assert.equal(rows.length, 1);
assert.equal(rows[0].duration_ms, 1000);
assert.equal(fs.readFileSync(rows[0].path).subarray(0, 4).toString(), 'OggS');
// 말하는 도중 철회 → 저장 안 함
conn.receiver.speaking.emit('start', 'yes');
const s2 = conn.receiver.subscriptions.get('yes')!;
for (let i = 0; i < 50; i++) s2.write(OPUS_20MS);
await new Promise((r) => setImmediate(r));
store.revoke('yes');
s2.write(OPUS_20MS);
await new Promise((r) => setImmediate(r));
assert.equal(store.recordings('yes').length, 1);
assert.equal(fs.readdirSync(path.dirname(rows[0].path)).length, 1);
rec.close();
store.close();
fs.rmSync(tmp, { recursive: true, force: true });
});
test('파일 삭제 직전 진행 중인 녹음을 버리면 삭제 뒤에 남지 않는다', async () => {
const tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-rec-'));
const store = new Store(':memory:');
store.consent({ id: 'yes', username: 'y' });
const conn = fakeConnection();
const rec = new Recorder(store, tmp, conn, 'g', 'c', (uid) => store.isConsented(uid));
conn.receiver.speaking.emit('start', 'yes');
const s = conn.receiver.subscriptions.get('yes')!;
for (let i = 0; i < 30; i++) s.write(OPUS_20MS); // 600ms, 아직 진행 중
await new Promise((r) => setImmediate(r));
rec.stopUser('yes'); // 사이트 /delete → discardActive
store.deleteRecordings('yes');
s.end();
await new Promise((r) => setImmediate(r));
assert.equal(store.recordings('yes').length, 0);
const left = fs.readdirSync(tmp, { recursive: true }).filter((f) => String(f).endsWith('.ogg'));
assert.deepEqual(left, []);
// 동의는 그대로라 다시 말하면 새로 녹음한다
conn.receiver.speaking.emit('start', 'yes');
assert.equal(conn.receiver.subscriptions.has('yes'), true);
rec.close();
store.close();
fs.rmSync(tmp, { recursive: true, force: true });
});

View File

@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src",
"types": ["node"],
"lib": ["ES2023"]
},
"include": ["src/**/*.ts"]
}

2
voice-changer/.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
*.bat text eol=crlf
*.ps1 text eol=crlf

10
voice-changer/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
engine/
env/
tools/
training/
datasets/
config/
dist/
models/*
!models/.gitkeep
__pycache__/

126
voice-changer/README.md Normal file
View File

@@ -0,0 +1,126 @@
# 실시간 음성 변환기 (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 정도 여유를 두세요
## 설치 — `VoiceChangerSetup.exe` 하나만
1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다).
2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다.
비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 상위 폴더가 일반 사용자 소유인 곳(예: 바탕 화면 · 문서 아래)도 거절합니다.
Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다.
설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요.
3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) ·
torch(CUDA 12.8) · 엔진 기본 모델(rmvpe · contentvec · 사전학습 가중치 · ffmpeg)을 그 폴더로 내려받습니다. 10~20분 걸립니다.
마지막에 `GPU 확인: NVIDIA GeForce RTX 5070 Ti (sm_120)` 가 나오면 정상입니다.
4. 시작 메뉴의 **음성 변환기**로 실행합니다.
가상 오디오 장치(VB-CABLE 등)는 필요 없습니다. 변환기가 내 마이크에서 나가는 소리를 직접 바꿔 주므로,
디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다.
- 내려받다가 끊기면 설치 폴더의 `install.bat` 을 실행합니다. 받은 곳부터 이어서 받습니다.
- 권한: 설치 프로그램이 설치 폴더의 소유자를 Administrators 로 바꾸고 잠근 뒤 확인합니다(`installer\secure-dir.ps1`, 실패하면 설치 중단). 설치 폴더와 실행 파일 · `app\` · `scripts\` · `apo\` · `uninstall\` 은 관리자만 고칠 수 있습니다. 일반 사용자는 `models` · `training` · `datasets` · `config` · `cache` · `env` · `engine` · `tools` 에만 씁니다. 엔진 내려받기(`install.ps1`)는 관리자 권한 없이 돕니다.
- 폴더 밖에 남는 것은 윈도우가 관리하는 항목뿐입니다: 시작 메뉴 바로 가기, 프로그램 제거 목록, 마이크 모듈 등록(레지스트리).
사용자 폴더(`%APPDATA%` · `%LOCALAPPDATA%` · `%TEMP%` · `.cache`)에는 아무것도 쓰지 않습니다.
- 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고, 만든 모델 · 녹음 · 설정까지 지울지 묻습니다.
### 마이크 모듈은 어떻게 동작하나
윈도우는 마이크 소리를 앱에 넘기기 전에 오디오 처리 모듈(APO, Equalizer APO 와 같은 방식)을 거칩니다.
설치 프로그램이 `apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 `apo\mic-apo-backup.json`, 이전 버전의 `config\mic-apo-backup.json` 은 값을 검증한 뒤 옮김).
통화 앱(디스코드 등)이 여는 통화(Communications) 모드 스트림에도 붙도록 기본 · 통화 · 음성 · 미디어 모드로 등록합니다. 드라이버가 이미 모드 목록을 갖고 있으면 그 목록을 그대로 둡니다.
- 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다
- 변환을 켜면 고른 마이크의 소리를 변환기로 넘기고, 바뀐 목소리를 대신 내보냅니다. 바뀐 소리가 아직 없을 때는 무음이라 원래 목소리가 새지 않습니다
- 변환기가 꺼지거나 멈추면 1.5초 안에 원래 목소리로 돌아갑니다
- 그 마이크를 쓰는 모든 앱(디스코드 · 게임 · 녹음기)에 바뀐 목소리가 갑니다
- 윈도우 소리 설정에서 마이크의 **오디오 향상**을 끄면 모듈이 빠집니다. 설치할 때 켜 두지만, 직접 끄면 변환이 안 됩니다
- 새로 꽂은 마이크나 드라이버를 업데이트한 마이크는 변환기 화면의 **마이크 다시 연결**을 누릅니다
## 변환하기 — 음성 변환기
1. 목소리 모델을 고릅니다. 직접 학습한 모델이 위에, 예시 모델이 아래에 나옵니다.
2. **내 목소리 성별**을 고르면 성별이 다른 모델은 음높이를 ±12반음(한 옥타브)으로 자동으로 맞춥니다. 슬라이더로 더 맞출 수 있고, 켜 둔 채로 바꿔도 바로 적용됩니다.
3. **마이크**에서 내 마이크를 고릅니다. 디스코드 입력 장치도 같은 마이크로 둡니다.
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\ 화면 · 학습 · 모델 목록 · 마이크 모듈 연결(mic_bridge.py) 코드
apo\ 마이크 모듈 VoiceChangerAPO.dll 과 소스 (vcapo.cpp, 주고받는 규약 vccore.h)
scripts\mic-apo.ps1 마이크 모듈 붙이기 · 떼기 (관리자)
models\<아이디>\ model.pth · model.index · info.json(이름 · 성별 · 출처 · 라이선스)
config\ 설정 · 마이크 모듈 백업
cache\ 임시 파일 · torch · huggingface · matplotlib 등 라이브러리 캐시 (지워도 됨)
engine\ env\ tools\ 설치하면 생기는 폴더 (엔진 · Python · uv)
uninstall\ 제거 프로그램
```
## 배포 파일 만들기
```bash
voice-changer/scripts/build-release.sh # 리눅스 mingw: VoiceChanger.exe · VoiceChangerAPO.dll 빌드 → dist/payload, dist/voice-changer-win.zip
```
```powershell
powershell -ExecutionPolicy Bypass -File installer\build.ps1 # Windows + Inno Setup 6: dist\payload → dist\VoiceChangerSetup.exe
```
Inno Setup 은 리눅스 wine 에서 돌지 않아(32비트 프로그램이 wine wow64 에서 죽음) Windows 에서 빌드합니다.
## 테스트
```bash
python -m unittest discover -s voice-changer/tests # 마이크 모듈 C 코드를 gcc 로 컴파일해 파이썬 쪽과 맞물려 봄 (soxr · numpy 필요)
```

457
voice-changer/apo/vcapo.cpp Normal file
View File

@@ -0,0 +1,457 @@
/* VoiceChangerAPO.dll: 실제 마이크에 붙는 Windows 오디오 처리 모듈(SFX APO).
* 음성 변환기가 켜져 있으면 마이크 소리를 변환된 목소리로 바꿔 디스코드 · 게임에 보낸다.
* 가상 오디오 드라이버(VB-CABLE 등) 없이 쓰기 위한 것. 처리 내용은 vccore.h.
*
* 빌드 (리눅스): scripts/build-release.sh 가 아래처럼 빌드한다
* x86_64-w64-mingw32-g++ -O2 -shared -static -fno-exceptions -fno-rtti -o VoiceChangerAPO.dll \
* apo/vcapo.cpp apo/vcapo.def -lole32 -luuid -ladvapi32
* 등록 · 해제는 scripts/mic-apo.ps1 (설치 프로그램이 관리자 권한으로 실행). */
#include <windows.h>
#include <objbase.h>
#include <mmreg.h>
#include <propsys.h>
#include <sddl.h>
#include <new>
#include "vccore.h"
/* ---- audioenginebaseapo.h / audiomediatype.h 의 필요한 부분 (mingw 에 없음) ---- */
typedef LONGLONG HNSTIME;
enum { BUFFER_INVALID = 0, BUFFER_VALID = 1, BUFFER_SILENT = 2 };
/* FRAMESPERSECOND_MUST_MATCH | BITSPERSAMPLE_MUST_MATCH | INPLACE (Equalizer APO 와 같음) */
#define VC_APO_FLAGS 0x0000000d
#define APOERR_NOT_INITIALIZED ((HRESULT)0x887D0002L)
#define APOERR_FORMAT_NOT_SUPPORTED ((HRESULT)0x887D0003L)
#define APOERR_ALREADY_UNLOCKED ((HRESULT)0x887D0006L)
#define APOERR_NUM_CONNECTIONS_INVALID ((HRESULT)0x887D0007L)
#define APOERR_APO_LOCKED ((HRESULT)0x887D000AL)
struct UNCOMPRESSEDAUDIOFORMAT {
GUID guidFormatType;
DWORD dwSamplesPerFrame;
DWORD dwBytesPerSampleContainer;
DWORD dwValidBitsPerSample;
FLOAT fFramesPerSecond;
DWORD dwChannelMask;
};
struct IAudioMediaType : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE IsCompressedFormat(BOOL *) = 0;
virtual HRESULT STDMETHODCALLTYPE IsEqual(IAudioMediaType *, DWORD *) = 0;
virtual const WAVEFORMATEX *STDMETHODCALLTYPE GetAudioFormat() = 0;
virtual HRESULT STDMETHODCALLTYPE GetUncompressedAudioFormat(UNCOMPRESSEDAUDIOFORMAT *) = 0;
};
struct APO_CONNECTION_DESCRIPTOR {
UINT32 Type;
UINT_PTR pBuffer;
UINT32 u32MaxFrameCount;
IAudioMediaType *pFormat;
UINT32 u32Signature;
};
struct APO_CONNECTION_PROPERTY {
UINT_PTR pBuffer;
UINT32 u32ValidFrameCount;
UINT32 u32BufferFlags;
UINT32 u32Signature;
};
struct APO_REG_PROPERTIES {
CLSID clsid;
UINT32 Flags;
WCHAR szFriendlyName[256];
WCHAR szCopyrightInfo[256];
UINT32 u32MajorVersion;
UINT32 u32MinorVersion;
UINT32 u32MinInputConnections;
UINT32 u32MaxInputConnections;
UINT32 u32MinOutputConnections;
UINT32 u32MaxOutputConnections;
UINT32 u32MaxInstances;
UINT32 u32NumAPOInterfaces;
IID iidAPOInterfaceList[1];
};
struct APOInitBaseStruct {
UINT32 cbSize;
CLSID clsid;
};
struct APOInitSystemEffects {
APOInitBaseStruct APOInit;
IPropertyStore *pAPOEndpointProperties;
IPropertyStore *pAPOSystemEffectsProperties;
void *pReserved;
IUnknown *pDeviceCollection;
};
struct APOInitSystemEffects2 {
APOInitBaseStruct APOInit;
IPropertyStore *pAPOEndpointProperties;
IPropertyStore *pAPOSystemEffectsProperties;
void *pReserved;
IUnknown *pDeviceCollection;
UINT nSoftwareIoDeviceInCollection;
UINT nSoftwareIoConnectorIndex;
GUID AudioProcessingMode;
BOOL InitializeForDiscoveryOnly;
};
struct IAudioProcessingObject : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE Reset() = 0;
virtual HRESULT STDMETHODCALLTYPE GetLatency(HNSTIME *) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRegistrationProperties(APO_REG_PROPERTIES **) = 0;
virtual HRESULT STDMETHODCALLTYPE Initialize(UINT32, BYTE *) = 0;
virtual HRESULT STDMETHODCALLTYPE IsInputFormatSupported(IAudioMediaType *, IAudioMediaType *, IAudioMediaType **) = 0;
virtual HRESULT STDMETHODCALLTYPE IsOutputFormatSupported(IAudioMediaType *, IAudioMediaType *, IAudioMediaType **) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputChannelCount(UINT32 *) = 0;
};
struct IAudioProcessingObjectRT : public IUnknown {
virtual void STDMETHODCALLTYPE APOProcess(UINT32, APO_CONNECTION_PROPERTY **, UINT32, APO_CONNECTION_PROPERTY **) = 0;
virtual UINT32 STDMETHODCALLTYPE CalcInputFrames(UINT32) = 0;
virtual UINT32 STDMETHODCALLTYPE CalcOutputFrames(UINT32) = 0;
};
struct IAudioProcessingObjectConfiguration : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE LockForProcess(UINT32, APO_CONNECTION_DESCRIPTOR **, UINT32, APO_CONNECTION_DESCRIPTOR **) = 0;
virtual HRESULT STDMETHODCALLTYPE UnlockForProcess() = 0;
};
struct IAudioSystemEffects2 : public IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetEffectsList(LPGUID *, UINT *, HANDLE) = 0;
};
static const IID IID_IAudioProcessingObject_ = {0xFD7F2B29, 0x24D0, 0x4b5c, {0xB1, 0x77, 0x59, 0x2C, 0x39, 0xF9, 0xCA, 0x10}};
static const IID IID_IAudioProcessingObjectRT_ = {0x9E1D6A6D, 0xDDBC, 0x4E95, {0xA4, 0xC7, 0xAD, 0x64, 0xBA, 0x37, 0x84, 0x6C}};
static const IID IID_IAudioProcessingObjectConfiguration_ = {0x0E5ED805, 0xABA6, 0x49c3, {0x8F, 0x9A, 0x2B, 0x8C, 0x88, 0x9C, 0x4F, 0xA8}};
static const IID IID_IAudioSystemEffects_ = {0x5FA00F27, 0xADD6, 0x499a, {0x8A, 0x9D, 0x6B, 0x98, 0x52, 0x1F, 0xA7, 0x5B}};
static const IID IID_IAudioSystemEffects2_ = {0xBAFE99D2, 0x7436, 0x44CE, {0x9E, 0x0E, 0x4D, 0x89, 0xAF, 0xBF, 0xFF, 0x56}};
static const GUID SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
static const PROPERTYKEY PKEY_FriendlyName_ = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14};
/* 이 APO 의 CLSID. scripts/mic-apo.ps1 의 $Clsid 와 같아야 한다. */
static const CLSID CLSID_VoiceChangerAPO = {0x6f1c5e2a, 0x3b7d, 0x4c41, {0x9a, 0x0e, 0x5d, 0x2b, 0x8f, 0x61, 0xc4, 0x37}};
static const wchar_t SHM_NAME[] = L"Global\\VoiceChangerAPO";
static LONG g_objects = 0, g_locks = 0;
#ifdef VC_DEBUG /* 진단용 빌드: audiodg 의 임시 폴더(LocalService)에 vcapo.log 를 남긴다 */
#include <stdio.h>
static void dlog(const char *fmt, ...) {
wchar_t dir[MAX_PATH], path[MAX_PATH];
if (!GetTempPathW(MAX_PATH, dir)) return;
_snwprintf(path, MAX_PATH, L"%lsvcapo.log", dir);
FILE *f = _wfopen(path, L"a");
if (!f) return;
va_list ap;
va_start(ap, fmt);
fprintf(f, "%llu pid=%lu ", (unsigned long long)GetTickCount64(), GetCurrentProcessId());
vfprintf(f, fmt, ap);
fputc('\n', f);
va_end(ap);
fclose(f);
}
#else
#define dlog(...) ((void)0)
#endif
static volatile LONG g_next_id = 0;
static bool is_float32(IAudioMediaType *t, UNCOMPRESSEDAUDIOFORMAT *f) {
if (!t) return false;
BOOL compressed = TRUE;
if (FAILED(t->IsCompressedFormat(&compressed)) || compressed) return false;
if (FAILED(t->GetUncompressedAudioFormat(f))) return false;
return IsEqualGUID(f->guidFormatType, SUBTYPE_IEEE_FLOAT) && f->dwBytesPerSampleContainer == 4 &&
f->dwSamplesPerFrame > 0;
}
static bool same_shape(IAudioMediaType *a, IAudioMediaType *b) {
UNCOMPRESSEDAUDIOFORMAT fa, fb;
if (!is_float32(a, &fa) || !is_float32(b, &fb)) return false;
return fa.dwSamplesPerFrame == fb.dwSamplesPerFrame && fa.fFramesPerSecond == fb.fFramesPerSecond;
}
struct INonDelegatingUnknown {
virtual HRESULT STDMETHODCALLTYPE NDQueryInterface(REFIID, void **) = 0;
virtual ULONG STDMETHODCALLTYPE NDAddRef() = 0;
virtual ULONG STDMETHODCALLTYPE NDRelease() = 0;
};
class VoiceChangerAPO : public INonDelegatingUnknown,
public IAudioProcessingObject,
public IAudioProcessingObjectRT,
public IAudioProcessingObjectConfiguration,
public IAudioSystemEffects2 {
LONG ref_ = 1;
IUnknown *outer_;
bool init_ = false, locked_ = false, discovery_ = false;
UINT32 ch_ = 0, rate_ = 0;
HANDLE map_ = NULL;
vc_header *shm_ = NULL;
vc_inst st_;
void open_shm() {
if (shm_) return;
/* audiodg(LocalService) 가 만들고, 일반 권한의 음성 변환기가 연다 */
SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, FALSE};
PSECURITY_DESCRIPTOR sd = NULL;
if (ConvertStringSecurityDescriptorToSecurityDescriptorW(
L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;LS)(A;;GA;;;IU)(A;;GA;;;AU)S:(ML;;NW;;;LW)", SDDL_REVISION_1, &sd,
NULL))
sa.lpSecurityDescriptor = sd;
map_ = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, 0, VC_SIZE, SHM_NAME);
dlog("open_shm map=%p err=%lu sd=%p", map_, GetLastError(), sd);
if (sd) LocalFree(sd);
if (!map_) return;
shm_ = (vc_header *)MapViewOfFile(map_, FILE_MAP_ALL_ACCESS, 0, 0, VC_SIZE);
if (!shm_) {
CloseHandle(map_);
map_ = NULL;
return;
}
vc_init_header(shm_);
}
void close_shm() {
if (shm_) UnmapViewOfFile(shm_);
if (map_) CloseHandle(map_);
shm_ = NULL;
map_ = NULL;
}
public:
explicit VoiceChangerAPO(IUnknown *outer) {
outer_ = outer ? outer : reinterpret_cast<IUnknown *>(static_cast<INonDelegatingUnknown *>(this));
InterlockedIncrement(&g_objects);
memset(&st_, 0, sizeof(st_));
st_.id = (uint32_t)InterlockedIncrement(&g_next_id) | ((GetCurrentProcessId() & 0xffff) << 16);
if (st_.id == 0) st_.id = 1;
}
virtual ~VoiceChangerAPO() {
close_shm();
InterlockedDecrement(&g_objects);
}
/* 오디오 엔진은 APO 를 COM 집합(aggregation)으로 만든다. 바깥 객체가 있으면 IUnknown 호출은 그쪽으로 넘기고,
자기 수명은 INonDelegatingUnknown 으로 따로 센다 (Windows SDK 의 CBaseAudioProcessingObject 와 같은 방식). */
STDMETHODIMP NDQueryInterface(REFIID riid, void **ppv) override {
if (!ppv) return E_POINTER;
*ppv = NULL;
if (IsEqualIID(riid, IID_IUnknown)) {
*ppv = static_cast<INonDelegatingUnknown *>(this);
NDAddRef();
return S_OK;
}
if (IsEqualIID(riid, IID_IAudioProcessingObject_))
*ppv = static_cast<IAudioProcessingObject *>(this);
else if (IsEqualIID(riid, IID_IAudioProcessingObjectRT_))
*ppv = static_cast<IAudioProcessingObjectRT *>(this);
else if (IsEqualIID(riid, IID_IAudioProcessingObjectConfiguration_))
*ppv = static_cast<IAudioProcessingObjectConfiguration *>(this);
else if (IsEqualIID(riid, IID_IAudioSystemEffects_) || IsEqualIID(riid, IID_IAudioSystemEffects2_))
*ppv = static_cast<IAudioSystemEffects2 *>(this);
else {
dlog("QI miss %08lx", riid.Data1);
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown *>(*ppv)->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG) NDAddRef() override { return (ULONG)InterlockedIncrement(&ref_); }
STDMETHODIMP_(ULONG) NDRelease() override {
LONG r = InterlockedDecrement(&ref_);
if (r == 0) delete this;
return (ULONG)r;
}
STDMETHODIMP QueryInterface(REFIID riid, void **ppv) override { return outer_->QueryInterface(riid, ppv); }
STDMETHODIMP_(ULONG) AddRef() override { return outer_->AddRef(); }
STDMETHODIMP_(ULONG) Release() override { return outer_->Release(); }
/* IAudioProcessingObject */
STDMETHODIMP Reset() override {
st_.primed = 0;
st_.first_seen = 0;
st_.was_alive = 0;
return S_OK;
}
STDMETHODIMP GetLatency(HNSTIME *t) override {
if (!t) return E_POINTER;
*t = 0;
return S_OK;
}
STDMETHODIMP GetRegistrationProperties(APO_REG_PROPERTIES **pp) override {
if (!pp) return E_POINTER;
APO_REG_PROPERTIES *p = (APO_REG_PROPERTIES *)CoTaskMemAlloc(sizeof(APO_REG_PROPERTIES));
if (!p) return E_OUTOFMEMORY;
memset(p, 0, sizeof(*p));
p->clsid = CLSID_VoiceChangerAPO;
p->Flags = VC_APO_FLAGS;
lstrcpynW(p->szFriendlyName, L"Voice Changer", 256);
lstrcpynW(p->szCopyrightInfo, L"voice_copy (MIT)", 256);
p->u32MajorVersion = 1;
p->u32MinorVersion = 0;
p->u32MinInputConnections = p->u32MaxInputConnections = 1;
p->u32MinOutputConnections = p->u32MaxOutputConnections = 1;
p->u32MaxInstances = 0xffffffff;
p->u32NumAPOInterfaces = 1;
p->iidAPOInterfaceList[0] = IID_IAudioProcessingObject_;
*pp = p;
return S_OK;
}
STDMETHODIMP Initialize(UINT32 cb, BYTE *data) override {
if (init_) return S_OK;
if (data && cb >= sizeof(APOInitSystemEffects)) {
APOInitSystemEffects *ini = (APOInitSystemEffects *)data;
if (cb >= sizeof(APOInitSystemEffects2)) discovery_ = ((APOInitSystemEffects2 *)data)->InitializeForDiscoveryOnly != FALSE;
if (ini->pAPOEndpointProperties) {
PROPVARIANT v;
PropVariantInit(&v);
if (SUCCEEDED(ini->pAPOEndpointProperties->GetValue(PKEY_FriendlyName_, &v)) && v.vt == VT_LPWSTR && v.pwszVal) {
unsigned i = 0;
for (; i + 1 < VC_NAME && v.pwszVal[i]; i++) st_.name[i] = (vc_wchar)v.pwszVal[i];
st_.name[i] = 0;
}
PropVariantClear(&v);
}
}
init_ = true;
dlog("Initialize cb=%u discovery=%d name0=%04x", cb, (int)discovery_, st_.name[0]);
return S_OK;
}
STDMETHODIMP IsInputFormatSupported(IAudioMediaType *opposite, IAudioMediaType *req, IAudioMediaType **out) override {
return check_format(opposite, req, out);
}
STDMETHODIMP IsOutputFormatSupported(IAudioMediaType *opposite, IAudioMediaType *req, IAudioMediaType **out) override {
return check_format(opposite, req, out);
}
HRESULT check_format(IAudioMediaType *opposite, IAudioMediaType *req, IAudioMediaType **out) {
if (!req || !out) return E_POINTER;
*out = NULL;
UNCOMPRESSEDAUDIOFORMAT f;
{
UNCOMPRESSEDAUDIOFORMAT r = {};
BOOL c = 0;
req->IsCompressedFormat(&c);
req->GetUncompressedAudioFormat(&r);
dlog("check_format opp=%p comp=%d bytes=%lu bits=%lu ch=%lu rate=%.0f type=%08lx", opposite, c, r.dwBytesPerSampleContainer,
r.dwValidBitsPerSample, r.dwSamplesPerFrame, r.fFramesPerSecond, r.guidFormatType.Data1);
}
if (is_float32(req, &f) && (!opposite || same_shape(opposite, req))) {
req->AddRef();
*out = req;
return S_OK;
}
if (opposite && is_float32(opposite, &f)) { /* 반대쪽과 같은 형식을 제안 */
opposite->AddRef();
*out = opposite;
return S_FALSE;
}
return APOERR_FORMAT_NOT_SUPPORTED;
}
STDMETHODIMP GetInputChannelCount(UINT32 *n) override {
if (!n) return E_POINTER;
if (!locked_) return APOERR_NOT_INITIALIZED;
*n = ch_;
return S_OK;
}
/* IAudioProcessingObjectConfiguration */
STDMETHODIMP LockForProcess(UINT32 nin, APO_CONNECTION_DESCRIPTOR **in, UINT32 nout, APO_CONNECTION_DESCRIPTOR **out) override {
dlog("LockForProcess nin=%u nout=%u", nin, nout);
if (locked_) return APOERR_APO_LOCKED;
if (nin != 1 || nout != 1 || !in || !out || !in[0] || !out[0]) return APOERR_NUM_CONNECTIONS_INVALID;
UNCOMPRESSEDAUDIOFORMAT fi, fo;
if (!is_float32(in[0]->pFormat, &fi) || !is_float32(out[0]->pFormat, &fo) ||
fi.dwSamplesPerFrame != fo.dwSamplesPerFrame || fi.fFramesPerSecond != fo.fFramesPerSecond)
return APOERR_FORMAT_NOT_SUPPORTED;
dlog("format ch=%lu rate=%.0f", fi.dwSamplesPerFrame, fi.fFramesPerSecond);
ch_ = fi.dwSamplesPerFrame;
rate_ = (UINT32)(fi.fFramesPerSecond + 0.5f);
if (!discovery_) open_shm();
Reset();
locked_ = true;
return S_OK;
}
STDMETHODIMP UnlockForProcess() override {
if (!locked_) return APOERR_ALREADY_UNLOCKED;
if (shm_ && shm_->owner == st_.id) VC_CAS(&shm_->owner, 0u, st_.id);
close_shm();
locked_ = false;
return S_OK;
}
/* IAudioProcessingObjectRT: 실시간 스레드. 메모리 할당 · 잠금 금지 */
STDMETHODIMP_(void) APOProcess(UINT32 nin, APO_CONNECTION_PROPERTY **in, UINT32 nout, APO_CONNECTION_PROPERTY **out) override {
if (nin < 1 || nout < 1) return;
#ifdef VC_DEBUG
static volatile LONG calls = 0;
if (InterlockedIncrement(&calls) % 500 == 1) dlog("APOProcess frames=%u flags=%u shm=%p", in[0]->u32ValidFrameCount, in[0]->u32BufferFlags, shm_);
#endif
APO_CONNECTION_PROPERTY *i = in[0], *o = out[0];
UINT32 frames = i->u32ValidFrameCount;
float *dst = (float *)o->pBuffer;
const float *src = (const float *)i->pBuffer;
size_t bytes = (size_t)frames * ch_ * 4;
if (i->u32BufferFlags == BUFFER_SILENT)
memset(dst, 0, bytes);
else if (dst != src)
memcpy(dst, src, bytes);
vc_process(&st_, shm_, dst, frames, ch_, rate_, (int64_t)GetTickCount64());
o->u32ValidFrameCount = frames;
o->u32BufferFlags = BUFFER_VALID;
}
STDMETHODIMP_(UINT32) CalcInputFrames(UINT32 n) override { return n; }
STDMETHODIMP_(UINT32) CalcOutputFrames(UINT32 n) override { return n; }
/* IAudioSystemEffects2: 윈도우 설정 화면에 보여 줄 효과 목록은 없음 */
STDMETHODIMP GetEffectsList(LPGUID *ids, UINT *count, HANDLE) override {
if (!ids || !count) return E_POINTER;
*ids = NULL;
*count = 0;
return S_OK;
}
};
class Factory : public IClassFactory {
public:
STDMETHODIMP QueryInterface(REFIID riid, void **ppv) override {
if (!ppv) return E_POINTER;
if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) {
*ppv = static_cast<IClassFactory *>(this);
return S_OK;
}
*ppv = NULL;
return E_NOINTERFACE;
}
STDMETHODIMP_(ULONG) AddRef() override { return 2; }
STDMETHODIMP_(ULONG) Release() override { return 1; }
STDMETHODIMP CreateInstance(IUnknown *outer, REFIID riid, void **ppv) override {
if (!ppv) return E_POINTER;
*ppv = NULL;
dlog("CreateInstance outer=%p riid=%08lx", outer, riid.Data1);
if (outer && !IsEqualIID(riid, IID_IUnknown)) return CLASS_E_NOAGGREGATION;
VoiceChangerAPO *a = new (std::nothrow) VoiceChangerAPO(outer);
if (!a) return E_OUTOFMEMORY;
HRESULT hr = a->NDQueryInterface(riid, ppv);
a->NDRelease();
return hr;
}
STDMETHODIMP LockServer(BOOL lock) override {
if (lock)
InterlockedIncrement(&g_locks);
else
InterlockedDecrement(&g_locks);
return S_OK;
}
};
static Factory g_factory;
extern "C" HRESULT STDAPICALLTYPE DllGetClassObject(REFCLSID clsid, REFIID riid, void **ppv) {
dlog("DllGetClassObject clsid=%08lx", clsid.Data1);
if (!IsEqualCLSID(clsid, CLSID_VoiceChangerAPO)) return CLASS_E_CLASSNOTAVAILABLE;
return g_factory.QueryInterface(riid, ppv);
}
extern "C" HRESULT STDAPICALLTYPE DllCanUnloadNow() { return (g_objects == 0 && g_locks == 0) ? S_OK : S_FALSE; }

View File

@@ -0,0 +1,4 @@
LIBRARY VoiceChangerAPO
EXPORTS
DllGetClassObject PRIVATE
DllCanUnloadNow PRIVATE

165
voice-changer/apo/vccore.h Normal file
View File

@@ -0,0 +1,165 @@
/* 마이크 APO 와 음성 변환기(app/mic_bridge.py)가 함께 쓰는 공유 메모리 규약과 APO 쪽 처리.
*
* APO 는 실제 마이크의 소리 처리 단계(audiodg.exe 안)에서 10ms 마다 불린다.
* - 변환기가 꺼져 있으면 아무것도 하지 않는다 (원래 목소리가 그대로 나감)
* - 변환기가 켜져 있고 이 마이크를 고르면: 원래 소리를 in 링에 쓰고, 변환기가 out 링에 써 준
* 변환된 소리를 내보낸다. 변환된 소리가 아직 없으면 무음 (원래 목소리가 새지 않게)
* 리눅스 테스트(tests/test_mic_bridge.py)가 이 파일을 그대로 컴파일해 파이썬 쪽과 맞춰 본다.
* 레이아웃을 바꾸면 VC_VERSION 과 mic_bridge.py 의 Header 를 같이 바꿀 것. */
#ifndef VCCORE_H
#define VCCORE_H
#include <stdint.h>
#include <string.h>
#define VC_MAGIC 0x31414356u /* "VCA1" */
#define VC_VERSION 1u
#define VC_RING 262144u /* 프레임 (48kHz 에서 5.4초) */
#define VC_HEADER 4096u
#define VC_SLOTS 8u
#define VC_NAME 128u
#define VC_SIZE (VC_HEADER + 2u * VC_RING * 4u)
typedef uint16_t vc_wchar; /* UTF-16 (Windows wchar_t) */
typedef struct {
vc_wchar name[VC_NAME];
volatile int64_t beat; /* 이 마이크의 APO 가 마지막으로 돈 시각 (ms) */
} vc_slot;
typedef struct {
uint32_t magic, version; /* 0 */
volatile int64_t app_beat; /* 8: 변환기가 살아 있다는 표시 (ms, GetTickCount64) */
volatile int64_t apo_beat; /* 16: 입력을 쓰는 APO 의 마지막 시각 */
volatile int64_t in_w; /* 24: in 링에 쓴 프레임 수 (누적) */
volatile int64_t out_w; /* 32: out 링에 쓴 프레임 수 (누적, 변환기가 씀) */
volatile uint32_t owner; /* 40: 입력을 쓰는 APO 인스턴스 (0 = 없음) */
volatile uint32_t rate; /* 44: 입력 샘플레이트 */
volatile uint32_t active; /* 48: 변환기가 켜져 있음 */
volatile uint32_t prefill_ms; /* 52: 변환된 소리를 이만큼 모은 뒤 내보냄 (끊김 방지 여유) */
volatile uint32_t underruns; /* 56: 변환된 소리가 모자랐던 횟수 */
uint32_t reserved; /* 60 */
vc_wchar target[VC_NAME]; /* 64: 변환할 마이크 이름 (변환기가 씀) */
vc_slot slots[VC_SLOTS]; /* 320: 지금 APO 가 붙어 도는 마이크들 (진단용) */
} vc_header;
typedef struct {
uint32_t id;
int primed; /* 변환된 소리를 내보내는 중 */
int64_t cursor; /* out 링에서 다음에 읽을 위치 */
int64_t first_seen; /* 다시 모으기 시작한 시각 (0 = 아직 소리 없음) */
int64_t slot_beat;
int was_alive;
vc_wchar name[VC_NAME];
} vc_inst;
#if defined(_MSC_VER) || defined(_WIN32)
#include <windows.h>
#define VC_CAS(p, n, o) ((uint32_t)InterlockedCompareExchange((volatile LONG *)(p), (LONG)(n), (LONG)(o)))
#define VC_FENCE() MemoryBarrier()
#else
#define VC_CAS(p, n, o) __sync_val_compare_and_swap((p), (o), (n))
#define VC_FENCE() __sync_synchronize()
#endif
static inline int vc_name_eq(const vc_wchar *a, const vc_wchar *b) {
for (unsigned i = 0; i < VC_NAME; i++) {
if (a[i] != b[i]) return 0;
if (a[i] == 0) return 1;
}
return 1;
}
static inline float *vc_in_ring(vc_header *s) { return (float *)((uint8_t *)s + VC_HEADER); }
static inline float *vc_out_ring(vc_header *s) { return (float *)((uint8_t *)s + VC_HEADER + VC_RING * 4u); }
static inline void vc_init_header(vc_header *s) {
if (s->magic != VC_MAGIC) {
s->version = VC_VERSION;
s->prefill_ms = 60;
VC_FENCE();
s->magic = VC_MAGIC;
}
}
static inline void vc_mark_slot(vc_inst *st, vc_header *s, int64_t now) {
if (now - st->slot_beat < 500) return;
st->slot_beat = now;
unsigned pick = VC_SLOTS;
for (unsigned i = 0; i < VC_SLOTS; i++)
if (vc_name_eq(s->slots[i].name, st->name)) { pick = i; break; }
if (pick == VC_SLOTS) {
int64_t oldest = INT64_MAX;
for (unsigned i = 0; i < VC_SLOTS; i++)
if (s->slots[i].beat < oldest) { oldest = s->slots[i].beat; pick = i; }
memcpy(s->slots[pick].name, st->name, sizeof(st->name));
}
s->slots[pick].beat = now;
}
/* io: 인터리브 float32 (frames × ch). 들어올 때 원래 마이크 소리, 나갈 때 내보낼 소리. */
static inline void vc_process(vc_inst *st, vc_header *s, float *io, uint32_t frames, uint32_t ch,
uint32_t rate, int64_t now) {
if (!s || s->magic != VC_MAGIC || s->version != VC_VERSION || ch == 0) return;
vc_mark_slot(st, s, now);
int alive = s->active && now - s->app_beat < 1500 && vc_name_eq(s->target, st->name);
if (!alive) {
if (s->owner == st->id) VC_CAS(&s->owner, 0u, st->id);
st->was_alive = 0;
return; /* 그대로 내보냄 */
}
if (!st->was_alive) { /* 막 켜짐: 지금 쓰인 곳부터 읽는다 */
st->was_alive = 1;
st->primed = 0;
st->first_seen = 0;
st->cursor = s->out_w;
}
uint32_t o = s->owner;
if (o == 0 || (o != st->id && now - s->apo_beat > 300)) VC_CAS(&s->owner, st->id, o);
if (s->owner == st->id) {
float *in = vc_in_ring(s);
int64_t w = s->in_w;
for (uint32_t i = 0; i < frames; i++) {
float m = 0;
for (uint32_t c = 0; c < ch; c++) m += io[i * ch + c];
in[(uint64_t)(w + i) % VC_RING] = m / (float)ch;
}
s->rate = rate;
VC_FENCE();
s->in_w = w + frames;
s->apo_beat = now;
}
if (s->rate != rate) { memset(io, 0, (size_t)frames * ch * 4); return; }
int64_t ow = s->out_w;
VC_FENCE();
int64_t avail = ow - st->cursor;
if (avail < 0 || avail > (int64_t)(VC_RING / 2)) { /* 너무 뒤처짐: 최신으로 */
st->cursor = ow;
st->primed = 0;
st->first_seen = 0;
avail = 0;
}
if (!st->primed) {
if (avail > 0 && st->first_seen == 0) st->first_seen = now;
if (st->first_seen == 0 || now - st->first_seen < (int64_t)s->prefill_ms) {
memset(io, 0, (size_t)frames * ch * 4);
return;
}
st->primed = 1;
}
const float *out = vc_out_ring(s);
uint32_t n = avail < (int64_t)frames ? (uint32_t)avail : frames;
for (uint32_t i = 0; i < n; i++) {
float v = out[(uint64_t)(st->cursor + i) % VC_RING];
for (uint32_t c = 0; c < ch; c++) io[i * ch + c] = v;
}
if (n < frames) {
memset(io + (size_t)n * ch, 0, (size_t)(frames - n) * ch * 4);
st->primed = 0;
st->first_seen = 0;
s->underruns++;
}
st->cursor += n;
}
#endif

View File

@@ -0,0 +1,80 @@
"""경로와 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"
CACHE = ROOT / "cache"
def keep_files_in_root():
"""라이브러리가 사용자 폴더(%TEMP% · %USERPROFILE%\\.cache · %APPDATA%)에 쓰는 캐시와 임시 파일을
모두 설치 폴더 안 cache\\ 로 돌린다. 다른 import 보다 먼저 돌아야 해서 이 모듈을 불러올 때 바로 한다."""
dirs = {
"TEMP": "temp", "TMP": "temp", "TMPDIR": "temp",
"TORCH_HOME": "torch", "TORCHINDUCTOR_CACHE_DIR": "torch/inductor", "CUDA_CACHE_PATH": "cuda",
"HF_HOME": "huggingface", "XDG_CACHE_HOME": "xdg", "MPLCONFIGDIR": "matplotlib",
"NUMBA_CACHE_DIR": "numba", "PIP_CACHE_DIR": "pip", "UV_CACHE_DIR": "uv",
}
for var, sub in dirs.items():
p = CACHE / sub
p.mkdir(parents=True, exist_ok=True)
os.environ[var] = str(p)
os.environ["PYTHONNOUSERSITE"] = "1" # %APPDATA%\Python 의 패키지를 읽지도 쓰지도 않게
import tempfile
tempfile.tempdir = None # 위 TEMP 를 다시 읽게
keep_files_in_root()
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"

View File

@@ -0,0 +1,177 @@
"""한국어 예시 모델 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 shutil
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"
marker = out.parent / "done.txt" # 끝까지 뽑았을 때만 쓴다. 중간에 끊긴 폴더는 다시 뽑는다
if marker.is_file() and float(marker.read_text(encoding="utf-8").split()[0]) >= minutes:
return out
print("KSS 받기 (약 540MB)...")
pq_path = _download(KSS_URL, DATASETS / "_downloads" / "kss-00000.parquet")
if out.exists():
shutil.rmtree(out)
out.mkdir(parents=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:
break
if total >= minutes * 60:
break
marker.write_text(f"{total / 60!r} {n}", encoding="utf-8")
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, *got = meta.read_text(encoding="utf-8").split()
if want.get(sex, 0) > 0 and float(got[0] if got else 0) >= minutes:
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 / "speaker.txt").unlink(missing_ok=True)
if (d / "raw").exists():
shutil.rmtree(d / "raw")
(d / "raw").mkdir(parents=True)
for fname, b in files.pop(spk):
(d / "raw" / fname).write_bytes(b)
(d / "speaker.txt").write_text(f"{spk} {sex} {secs[spk] / 60!r}", 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())

View File

@@ -0,0 +1,160 @@
"""마이크 APO(apo/vcapo.cpp)와 주고받는 공유 메모리. 규약은 apo/vccore.h 와 같다.
APO 가 실제 마이크 소리를 in 링에 쓰면, 변환기가 읽어서 바꾼 소리를 out 링에 쓴다.
APO 는 그 소리를 마이크 소리 대신 디스코드 · 게임에 보낸다.
"""
import ctypes
import sys
import time
import numpy as np
NAME = "Global\\VoiceChangerAPO"
MAGIC = 0x31414356
VERSION = 1
RING = 262144
HEADER = 4096
SLOTS = 8
NAME_LEN = 128
SIZE = HEADER + 2 * RING * 4
class Slot(ctypes.Structure):
_fields_ = [("name", ctypes.c_uint16 * NAME_LEN), ("beat", ctypes.c_int64)]
class Header(ctypes.Structure):
_fields_ = [
("magic", ctypes.c_uint32),
("version", ctypes.c_uint32),
("app_beat", ctypes.c_int64),
("apo_beat", ctypes.c_int64),
("in_w", ctypes.c_int64),
("out_w", ctypes.c_int64),
("owner", ctypes.c_uint32),
("rate", ctypes.c_uint32),
("active", ctypes.c_uint32),
("prefill_ms", ctypes.c_uint32),
("underruns", ctypes.c_uint32),
("reserved", ctypes.c_uint32),
("target", ctypes.c_uint16 * NAME_LEN),
("slots", Slot * SLOTS),
]
assert ctypes.sizeof(Header) <= HEADER and Header.target.offset == 64 and Header.slots.offset == 320
def tick_ms() -> int:
"""APO 와 같은 시계 (GetTickCount64)."""
if sys.platform == "win32":
f = ctypes.windll.kernel32.GetTickCount64
f.restype = ctypes.c_uint64
return int(f())
return int(time.monotonic() * 1000)
def _utf16(s: str) -> list:
b = s.encode("utf-16-le")[: (NAME_LEN - 1) * 2]
return list(np.frombuffer(b, dtype="<u2")) + [0]
def _from_utf16(arr) -> str:
a = np.array(arr[:], dtype="<u2")
n = int(np.argmin(a)) if (a == 0).any() else len(a)
return a[:n].tobytes().decode("utf-16-le", "replace")
class NotConnected(RuntimeError):
pass
class Bridge:
def __init__(self, buf, clock=tick_ms, keep=None):
self._keep = keep # 매핑 핸들 등 (buf 보다 먼저 사라지면 안 됨)
self.clock = clock
self.h = Header.from_buffer(buf)
self.inr = np.frombuffer(buf, np.float32, RING, offset=HEADER)
self.outr = np.frombuffer(buf, np.float32, RING, offset=HEADER + RING * 4)
self.cursor = None
@classmethod
def open(cls):
"""APO 가 만든 공유 메모리를 연다. 아직 마이크를 쓰는 앱이 없으면 NotConnected."""
if sys.platform != "win32":
raise NotConnected("Windows 에서만 됩니다")
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.OpenFileMappingW.restype = ctypes.c_void_p
k32.OpenFileMappingW.argtypes = [ctypes.c_uint32, ctypes.c_int, ctypes.c_wchar_p]
k32.MapViewOfFile.restype = ctypes.c_void_p
k32.MapViewOfFile.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_size_t]
h = k32.OpenFileMappingW(0x0006, 0, NAME) # FILE_MAP_READ | FILE_MAP_WRITE
if not h:
raise NotConnected(f"마이크 변환 모듈이 아직 열리지 않았습니다 (오류 {ctypes.get_last_error()})")
p = k32.MapViewOfFile(h, 0x0006, 0, 0, SIZE)
if not p:
k32.CloseHandle(ctypes.c_void_p(h))
raise NotConnected(f"공유 메모리를 열지 못했습니다 (오류 {ctypes.get_last_error()})")
buf = (ctypes.c_char * SIZE).from_address(p)
b = cls(buf, keep=(k32, h, p))
if b.h.magic != MAGIC or b.h.version != VERSION:
raise NotConnected("마이크 변환 모듈 버전이 맞지 않습니다. 설치를 다시 해 주세요")
return b
def close(self):
if self._keep and sys.platform == "win32":
k32, h, p = self._keep
self.h = self.inr = self.outr = None
k32.UnmapViewOfFile(ctypes.c_void_p(p))
k32.CloseHandle(ctypes.c_void_p(h))
self._keep = None
# ---- 상태 ----
def endpoints(self, within_ms=2000) -> list:
"""최근에 APO 가 돈 마이크 이름들."""
now = self.clock()
return [_from_utf16(s.name) for s in self.h.slots if s.beat and now - s.beat < within_ms and s.name[0]]
def owner_alive(self, within_ms=500) -> bool:
return self.h.owner != 0 and self.clock() - self.h.apo_beat < within_ms
@property
def rate(self) -> int:
return int(self.h.rate)
def start(self, target: str, prefill_ms: int = 60):
h = self.h
h.target[:] = (_utf16(target) + [0] * NAME_LEN)[:NAME_LEN]
h.prefill_ms = prefill_ms
h.app_beat = self.clock()
self.cursor = None
h.active = 1
def beat(self):
self.h.app_beat = self.clock()
def stop(self):
if self.h is not None:
self.h.active = 0
# ---- 소리 ----
def read(self, max_lag: int) -> np.ndarray:
"""APO 가 새로 쓴 마이크 소리 (모노 float32). 너무 밀렸으면 최근 max_lag 프레임만."""
w = int(self.h.in_w)
if self.cursor is None or w - self.cursor > min(max_lag, RING) or w < self.cursor:
self.cursor = max(w - max_lag, 0) if self.cursor is not None else w
n = w - self.cursor
if n <= 0:
return np.zeros(0, np.float32)
i = np.arange(self.cursor, w) % RING
self.cursor = w
return self.inr[i].copy()
def write(self, x: np.ndarray):
"""변환된 소리를 out 링에 이어 쓴다. 쓴 뒤에 위치를 올려야 APO 가 덜 쓴 소리를 읽지 않는다."""
x = np.asarray(x, np.float32).reshape(-1)
if len(x) == 0:
return
w = int(self.h.out_w)
self.outr[np.arange(w, w + len(x)) % RING] = x
self.h.out_w = w + len(x)

View 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

View 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
View 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())

View File

@@ -0,0 +1,515 @@
"""실시간 음성 변환기 (Windows 게임PC 용 화면).
마이크로 들어온 내 말소리를 고른 목소리 모델로 바꿔서, 그 마이크에서 나가는 소리를 바꿔치기한다.
마이크에 붙인 오디오 처리 모듈(apo/VoiceChangerAPO.dll)이 소리를 주고받으므로 가상 케이블이 필요 없다.
디스코드 · 게임의 입력 장치는 평소 마이크 그대로 두면 된다.
"""
import json
import multiprocessing as mp
import queue
import sys
import threading
import time
import tkinter as tk
from tkinter import messagebox, ttk
from common import ROOT, 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():
"""(마이크 이름→번호, 출력 이름→번호). 마이크는 WASAPI 항목만 쓴다 (이름이 윈도우 장치 이름과 같아서
마이크 모듈이 자기 마이크인지 알아볼 수 있음)."""
from rvc.realtime.audio import list_audio_device
ins, outs = list_audio_device()
mics = {d.name: d.index for d in ins if "WASAPI" in d.host_api and "loopback" not in d.name.lower()}
fmt = lambda d: f"{d.name} ({d.host_api})"
return mics, {fmt(d): d.index for d in outs}
def hooked_mics() -> list:
"""설치할 때 마이크 모듈을 붙인 마이크들 (scripts/mic-apo.ps1 이 apo\\ 에 남긴 목록)."""
try:
items = json.loads((ROOT / "apo" / "mic-apo.json").read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return []
items = items if isinstance(items, list) else [items]
return [(i.get("desc") or "", i.get("iface") or "") for i in items if isinstance(i, dict)]
def is_hooked(name: str, hooked: list) -> bool:
return any(d and d in name and (not f or f in name) for d, f in hooked)
def reconnect_params(root=None) -> str:
"""관리자 PowerShell 에 넘길 인자. Windows 경로에는 " 가 들어갈 수 없어서 큰따옴표로만 감싸면 공백 · 한글 경로도 안전하다."""
root = ROOT if root is None else root
script, r = str(root / "scripts" / "mic-apo.ps1"), str(root)
if r.endswith("\\"): # "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로
r += "."
return f'-NoProfile -ExecutionPolicy Bypass -File "{script}" -Install -Root "{r}"'
def mic_apo_log_tail(lines: int = 8) -> str:
"""scripts/mic-apo.ps1 이 apo\\mic-apo.log 에 남긴 마지막 기록."""
try:
text = (ROOT / "apo" / "mic-apo.log").read_text(encoding="utf-8-sig", errors="replace")
except OSError:
return "(기록 없음)"
return "\n".join(text.strip().splitlines()[-lines:])
def reconnect_mics() -> int:
"""관리자 권한으로 mic-apo.ps1 -Install 을 돌린다 (UAC 확인 창이 뜸). 스크립트의 종료 코드를 돌려준다.
ShellExecuteExW("runas") 로 PowerShell 하나만 띄우고 끝날 때까지 기다린다. -1223 = 사용자가 UAC 를 취소함."""
import ctypes
from ctypes import wintypes
class SHELLEXECUTEINFOW(ctypes.Structure):
_fields_ = [("cbSize", wintypes.DWORD), ("fMask", wintypes.ULONG), ("hwnd", wintypes.HWND),
("lpVerb", wintypes.LPCWSTR), ("lpFile", wintypes.LPCWSTR), ("lpParameters", wintypes.LPCWSTR),
("lpDirectory", wintypes.LPCWSTR), ("nShow", ctypes.c_int), ("hInstApp", wintypes.HINSTANCE),
("lpIDList", ctypes.c_void_p), ("lpClass", wintypes.LPCWSTR), ("hkeyClass", wintypes.HKEY),
("dwHotKey", wintypes.DWORD), ("hIconOrMonitor", wintypes.HANDLE), ("hProcess", wintypes.HANDLE)]
shell32 = ctypes.WinDLL("shell32", use_last_error=True)
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
k32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
k32.CloseHandle.argtypes = [wintypes.HANDLE]
sei = SHELLEXECUTEINFOW(cbSize=ctypes.sizeof(SHELLEXECUTEINFOW), fMask=0x40, # SEE_MASK_NOCLOSEPROCESS
lpVerb="runas", lpFile="powershell.exe", lpParameters=reconnect_params(),
lpDirectory=str(ROOT), nShow=0)
if not shell32.ShellExecuteExW(ctypes.byref(sei)):
return -ctypes.get_last_error()
try:
k32.WaitForSingleObject(sei.hProcess, 0xFFFFFFFF)
code = wintypes.DWORD()
k32.GetExitCodeProcess(sei.hProcess, ctypes.byref(code))
return int(code.value)
finally:
k32.CloseHandle(sei.hProcess)
class Converter:
"""Applio 실시간 엔진 하나를 켜고, 마이크 모듈과 소리를 주고받는다."""
def __init__(self):
self.callbacks = None
self.bridge = None
self.streams = []
self.halt = threading.Event()
self.worker = None
self.error = None
@property
def running(self):
return self.callbacks is not None
def start(self, model, pitch, mic_name, mic_id, monitor_id, chunk_ms, threshold, index_rate, on_status):
import numpy as np
import sounddevice as sd
from mic_bridge import Bridge, NotConnected
from rvc.realtime.callbacks import AudioCallbacks
from rvc.realtime.core import AUDIO_SAMPLE_RATE
# 엔진은 받은 소리를 항상 48kHz 로 보고 분석·합성한다. 마이크 소리는 장치 샘플레이트로 오므로
# 48kHz 로 바꿔서 넣고, 나온 소리를 다시 장치 샘플레이트로 바꿔 마이크로 돌려보낸다.
sr = AUDIO_SAMPLE_RATE
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
self.halt.clear()
self.error = None
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)
try:
on_status("마이크에 연결하는 중...")
# 마이크를 쓰는 앱이 하나라도 있어야 윈도우가 마이크 모듈을 돌린다. 디스코드가 꺼져 있어도
# 변환이 돌도록 이 앱도 마이크를 연다 (받은 소리는 쓰지 않음).
keep = sd.InputStream(device=mic_id, channels=1, dtype="float32", callback=lambda *a: None,
extra_settings=sd.WasapiSettings(auto_convert=True))
keep.start()
self.streams.append(keep)
b, err = None, None
for _ in range(50):
try:
b = Bridge.open()
break
except NotConnected as e:
err = e
time.sleep(0.1)
if b is None:
raise RuntimeError(f"{err}\n'마이크 다시 연결' 을 눌러 주세요.")
self.bridge = b
b.start(mic_name, prefill_ms=60)
for _ in range(30):
if b.owner_alive() and b.rate:
break
b.beat()
time.sleep(0.1)
else:
seen = ", ".join(b.endpoints()) or "없음"
raise RuntimeError(
f"'{mic_name}' 에 마이크 모듈이 붙어 있지 않습니다 (모듈이 붙은 마이크: {seen}).\n"
"'마이크 다시 연결' 을 누르고, 윈도우 소리 설정에서 이 마이크의 '오디오 향상' 이 켜져 있는지 확인해 주세요."
)
if monitor_id is not None: # 엔진의 모니터 큐(cb.audio.mon_queue)를 헤드셋으로
dev = sd.query_devices(monitor_id)
api = sd.query_hostapis(dev["hostapi"])["name"]
mon = sd.OutputStream(
callback=lambda outdata, frames, times, status: cb.audio.audio_queue(cb.audio.mon_queue, outdata, cb.audio.monitor_audio_gain),
latency="low", dtype=np.float32, device=monitor_id, blocksize=block, samplerate=sr,
channels=min(2, dev["max_output_channels"]),
extra_settings=sd.WasapiSettings(auto_convert=True) if "WASAPI" in api else None,
)
cb.audio.running = True
mon.start()
self.streams.append(mon)
except Exception as e:
self.stop()
if isinstance(e, RuntimeError):
raise
raise RuntimeError(f"마이크를 열지 못했습니다: {e}") from e
self.worker = threading.Thread(target=self._pump, args=(b, cb, block, sr), daemon=True)
self.worker.start()
def _pump(self, b, cb, block, sr):
"""마이크 모듈 ↔ 엔진. 장치 샘플레이트 ↔ 48kHz 는 끊김 없이 이어지는 리샘플러로 바꾼다."""
import numpy as np
import soxr
from rvc.realtime.audio import queue_latest
rate, rs_in, rs_out = None, None, None
pending = np.zeros(0, np.float32)
try:
while not self.halt.is_set():
b.beat()
if not b.rate: # 마이크 모듈이 아직 소리를 쓰기 전
time.sleep(0.005)
continue
if b.rate != rate:
rate = b.rate
rs_in = soxr.ResampleStream(rate, sr, 1, dtype="float32") if rate != sr else None
rs_out = soxr.ResampleStream(sr, rate, 1, dtype="float32") if rate != sr else None
pending = np.zeros(0, np.float32)
x = b.read(max_lag=rate) # 1초 넘게 밀렸으면 버리고 따라잡는다
if len(x):
pending = np.concatenate([pending, rs_in.resample_chunk(x) if rs_in else x])
while len(pending) >= block and not self.halt.is_set():
blk, pending = pending[:block], pending[block:]
out = np.asarray(cb.audio.process_data_with_time(blk[:, None]), np.float32) * cb.audio.output_audio_gain
if cb.audio.use_monitor:
queue_latest(cb.audio.mon_queue, out)
b.write(rs_out.resample_chunk(out) if rs_out else out)
time.sleep(0.005)
except Exception as e: # 화면이 알 수 있게 남긴다
self.error = e
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 mic_ok(self) -> bool:
return self.bridge is not None and self.bridge.owner_alive(1000)
def stop(self):
cb, self.callbacks = self.callbacks, None
self.halt.set()
if self.worker is not None:
self.worker.join(timeout=3)
self.worker = None
if self.bridge is not None:
self.bridge.stop() # 마이크 모듈이 바로 원래 목소리로 돌아감
self.bridge.close()
self.bridge = None
for s in self.streams:
try:
s.abort()
s.close()
except Exception:
pass
self.streams = []
if cb is not None:
cb.audio.running = False
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.mon_dev = 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, sticky="ew", padx=10)
self.in_box.bind("<<ComboboxSelected>>", lambda e: self.show_mic_state())
self.reconnect_btn = ttk.Button(f, text="마이크 다시 연결", command=self.reconnect)
self.reconnect_btn.grid(row=6, column=2, sticky="e", padx=10)
self.mic_state = ttk.Label(f, text="", foreground="#555")
self.mic_state.grid(row=7, column=0, columnspan=3, sticky="w", 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.hooked = hooked_mics()
self.in_box["values"] = list(self.ins)
self.mon_box["values"] = list(self.outs)
for var, choices, key in ((self.in_dev, self.ins, "input"), (self.mon_dev, self.outs, "monitor")):
saved = self.settings.get(key)
var.set(saved if saved in choices else next(iter(choices), ""))
self.show_mic_state()
def show_mic_state(self):
name = self.in_dev.get()
if not name:
self.mic_state.config(text="마이크가 없습니다.")
elif is_hooked(name, self.hooked):
self.mic_state.config(text="디스코드 · 게임의 입력 장치는 이 마이크 그대로 두세요. 변환을 켜면 이 마이크로 바뀐 목소리가 나갑니다.")
else:
self.mic_state.config(text="이 마이크에는 아직 변환 모듈이 없습니다. '마이크 다시 연결' 을 눌러 주세요 (새로 꽂은 마이크 등).")
def reconnect(self):
if self.conv.running:
messagebox.showinfo("음성 변환기", "변환을 정지한 뒤에 눌러 주세요.")
return
if not messagebox.askokcancel("음성 변환기", "관리자 권한으로 모든 마이크에 변환 모듈을 붙입니다.\n윈도우 소리가 1~2초 끊겼다가 돌아옵니다."):
return
self.reconnect_btn.config(state="disabled")
self.status.config(text="마이크 연결 중...")
def run():
try:
code = reconnect_mics()
except Exception as e:
code = str(e)
self.events.put(("reconnected", code))
threading.Thread(target=run, daemon=True).start()
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:
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.in_dev.get(), self.ins[self.in_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)
elif kind == "reconnected":
self.reconnect_btn.config(state="normal")
self.load_devices()
if val == 0:
self.status.config(text="마이크를 다시 연결했습니다.")
else:
self.status.config(text="마이크 연결을 취소했습니다." if val == -1223 else f"마이크를 연결하지 못했습니다 (코드 {val}).")
if val != -1223:
messagebox.showerror("음성 변환기", f"마이크를 연결하지 못했습니다 (코드 {val}).\n\n{mic_apo_log_tail()}")
if self.conv.running and str(self.stop_btn["state"]) == "normal":
if self.conv.error is not None:
err, self.conv.error = self.conv.error, None
self.stop()
messagebox.showerror("음성 변환기", f"변환이 멈췄습니다.\n{err}")
elif not self.conv.mic_ok():
self.status.config(text=f"● 변환 중: {self.running_name} · 마이크 신호 없음 (마이크가 뽑혔거나 윈도우 소리가 다시 시작됨)")
else:
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(),
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())

View 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

View 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

View File

@@ -0,0 +1,209 @@
; 음성 변환기 설치 프로그램 (Inno Setup 6). 빌드: scripts/build-release.sh 가 만든 dist\payload 를 담는다.
; ISCC.exe installer\VoiceChanger.iss → dist\VoiceChangerSetup.exe
; 하는 일
; 1. 설치할 폴더를 고르게 한다. Python · 엔진 · 모델 · 설정 · 캐시 · 임시 파일이 모두 그 폴더 안에만 생긴다
; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음)
; 3. Python · 엔진 · torch(CUDA) · 엔진 기본 모델을 그 폴더 안으로 내려받는다 (scripts\install.ps1, 10~20분)
; 제거할 때는 마이크 설정을 원래대로 되돌리고, 모델 · 녹음까지 지울지 묻는다.
#define AppName "음성 변환기"
#ifndef AppVersion
#define AppVersion "1.0.0"
#endif
[Setup]
AppId={{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90}
AppName={#AppName}
AppVersion={#AppVersion}
AppPublisher=voice_copy
DefaultDirName={sd}\VoiceChanger
DisableDirPage=no
DisableProgramGroupPage=yes
DirExistsWarning=no
AllowUNCPath=no
PrivilegesRequired=admin
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
MinVersion=10.0.19041
OutputDir=..\dist
OutputBaseFilename=VoiceChangerSetup
Compression=lzma2
SolidCompression=yes
WizardStyle=modern
UninstallFilesDir={app}\uninstall
UninstallDisplayIcon={app}\VoiceChanger.exe
UninstallDisplayName={#AppName}
[Languages]
Name: "ko"; MessagesFile: "compiler:Languages\Korean.isl"
[Messages]
ko.SelectDirLabel3=음성 변환기를 설치할 폴더를 골라 주세요.%n%nPython · 변환 엔진 · 목소리 모델 · 설정 · 학습 파일 · 캐시가 모두 이 폴더 안에만 저장됩니다. 설치 중에 약 8GB 를 내려받고, 모델을 만들면 더 늘어나므로 15GB 이상 여유가 있는 드라이브를 골라 주세요.
ko.DiskSpaceMBLabel=설치 중에 약 8GB 를 더 내려받습니다. 15GB 이상 비어 있는 드라이브를 권합니다.
[Tasks]
Name: "desktopicon"; Description: "바탕 화면에 바로 가기 만들기"; Flags: unchecked
[Files]
Source: "secure-dir.ps1"; Flags: dontcopy
Source: "..\dist\payload\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion
[Icons]
Name: "{autoprograms}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"; Tasks: desktopicon
[Run]
Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked
[UninstallRun]
Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall"
[Code]
{ 설치 폴더 보안은 secure-dir.ps1 (설치 프로그램에 들어 있고 임시 폴더에 풀어서 관리자 권한으로 실행)이 맡는다.
관리자 권한으로 실행되는 것(설치 폴더 루트의 exe, app\, scripts\, apo\, uninstall\)은 관리자만 고칠 수 있고,
일반 사용자는 데이터 폴더(models · training · datasets · config · cache · env · engine · tools)에만 쓴다. }
function SecureDir(const Mode, Dir: String): Integer;
begin
ExtractTemporaryFile('secure-dir.ps1');
if not Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\secure-dir.ps1') + '" -Mode ' + Mode + ' -App "' + Dir + '"',
'', SW_HIDE, ewWaitUntilTerminated, Result) then
Result := -1;
Log('secure-dir ' + Mode + ' exit=' + IntToStr(Result));
end;
function PowerShell(const Args: String; const Show: Integer; var Code: Integer): Boolean;
begin
Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -ExecutionPolicy Bypass ' + Args, ExpandConstant('{app}'), Show, ewWaitUntilTerminated, Code);
end;
function IsEmptyDir(const Dir: String): Boolean;
var
F: TFindRec;
begin
Result := True;
if FindFirst(AddBackslash(Dir) + '*', F) then
try
repeat
if (F.Name <> '.') and (F.Name <> '..') then
begin
Result := False;
Exit;
end;
until not FindNext(F);
finally
FindClose(F);
end;
end;
{ 다른 파일이 들어 있는 폴더에는 설치하지 않는다. 설치 폴더의 권한을 잠그고, 제거할 때 지우기 때문.
이 앱을 이미 설치한 폴더(업데이트)나 비어 있는 · 새 폴더만 받는다. }
function NextButtonClick(CurPageID: Integer): Boolean;
var
Dir: String;
begin
Result := True;
if CurPageID <> wpSelectDir then Exit;
Dir := WizardDirValue;
if DirExists(Dir) and not IsEmptyDir(Dir) and not FileExists(AddBackslash(Dir) + 'uninstall\unins000.exe') then
begin
SuppressibleMsgBox('이 폴더에는 이미 다른 파일이 있습니다.' + #13#10 +
'비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)', mbError, MB_OK, IDOK);
Result := False;
Exit;
end;
{ 상위 폴더가 일반 사용자 소유면 그 사용자가 설치 폴더를 통째로 다른 것으로 바꿔칠 수 있다 }
if SecureDir('CheckParent', Dir) <> 0 then
begin
SuppressibleMsgBox('이 위치의 상위 폴더는 관리자 소유가 아니라서 설치할 수 없습니다.' + #13#10 +
'드라이브 바로 아래(예: C:\VoiceChanger, D:\VoiceChanger)나 Program Files 처럼 관리자가 관리하는 곳을 골라 주세요.', mbError, MB_OK, IDOK);
Result := False;
end;
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
var
Code: Integer;
begin
Result := '';
{ 다시 설치(업데이트)할 때 오디오 엔진이 쥐고 있는 APO 파일을 바꿀 수 있게 잠깐 오디오 서비스를 멈춘다.
설치 뒤 mic-apo.ps1 이 다시 켠다. }
if FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code);
{ 파일을 풀기 전에 설치 폴더를 관리자 소유로 잠근다. 실패하면 설치하지 않는다. }
case SecureDir('Prepare', ExpandConstant('{app}')) of
0: ;
10: Result := '이 폴더에는 이미 다른 파일이 있습니다. 비어 있는 폴더나 새 폴더를 골라 주세요.';
11: Result := '설치 폴더 안에 링크(정션 · 심볼릭 링크)가 있어 안전하게 설치할 수 없습니다. 링크를 지우거나 새 폴더를 골라 주세요.';
else
Result := '설치 폴더의 권한을 잠그지 못했습니다. 다른 폴더를 골라 다시 설치해 주세요.';
end;
if (Result <> '') and FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
end;
procedure CurStepChanged(CurStep: TSetupStep);
var
Code: Integer;
begin
if CurStep <> ssPostInstall then Exit;
{ 데이터 폴더에만 사용자 쓰기 권한을 주고, 관리자 권한으로 실행되는 파일이 잠겼는지 확인한다.
확인이 안 되면 관리자 권한으로 아무것도 실행하지 않는다. }
if SecureDir('Finish', ExpandConstant('{app}')) <> 0 then
begin
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
SuppressibleMsgBox('설치 폴더의 권한을 확인하지 못해 마이크 연결과 엔진 내려받기를 하지 않았습니다.' + #13#10 +
'음성 변환기를 제거한 뒤 다른 폴더(예: C:\VoiceChanger)에 다시 설치해 주세요.', mbError, MB_OK, IDOK);
Exit;
end;
WizardForm.StatusLabel.Caption := '마이크에 변환 모듈을 붙이는 중... (윈도우 소리가 잠깐 끊깁니다)';
if not PowerShell('-File "' + ExpandConstant('{app}\scripts\mic-apo.ps1') + '" -Install -Root "' + ExpandConstant('{app}') + '"', SW_HIDE, Code) or (Code <> 0) then
begin
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
SuppressibleMsgBox('마이크에 변환 모듈을 붙이지 못했습니다. 설치가 끝난 뒤 음성 변환기의 "마이크 다시 연결" 을 눌러 주세요.', mbError, MB_OK, IDOK);
end;
WizardForm.StatusLabel.Caption := 'Python · 변환 엔진 · 기본 모델을 설치 폴더로 내려받는 중... (10~20분, 검은 창에 진행 상황이 나옵니다)';
{ 일반 권한(설치를 시작한 사용자)으로 받는다. 관리자 권한으로 사용자 쓰기 폴더(env · engine)의 코드를 돌리지 않게. }
if not ExecAsOriginalUser(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\install.ps1') + '"',
ExpandConstant('{app}'), SW_SHOWNORMAL, ewWaitUntilTerminated, Code) or (Code <> 0) then
SuppressibleMsgBox('엔진을 내려받지 못했습니다 (인터넷 연결을 확인해 주세요).' + #13#10 +
'설치 폴더의 install.bat 을 실행하면 받은 곳부터 이어서 받습니다.', mbError, MB_OK, IDOK);
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
App: String;
begin
{ 마이크 되돌리기([UninstallRun])와 설치 파일 지우기가 끝난 뒤 }
if CurUninstallStep <> usPostUninstall then Exit;
App := ExpandConstant('{app}');
{ 설치 중에 내려받은 것들 (설치 파일 목록에 없어서 직접 지운다) }
DelTree(App + '\env', True, True, True);
DelTree(App + '\engine', True, True, True);
DelTree(App + '\tools', True, True, True);
DelTree(App + '\cache', True, True, True);
DelTree(App + '\app\__pycache__', True, True, True);
RemoveDir(App + '\app');
{ 사용자가 만든 것은 물어보고 지운다. 조용히 제거할 때는 남겨 둔다 }
{ 앱이 만든 폴더만 지운다. 설치 폴더 자체는 비어 있을 때만 지운다 (RemoveDir 는 빈 폴더만 지움) }
if (not UninstallSilent) and (MsgBox('만든 목소리 모델 · 학습 파일 · 녹음 · 설정도 지울까요?' + #13#10 +
'(models, training, datasets, config 폴더)' + #13#10#13#10 + '"아니요" 를 누르면 남겨 둡니다.', mbConfirmation, MB_YESNO) = IDYES) then
begin
DelTree(App + '\models', True, True, True);
DelTree(App + '\training', True, True, True);
DelTree(App + '\datasets', True, True, True);
DelTree(App + '\config', True, True, True);
end;
RemoveDir(App + '\models');
RemoveDir(App + '\training');
RemoveDir(App + '\datasets');
RemoveDir(App + '\config');
DeleteFile(App + '\apo\mic-apo.log');
RemoveDir(App + '\apo');
RemoveDir(App);
end;

View File

@@ -0,0 +1,14 @@
# 설치 프로그램 빌드 (Windows). scripts/build-release.sh 로 만든 dist\payload 가 있어야 한다.
# powershell -ExecutionPolicy Bypass -File installer\build.ps1 [-Iscc <ISCC.exe 경로>]
# 결과: dist\VoiceChangerSetup.exe
param([string]$Iscc)
$ErrorActionPreference = 'Stop'
$here = Split-Path -Parent $PSScriptRoot
if (-not (Test-Path (Join-Path $here 'dist\payload\VoiceChanger.exe'))) { throw 'dist\payload 가 없습니다. scripts/build-release.sh 를 먼저 실행하세요' }
if (-not $Iscc) {
$Iscc = @("$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe", "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe", "$env:ProgramFiles\Inno Setup 6\ISCC.exe") |
Where-Object { Test-Path $_ } | Select-Object -First 1
}
if (-not $Iscc) { throw 'Inno Setup 6 (https://jrsoftware.org/isdl.php) 를 설치하거나 -Iscc 로 ISCC.exe 경로를 주세요' }
& $Iscc (Join-Path $here 'installer\VoiceChanger.iss')
if ($LASTEXITCODE -ne 0) { throw "ISCC 실패 ($LASTEXITCODE)" }

View File

@@ -0,0 +1,153 @@
# 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행). 종료 코드로 결과를 알린다.
# -Mode CheckParent -App <폴더> 가장 가까운 상위 폴더가 드라이브 루트이거나 관리자 · SYSTEM · TrustedInstaller 소유인지
# 0 = 괜찮음, 20 = 일반 사용자 소유 (그 사용자가 설치 폴더를 통째로 바꿔치기할 수 있음)
# -Mode Prepare -App <폴더> 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 +
# Users 읽기로 잠근다. 업데이트면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다.
# 10 = 다른 파일이 있는 폴더, 11 = 링크(정션 · 심볼릭 링크)가 있음, 12 = 잠그지 못함
# -Mode Finish -App <폴더> 파일을 푼 뒤: 데이터 폴더에만 Users 수정 권한을 주고, 관리자 권한으로 실행되는 파일이
# 관리자 소유이고 일반 사용자가 쓸 수 없는지 확인한다. 13 = 확인 실패
param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App)
$ErrorActionPreference = 'Stop'
$SY = 'S-1-5-18'; $BA = 'S-1-5-32-544'; $BU = 'S-1-5-32-545'
$TI = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
$UserDirs = 'models', 'training', 'datasets', 'config', 'cache', 'env', 'engine', 'tools'
# 쓰기 계열 권한 비트: WriteData · AppendData · WriteEA · DeleteChild · WriteAttributes · Delete · WriteDAC · WriteOwner + GENERIC_ALL/WRITE
$WriteBits = 0x2 -bor 0x4 -bor 0x10 -bor 0x40 -bor 0x100 -bor 0x10000 -bor 0x40000 -bor 0x80000 -bor 0x10000000 -bor 0x40000000
$Sid = [System.Security.Principal.SecurityIdentifier]
$App = [IO.Path]::GetFullPath($App).TrimEnd('\')
function Say($m) { Write-Host "[secure-dir] $m" }
function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 }
# 링크를 따라 들어가지 않고 폴더 안을 모두 훑어, 설치 폴더 밖을 가리키는 첫 링크를 찾는다.
# 안을 가리키는 링크는 괜찮다 (uv 가 tools\python 안에 "cpython-3.12-..." → "cpython-3.12.x-..." 정션을 만듦).
function Link-Target([string]$p) {
$t = @((Get-Item -LiteralPath $p -Force).Target) | Select-Object -First 1
if (-not $t) { return $null }
$t = [string]$t
if ($t.StartsWith('\\?\')) { $t = $t.Substring(4) }
if (-not [IO.Path]::IsPathRooted($t)) { $t = Join-Path (Split-Path -Parent $p) $t }
return [IO.Path]::GetFullPath($t)
}
function Find-Link([string]$dir) {
$stack = New-Object System.Collections.Stack
$stack.Push($dir)
while ($stack.Count) {
foreach ($e in [IO.Directory]::EnumerateFileSystemEntries($stack.Pop())) {
$a = [IO.File]::GetAttributes($e)
if ($a -band [IO.FileAttributes]::ReparsePoint) {
$t = Link-Target $e
if (-not $t -or -not ($t.StartsWith($App + '\', [StringComparison]::OrdinalIgnoreCase))) { return "$e -> $t" }
continue # 안쪽 링크: 따라 들어가지 않음 (가리키는 곳은 따로 훑음)
}
if ($a -band [IO.FileAttributes]::Directory) { $stack.Push($e) }
}
}
return $null
}
function Owner-Sid([string]$p) { (Get-Acl -LiteralPath $p).GetOwner($Sid).Value }
if ($Mode -eq 'CheckParent') {
$p = Split-Path -Parent $App
while ($p -and -not (Test-Path -LiteralPath $p)) { $p = Split-Path -Parent $p }
if (-not $p -or $p -eq [IO.Path]::GetPathRoot($p)) { Say "상위: 드라이브 루트"; exit 0 }
$o = Owner-Sid $p
Say "상위: $p 소유자 $o"
if ($o -in @($BA, $SY, $TI)) { exit 0 }
exit 20
}
if ($Mode -eq 'Prepare') {
$upgrade = Test-Path -LiteralPath (Join-Path $App 'uninstall\unins000.exe')
if (Test-Path -LiteralPath $App) {
if (Is-Link $App) { Say "설치 폴더가 링크: $App"; exit 11 }
if (-not $upgrade -and [IO.Directory]::EnumerateFileSystemEntries($App).GetEnumerator().MoveNext()) { exit 10 }
$link = Find-Link $App
if ($link) { Say "링크 발견: $link"; exit 11 }
}
if ($upgrade) {
# 이전 버전(21b4278)은 설치 폴더 전체를 사용자 쓰기로 두었다. 이전 배포에 들어 있던 실행 부분은 믿지 않고
# 이름을 하나씩 지정해서만 지운다 (새 파일은 곧 다시 풂). 목록에 없는 파일(사용자가 넣어 둔 녹음 등)은 지우지 않고,
# 아래에서 소유자 · 권한만 관리자 쪽으로 정리한다. 제거 기록(unins*.dat)은 제거할 때 관리자 권한으로 쓰이므로 꼭 지운다.
$known = [ordered]@{
'.' = @('VoiceChanger.exe', 'install.bat', 'train.bat', 'examples.bat', 'README.md')
'scripts' = @('install.ps1', 'mic-apo.ps1')
'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'setup_engine.py', 'train.py', 'voice_changer.py')
'launcher' = @('launcher.c')
'apo' = @('VoiceChangerAPO.dll', 'vcapo.cpp', 'vccore.h', 'vcapo.def', 'mic-apo.json', 'mic-apo.log')
'uninstall' = @('unins*.exe', 'unins*.dat', 'unins*.msg')
'app\__pycache__' = @('*.pyc')
}
$n = 0
foreach ($d in $known.Keys) {
$dir = if ($d -eq '.') { $App } else { Join-Path $App $d }
if (-not (Test-Path -LiteralPath $dir -PathType Container)) { continue }
foreach ($pat in $known[$d]) {
Get-ChildItem -LiteralPath $dir -Force -File -Filter $pat | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force; $n++ }
}
}
foreach ($d in 'app\__pycache__', 'app', 'scripts', 'launcher', 'uninstall') { # 비었을 때만
$dir = Join-Path $App $d
if ((Test-Path -LiteralPath $dir) -and -not [IO.Directory]::EnumerateFileSystemEntries($dir).GetEnumerator().MoveNext()) { Remove-Item -LiteralPath $dir -Force }
}
Say "업데이트: 이전 배포 파일 $n 개 정리 (그 밖의 파일은 남김)"
}
New-Item -ItemType Directory -Force -Path $App | Out-Null
$sd = New-Object System.Security.AccessControl.DirectorySecurity
# 소유자 · 그룹 · DACL 만 쓴다 (SACL 까지 쓰면 감사 특권이 필요함)
$sd.SetSecurityDescriptorSddlForm("O:BAG:SYD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)",
[System.Security.AccessControl.AccessControlSections]'Owner, Group, Access')
[IO.Directory]::SetAccessControl($App, $sd)
foreach ($c in Get-ChildItem -LiteralPath $App -Force) {
& icacls $c.FullName /setowner "*$BA" /C /Q | Out-Null
if ($LASTEXITCODE -ne 0) { Say "소유자 변경 실패: $($c.FullName)"; exit 12 }
if ($c.Name -notin $UserDirs) {
# 관리자 쪽 하위 항목(apo\ 백업 등): 전부 관리자 소유, 명시 권한 없이 상속만
& icacls $c.FullName /setowner "*$BA" /T /C /Q | Out-Null
& icacls $c.FullName /reset /T /C /Q | Out-Null
if ($LASTEXITCODE -ne 0) { Say "권한 초기화 실패: $($c.FullName)"; exit 12 }
}
}
$acl = Get-Acl -LiteralPath $App
$rules = @($acl.GetAccessRules($true, $true, $Sid))
$bad = @($rules | ? { $_.IsInherited -or $_.IdentityReference.Value -notin @($SY, $BA, $BU) -or
($_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band $WriteBits)) })
if ($acl.GetOwner($Sid).Value -ne $BA -or -not $acl.AreAccessRulesProtected -or $bad.Count -gt 0) {
Say "잠금 확인 실패: owner=$($acl.GetOwner($Sid).Value) protected=$($acl.AreAccessRulesProtected) bad=$($bad.Count)"
exit 12
}
Say "잠금 완료"
exit 0
}
if ($Mode -eq 'Finish') {
foreach ($d in $UserDirs) {
$p = Join-Path $App $d
if (-not (Test-Path -LiteralPath $p)) { New-Item -ItemType Directory -Path $p | Out-Null }
if (Is-Link $p) { Say "데이터 폴더가 링크: $p"; exit 13 }
$has = @((Get-Acl -LiteralPath $p).GetAccessRules($true, $false, $Sid) | ? {
$_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band 0x2) -and $_.InheritanceFlags -eq 'ContainerInherit, ObjectInherit' })
if (-not $has) {
& icacls $p /grant "*${BU}:(OI)(CI)M" /C /Q | Out-Null
if ($LASTEXITCODE -ne 0) { Say "데이터 폴더 권한 실패: $p"; exit 13 }
}
}
# 관리자 권한으로 실행되거나 읽히는 것: 루트 파일, scripts\ app\ apo\ launcher\ uninstall\ 아래 전부
$items = @(Get-Item -LiteralPath $App -Force) + @(Get-ChildItem -LiteralPath $App -Force -File)
foreach ($d in 'scripts', 'app', 'apo', 'launcher', 'uninstall') {
$p = Join-Path $App $d
if (Test-Path -LiteralPath $p) { $items += Get-Item -LiteralPath $p -Force; $items += @(Get-ChildItem -LiteralPath $p -Recurse -Force) }
}
foreach ($it in $items) {
if (Is-Link $it.FullName) { Say "링크: $($it.FullName)"; exit 13 }
$acl = Get-Acl -LiteralPath $it.FullName
$o = $acl.GetOwner($Sid).Value
$w = @($acl.GetAccessRules($true, $true, $Sid) | ? { $_.AccessControlType -eq 'Allow' -and
$_.IdentityReference.Value -notin @($SY, $BA, $TI) -and ([int]$_.FileSystemRights -band $WriteBits) })
if ($o -notin @($BA, $SY) -or $w.Count -gt 0) { Say "확인 실패: $($it.FullName) owner=$o 쓰기권한=$($w.Count)"; exit 13 }
}
Say "확인 완료: $($items.Count)개"
exit 0
}
throw "알 수 없는 Mode: $Mode"

View 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;
}

View File

View File

@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# 배포 파일을 만든다 (리눅스, mingw).
# dist/payload/ 설치 프로그램에 들어갈 파일 (VoiceChanger.exe · VoiceChangerAPO.dll · 스크립트 · 앱 코드)
# dist/voice-changer-win.zip 같은 내용의 zip (설치 프로그램 없이 풀어서 쓸 때)
# 설치 프로그램(VoiceChangerSetup.exe)은 Windows 의 Inno Setup 으로 만든다: installer/build.ps1
# 엔진 · torch 는 설치할 때 게임PC 에서 받는다.
set -euo pipefail
here="$(cd "$(dirname "$0")/.." && pwd)"
out="${1:-$here/dist}"
pkg="$out/payload"
rm -rf "$pkg"
mkdir -p "$pkg/scripts" "$pkg/models" "$pkg/launcher" "$pkg/app" "$pkg/apo" "$out"
x86_64-w64-mingw32-gcc -O2 -municode -mwindows -finput-charset=UTF-8 -o "$pkg/VoiceChanger.exe" "$here/launcher/launcher.c"
x86_64-w64-mingw32-g++ -O2 -Wall -shared -static -fno-exceptions -fno-rtti -o "$pkg/apo/VoiceChangerAPO.dll" \
"$here/apo/vcapo.cpp" "$here/apo/vcapo.def" -lole32 -luuid -ladvapi32
cp "$here"/*.bat "$here/README.md" "$pkg/"
cp "$here/scripts/install.ps1" "$here/scripts/mic-apo.ps1" "$pkg/scripts/"
cp "$here/launcher/launcher.c" "$pkg/launcher/"
cp "$here/apo/vcapo.cpp" "$here/apo/vccore.h" "$here/apo/vcapo.def" "$pkg/apo/"
cp "$here"/app/*.py "$pkg/app/"
touch "$pkg/models/.gitkeep"
# Windows PowerShell 5.1 은 BOM 이 없는 .ps1 의 한글을 ANSI 로 읽어 스크립트가 깨진다. 줄바꿈도 CRLF 로 맞춘다
for f in "$pkg"/scripts/*.ps1; do
[ "$(head -c 3 "$f" | xxd -p)" = "efbbbf" ] || { echo "BOM 없음: $f" >&2; exit 1; }
done
for f in "$pkg"/scripts/*.ps1 "$pkg"/*.bat; do sed -i 's/\r*$/\r/' "$f"; done
rm -f "$out/voice-changer-win.zip"
(cd "$pkg" && zip -qr "$out/voice-changer-win.zip" .)
echo "$pkg"
echo "$out/voice-changer-win.zip"

View File

@@ -0,0 +1,75 @@
# 음성 변환기 설치: 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] 엔진 있음" }
# 받는 것 · 캐시 · 임시 파일을 모두 이 폴더 안에 둔다 (사용자 폴더 %TEMP% · %LOCALAPPDATA% · 레지스트리에 안 남김)
$Temp = Join-Path $Root "cache\temp"
New-Item -ItemType Directory -Force $Temp | Out-Null
$env:TEMP = $Temp; $env:TMP = $Temp
$env:UV_PYTHON_INSTALL_DIR = Join-Path $Tools "python"
$env:UV_CACHE_DIR = Join-Path $Tools "uv-cache"
$env:UV_PYTHON_BIN_DIR = Join-Path $Tools "python-bin"
$env:UV_TOOL_DIR = Join-Path $Tools "uv-tools"
$env:UV_NO_CONFIG = "1"
$env:PYTHONNOUSERSITE = "1"
if (-not (Test-Path (Join-Path $VenvDir "Scripts\python.exe"))) {
Write-Host "[3/5] Python 3.12 환경 만들기..."
& $Uv python install 3.12 --no-bin --no-registry
if ($LASTEXITCODE -ne 0) { throw "Python 을 받지 못했습니다" }
& $Uv venv --python 3.12 --managed-python --no-python-downloads $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 확인에 실패했습니다" }
# 내려받은 패키지 캐시는 env 에 이미 풀려 있으니 지워서 디스크를 아낀다 (install.bat 을 다시 돌리면 다시 받음)
& $Uv cache clean | Out-Null
Write-Host ""
Write-Host "설치가 끝났습니다. VoiceChanger.exe 로 실행하세요."

View File

@@ -0,0 +1,308 @@
# 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다.
# mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
# mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림
# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
# apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게).
param([switch]$Install, [switch]$Uninstall, [string]$Root)
$ErrorActionPreference = 'Stop'
if (-not $Root) { $Root = Split-Path -Parent $PSScriptRoot }
$Root = (Resolve-Path $Root).Path
# apo/vcapo.cpp 의 CLSID_VoiceChangerAPO 와 같아야 한다
$Clsid = '{6F1C5E2A-3B7D-4C41-9A0E-5D2B8F61C437}'
$Dll = Join-Path $Root 'apo\VoiceChangerAPO.dll'
$Config = Join-Path $Root 'apo'
$BackupFile = Join-Path $Config 'mic-apo-backup.json'
$ListFile = Join-Path $Config 'mic-apo.json' # 앱이 읽는 "모듈을 붙인 마이크" 목록
$OldListFile = Join-Path $Root 'config\mic-apo.json' # 이전 버전(21b4278)의 목록 위치 (설치 · 제거 때 지움)
# 실행 기록은 관리자만 쓸 수 있는 apo\mic-apo.log 에 남긴다 (앱이 실패 이유를 보여 줄 때 읽음)
$LogFile = Join-Path $Config 'mic-apo.log'
function Write-RunLog($m) { try { Add-Content -Path $LogFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $m" -Encoding UTF8 } catch {} }
trap { Write-RunLog ("실패: " + ($_ | Out-String).Trim()); Write-Host "[mic-apo] 실패: $($_.Exception.Message)"; exit 1 }
# 관리자 권한으로 도는 스크립트라 임시 파일(Add-Type 컴파일 결과 등)은 관리자만 쓰는 Windows 임시 폴더에 둔다.
# 앱이 물려준 TEMP(설치 폴더의 cache\temp)는 일반 사용자도 쓸 수 있는 곳이라 쓰지 않는다.
$env:TEMP = Join-Path $env:SystemRoot 'Temp'; $env:TMP = $env:TEMP
Write-RunLog ("시작: " + $(if ($Install) { '-Install' } elseif ($Uninstall) { '-Uninstall' } else { '(없음)' }))
$Capture = 'SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture'
$FX = '{d04e05a6-594b-4fb6-a80d-01af5eed7d1d}'
$SFX = "$FX,5" # PKEY_FX_StreamEffectClsid
$SFX_COMPOSITE = "$FX,13" # PKEY_CompositeFX_StreamEffectClsid (여러 개를 차례로)
$SFX_MODES = '{d3993a3f-99c2-4402-b5ec-a92a0367664b},5' # SFX 가 맡는 처리 모드 (없을 때만 아래 목록을 넣음)
# 녹음 쪽 처리 모드 (ksmedia.h AUDIO_SIGNALPROCESSINGMODE_*): 기본 · 통화(디스코드 등 VoIP) · 음성 · 미디어.
# RAW 는 "처리 없이" 를 요청한 스트림이라 넣지 않는다.
$CAPTURE_MODES = @(
'{C18E2F7E-933D-4965-B7D1-1EEF228D2AF3}', # DEFAULT
'{98951333-B9CD-48B1-A0A3-FF40682D73F7}', # COMMUNICATIONS
'{FC1CFC9B-B9D6-4CFA-B5E0-4BB2166878B2}', # SPEECH
'{4780004E-7133-41D8-8C74-660DADD2C0EE}' # MEDIA
)
$DISABLE_SYSFX = '{1da5d803-d492-4edd-8c23-e0c0ffee7f0e},5' # "오디오 향상 끔" (FxProperties 에 있음)
$DESC = '{a45c254e-df1c-4efd-8020-67d146a850e0},2'
$IFACE = '{b3f8fa53-0004-438e-9003-51a46e139bfc},6'
Add-Type @'
using System;
using System.Runtime.InteropServices;
public static class VcPriv {
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct TP { public int Count; public long Luid; public int Attr; }
[DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenProcessToken(IntPtr h, int acc, out IntPtr tok);
[DllImport("advapi32.dll", SetLastError = true)] static extern bool LookupPrivilegeValue(string sys, string name, out long luid);
[DllImport("advapi32.dll", SetLastError = true)] static extern bool AdjustTokenPrivileges(IntPtr tok, bool all, ref TP np, int len, IntPtr prev, IntPtr rl);
[DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
public static void Enable(string name) {
IntPtr t; OpenProcessToken(GetCurrentProcess(), 0x28, out t);
TP tp = new TP(); tp.Count = 1; tp.Attr = 2; LookupPrivilegeValue(null, name, out tp.Luid);
AdjustTokenPrivileges(t, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
}
}
'@
$HKLM = [Microsoft.Win32.Registry]::LocalMachine
$Admins = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')
$RW = [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree
$Rights = [System.Security.AccessControl.RegistryRights]
function Log($m) { Write-Host "[mic-apo] $m"; Write-RunLog $m }
# MMDevices 의 마이크 키에서 관리자는 값 읽기 · 쓰기만 되고 하위 키는 못 만든다.
# 그래서 값은 그 권한으로만 바꾼다. FxProperties 키가 아예 없는 마이크에서만 잠깐 소유권을 가져와
# 키를 만든 뒤, 그 마이크 키의 보안 설정(SDDL)을 원래대로 바로 되돌린다.
$ValueRights = $Rights::QueryValues -bor $Rights::SetValue -bor $Rights::ReadKey
function Open-Values([string]$sub) { return $HKLM.OpenSubKey($sub, $RW, $ValueRights) }
function New-FxKey([string]$sub) {
[VcPriv]::Enable('SeTakeOwnershipPrivilege'); [VcPriv]::Enable('SeRestorePrivilege')
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::ReadPermissions)
$orig = $k.GetAccessControl('All').GetSecurityDescriptorSddlForm('All'); $k.Close()
try {
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::TakeOwnership)
$acl = New-Object System.Security.AccessControl.RegistrySecurity
$acl.SetOwner($Admins); $k.SetAccessControl($acl); $k.Close()
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::ChangePermissions -bor $Rights::ReadPermissions)
$acl = $k.GetAccessControl()
$acl.AddAccessRule((New-Object System.Security.AccessControl.RegistryAccessRule($Admins, 'CreateSubKey', 'None', 'None', 'Allow')))
$k.SetAccessControl($acl); $k.Close()
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::CreateSubKey -bor $Rights::ReadKey)
$k.CreateSubKey('FxProperties', $RW).Close(); $k.Close()
} finally {
$k = $HKLM.OpenSubKey($sub, $RW, $Rights::ChangePermissions -bor $Rights::TakeOwnership -bor $Rights::ReadPermissions)
$acl = New-Object System.Security.AccessControl.RegistrySecurity
$acl.SetSecurityDescriptorSddlForm($orig)
$k.SetAccessControl($acl); $k.Close()
}
}
function Get-Val($key, [string]$name) {
if (-not $key -or -not ($key.GetValueNames() -contains $name)) { return $null }
return @{ kind = $key.GetValueKind($name).ToString(); data = $key.GetValue($name, $null, 'DoNotExpandEnvironmentNames') }
}
function Set-Val($key, [string]$name, $v) {
if ($null -eq $v) { if ($key.GetValueNames() -contains $name) { $key.DeleteValue($name) }; return }
$data = $v.data
if ($v.kind -eq 'MultiString') { $data = [string[]]@($data) }
if ($v.kind -eq 'Binary') { $data = [byte[]]@($data) }
$key.SetValue($name, $data, [Microsoft.Win32.RegistryValueKind]$v.kind)
}
# 백업 값 검증. 이전 버전 백업(config\, 일반 사용자 쓰기 폴더)은 그대로 믿지 않는다.
# 허용: null, CLSID 문자열, CLSID 목록, 알려진 처리 모드 GUID 목록, DISABLE_SYSFX(0/1). 이 APO 자신의 CLSID 는 "원래 값" 에서 뺀다.
$GuidRe = '^\{[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\}$'
$KNOWN_MODES = $CAPTURE_MODES + @(
'{9E90EA20-B493-4FD1-A1A8-7E1361A956CF}', # RAW
'{B26FEB0D-EC94-477C-9494-D1AB8E753F6E}', # MOVIE
'{9CF2A70B-F377-403B-BD6B-360863E0355C}' # NOTIFICATION
)
function Clean-Val([string]$field, $v) {
if ($null -eq $v) { return @{ ok = $true; v = $null } }
$kind = [string]$v.kind; $data = $v.data
switch ($field) {
'sfx' {
if ($kind -ne 'String' -or [string]$data -notmatch $GuidRe) { break }
if ([string]$data -eq $Clsid) { return @{ ok = $true; v = $null } }
return @{ ok = $true; v = @{ kind = 'String'; data = [string]$data } }
}
'sfx_composite' {
$list = @($data | ForEach-Object { [string]$_ })
if ($kind -ne 'MultiString' -or @($list | Where-Object { $_ -notmatch $GuidRe }).Count) { break }
$list = @($list | Where-Object { $_ -ne $Clsid })
if ($list.Count -eq 0) { return @{ ok = $true; v = $null } }
return @{ ok = $true; v = @{ kind = 'MultiString'; data = [string[]]$list } }
}
'sfx_modes' {
$list = @($data | ForEach-Object { [string]$_ })
if ($kind -ne 'MultiString' -or $list.Count -eq 0 -or @($list | Where-Object { $KNOWN_MODES -notcontains $_ }).Count) { break }
return @{ ok = $true; v = @{ kind = 'MultiString'; data = [string[]]$list } }
}
'disable_sysfx' {
if ($kind -ne 'DWord' -or ($data -ne 0 -and $data -ne 1)) { break }
return @{ ok = $true; v = @{ kind = 'DWord'; data = [int]$data } }
}
}
return @{ ok = $false; v = $null }
}
# 지금 레지스트리 값을 "원래 값" 으로 남길 때. 이전 설치가 넣은 이 APO 흔적은 뺀다.
function Current-Original([string]$sub) {
$fx = $HKLM.OpenSubKey("$sub\FxProperties")
$e = @{}
foreach ($f in @(@('sfx', $SFX), @('sfx_composite', $SFX_COMPOSITE), @('sfx_modes', $SFX_MODES), @('disable_sysfx', $DISABLE_SYSFX))) {
$r = Clean-Val $f[0] (Get-Val $fx $f[1])
$e[$f[0]] = $r.v
}
$cur = Get-Val $fx $SFX
$modes = Get-Val $fx $SFX_MODES
# SFX 가 이 APO 이고 모드가 기본 하나뿐이면 이전 버전이 만든 목록이다
if ($cur -and $cur.data -eq $Clsid -and $modes -and @($modes.data).Count -eq 1 -and @($modes.data)[0] -eq $CAPTURE_MODES[0]) { $e.sfx_modes = $null }
return $e
}
function Load-Backup {
$b = @{}
$src = $BackupFile
$old = Join-Path $Root 'config\mic-apo-backup.json' # 이전 버전(21b4278)의 위치
if (-not (Test-Path $src) -and (Test-Path $old)) { $src = $old; Log "이전 백업을 옮김: $old" }
if (Test-Path $src) {
try { $j = Get-Content $src -Raw -Encoding UTF8 | ConvertFrom-Json } catch { $j = $null; Log "백업을 읽지 못함: $src" }
if ($j) {
foreach ($p in $j.PSObject.Properties) {
if ($p.Name -notmatch $GuidRe -or -not $HKLM.OpenSubKey("$Capture\$($p.Name)")) { Log "백업 항목 무시: $($p.Name)"; continue }
$fallback = Current-Original "$Capture\$($p.Name)"
$e = @{}
foreach ($f in 'sfx', 'sfx_composite', 'sfx_modes', 'disable_sysfx') {
$raw = $p.Value.$f
$in = if ($null -eq $raw) { $null } else { @{ kind = $raw.kind; data = $raw.data } }
$r = Clean-Val $f $in
if ($r.ok) { $e[$f] = $r.v } else { $e[$f] = $fallback[$f]; Log "백업 값 거부($f): $($p.Name)" }
}
$b[$p.Name] = $e
}
}
}
if ($src -eq $old) {
Save-Backup $b
Remove-Item -Force $old -ErrorAction SilentlyContinue
}
return $b
}
function Save-Backup($b) {
New-Item -ItemType Directory -Force $Config | Out-Null
$b | ConvertTo-Json -Depth 6 | Set-Content $BackupFile -Encoding UTF8
}
function Restart-Audio {
# 마이크 설정은 AudioEndpointBuilder 가 들고 있으므로 이것까지 다시 시작해야 새 값을 읽는다
Log '오디오 서비스 다시 시작'
Restart-Service -Name AudioEndpointBuilder -Force
Start-Service -Name Audiosrv
}
function Get-Endpoints {
$root = $HKLM.OpenSubKey($Capture)
foreach ($guid in $root.GetSubKeyNames()) {
$ek = $root.OpenSubKey($guid)
$state = [int]$ek.GetValue('DeviceState', 0)
$pk = $ek.OpenSubKey('Properties')
$desc = if ($pk) { $pk.GetValue($DESC) } else { $null }
$iface = if ($pk) { $pk.GetValue($IFACE) } else { $null }
# 1 = 사용 중, 8 = 뽑혀 있음 (헤드셋을 꽂으면 바로 쓰게 같이 붙인다)
if ($state -eq 1 -or $state -eq 8) { [pscustomobject]@{ guid = $guid; desc = $desc; iface = $iface; state = $state } }
}
}
function Install-Apo {
if (-not (Test-Path $Dll)) { throw "APO 파일이 없습니다: $Dll" }
# audiodg.exe (LOCAL SERVICE) 가 설치 폴더가 어디든 DLL 을 읽을 수 있게
& icacls (Split-Path $Dll) /grant '*S-1-5-19:(OI)(CI)RX' '*S-1-15-2-1:(OI)(CI)RX' /T /Q | Out-Null
$k = $HKLM.CreateSubKey("SOFTWARE\Classes\CLSID\$Clsid")
$k.SetValue('', 'Voice Changer APO'); $k.Close()
$k = $HKLM.CreateSubKey("SOFTWARE\Classes\CLSID\$Clsid\InprocServer32")
$k.SetValue('', $Dll); $k.SetValue('ThreadingModel', 'Both'); $k.Close()
$k = $HKLM.CreateSubKey("SOFTWARE\Classes\AudioEngine\AudioProcessingObjects\$Clsid")
$k.SetValue('FriendlyName', 'Voice Changer'); $k.SetValue('Copyright', 'voice_copy (MIT)')
foreach ($kv in @(@('MajorVersion', 1), @('MinorVersion', 0), @('Flags', 0xd), @('MinInputConnections', 1), @('MaxInputConnections', 1),
@('MinOutputConnections', 1), @('MaxOutputConnections', 1), @('MaxInstances', -1), @('NumAPOInterfaces', 1))) {
$k.SetValue($kv[0], [int]$kv[1], 'DWord')
}
$k.SetValue('APOInterface0', '{FD7F2B29-24D0-4b5c-B177-592C39F9CA10}'); $k.Close()
$bk = Load-Backup
$done = @()
foreach ($ep in Get-Endpoints) {
$sub = "$Capture\$($ep.guid)"
try {
if (-not $bk.ContainsKey($ep.guid)) { # 처음 붙일 때의 값만 남긴다 (다시 실행해도 덮어쓰지 않음)
$bk[$ep.guid] = Current-Original $sub
Save-Backup $bk
}
if (-not $HKLM.OpenSubKey("$sub\FxProperties")) { New-FxKey $sub }
$fx = Open-Values "$sub\FxProperties"
$cur = Get-Val $fx $SFX
$comp = Get-Val $fx $SFX_COMPOSITE
if ($comp) {
# 제조사 효과가 여러 개 있으면 그 뒤에 붙인다 (잡음 제거 등을 거친 소리를 변환)
$list = @($comp.data | Where-Object { $_ -ne $Clsid }) + $Clsid
$fx.SetValue($SFX_COMPOSITE, [string[]]$list, 'MultiString')
} elseif ($cur -and $cur.data -ne $Clsid) {
$fx.SetValue($SFX_COMPOSITE, [string[]]@($cur.data, $Clsid), 'MultiString')
} else {
$fx.SetValue($SFX, $Clsid, 'String')
}
# 드라이버가 원래 갖고 있던 모드 목록은 그대로 둔다 (드라이버 효과가 지원하지 않는 모드를 억지로 켜지 않게).
# 원래 목록이 없었으면(백업이 null) 이 앱이 만든 목록이므로 통화 · 음성 · 미디어 모드까지 넣는다.
# 이전 버전이 넣은 "기본 모드 하나" 목록도 여기서 갱신된다.
$modes = Get-Val $fx $SFX_MODES
if ($null -eq $bk[$ep.guid].sfx_modes -and (-not $modes -or (Compare-Object @($modes.data) $CAPTURE_MODES))) {
$fx.SetValue($SFX_MODES, [string[]]$CAPTURE_MODES, 'MultiString')
}
# 사용자가 "오디오 향상" 을 꺼 두면 APO 가 통째로 빠지므로 켠다 (해제할 때 되돌림)
if ($fx.GetValueNames() -contains $DISABLE_SYSFX) { $fx.DeleteValue($DISABLE_SYSFX) }
$fx.Close()
$done += $ep
Log "연결: $($ep.desc) ($($ep.iface))"
} catch {
Log "연결 못 함: $($ep.desc) ($($ep.iface)) - $($_.Exception.Message)"
}
}
New-Item -ItemType Directory -Force $Config | Out-Null
ConvertTo-Json -InputObject @($done) -Depth 3 | Set-Content $ListFile -Encoding UTF8
Remove-Item -Force $OldListFile -ErrorAction SilentlyContinue
Restart-Audio
if ($done.Count -eq 0) { throw '마이크를 하나도 연결하지 못했습니다' }
}
function Uninstall-Apo {
$bk = Load-Backup
foreach ($guid in @($bk.Keys)) {
$e = $bk[$guid]
$sub = "$Capture\$guid"
try {
$fx = Open-Values "$sub\FxProperties"
if ($fx) {
Set-Val $fx $SFX $e.sfx
Set-Val $fx $SFX_COMPOSITE $e.sfx_composite
Set-Val $fx $SFX_MODES $e.sfx_modes
Set-Val $fx $DISABLE_SYSFX $e.disable_sysfx
$fx.Close()
}
Log "되돌림: $guid"
} catch { Log "되돌리지 못함: $guid - $($_.Exception.Message)" }
}
foreach ($sub in @("SOFTWARE\Classes\AudioEngine\AudioProcessingObjects\$Clsid", "SOFTWARE\Classes\CLSID\$Clsid")) {
if ($HKLM.OpenSubKey($sub)) { $HKLM.DeleteSubKeyTree($sub) }
}
Remove-Item -Force $BackupFile, $ListFile, $OldListFile -ErrorAction SilentlyContinue
Restart-Audio
}
try {
if ($Install) { Install-Apo } elseif ($Uninstall) { Uninstall-Apo } else { throw '-Install 또는 -Uninstall 을 주세요' }
Write-RunLog '끝: 성공'
exit 0
} catch {
Write-RunLog ("실패: " + ($_ | Out-String).Trim())
Write-Host "[mic-apo] 실패: $($_.Exception.Message)"
exit 1
}

View File

@@ -0,0 +1,88 @@
"""변환기(voice_changer.Converter._pump)가 마이크 모듈과 실제로 맞물려 도는지.
APO 는 vccore.h 를 그대로 컴파일한 것(test_mic_bridge.Sim)이고 마이크는 44.1kHz 스테레오다.
엔진 자리에는 부호만 뒤집는 가짜 엔진을 넣어서, 44.1kHz → 48kHz → 엔진 → 44.1kHz 로 바꿔 마이크로
돌려보낸 소리가 끊김 없이 이어지는지(원래 목소리는 새지 않는지) 본다. Applio 엔진 자체는 따로 검증함.
"""
import os
import sys
import tempfile
import threading
import time
import types
import unittest
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE.parent / "app"))
os.environ.setdefault("VC_ROOT", tempfile.mkdtemp())
try:
import soxr # noqa: F401
import tkinter # noqa: F401
except ImportError:
soxr = None
from test_mic_bridge import Sim, build_core # noqa: E402
LIB = build_core()
def fake_engine():
"""rvc.realtime.audio.queue_latest 와 AudioCallbacks.audio 자리."""
mod = types.ModuleType("rvc.realtime.audio")
mod.queue_latest = lambda q, x: None
for name in ("rvc", "rvc.realtime"):
sys.modules.setdefault(name, types.ModuleType(name))
sys.modules["rvc.realtime.audio"] = mod
audio = types.SimpleNamespace(
output_audio_gain=1.0, use_monitor=False, mon_queue=None,
process_data_with_time=lambda x: -x[:, 0], # (N, 1) → (N,), Applio 와 같은 모양
)
return types.SimpleNamespace(audio=audio)
@unittest.skipUnless(LIB and soxr, "C 컴파일러 · soxr · tkinter 필요")
class PumpTest(unittest.TestCase):
def test_44k_mic_roundtrip_through_48k_engine(self):
from voice_changer import Converter
sim = Sim(LIB, rate=44100, ch=2)
b = sim.bridge
b.start("마이크(USB Audio Device)", prefill_ms=60)
conv = Converter()
cb = fake_engine()
t = threading.Thread(target=conv._pump, args=(b, cb, 12000, 48000), daemon=True) # 0.25초 블록
n = 441 # 10ms
xs, ys = [], []
t.start()
try:
for i in range(300): # 3초, 실제 시간으로 흘린다
sim.now += 10
x = 0.3 * np.sin(2 * np.pi * 300 * (np.arange(n) + i * n) / 44100)
xs.append(x)
ys.append(sim.call(1, x, name="마이크(USB Audio Device)"))
time.sleep(0.01)
finally:
conv.halt.set()
t.join(2)
self.assertIsNone(conv.error)
x, y = np.concatenate(xs), np.concatenate(ys)
start = int(np.argmax(np.abs(y) > 1e-4))
self.assertTrue(np.all(np.abs(y[:start]) <= 1e-4), "변환된 소리가 오기 전에 원래 목소리가 샘")
self.assertLess(start / 44100, 0.6)
seg = y[start + 2000:]
# 지연 D 를 찾아 y[t] ≈ -x[t-D] 인지 (리샘플 두 번의 오차만 남아야 함)
best = max(range(0, start + 2000), key=lambda d: -np.abs(seg[:4000] + x[start + 2000 - d:start + 6000 - d]).mean())
ref = -x[start + 2000 - best: start + 2000 - best + len(seg)]
err = np.abs(seg - ref)
self.assertLess(float(err.mean()), 0.01)
self.assertEqual(int(b.h.underruns), 0, "중간에 끊김")
self.assertEqual(b.rate, 44100)
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,63 @@
"""KSS 예시 데이터 준비가 중간에 끊긴 뒤 다시 실행해도 목표 길이만큼 다시 뽑는지 (pyarrow · soundfile 필요)."""
import io
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app"))
try:
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import soundfile as sf
except ImportError: # 엔진 환경 밖
pa = None
import examples # noqa: E402
@unittest.skipIf(pa is None, "pyarrow/soundfile 없음")
class KssResumeTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
root = Path(self.tmp.name)
clips = []
for i in range(10): # 1초짜리 10개
buf = io.BytesIO()
sf.write(buf, np.full(44100, 0.01 * (i + 1), dtype="float32"), 44100, format="WAV")
clips.append({"bytes": buf.getvalue(), "path": None})
self.parquet = root / "kss.parquet"
pq.write_table(pa.table({"audio": clips}), self.parquet)
self.old = (examples.DATASETS, examples._download)
examples.DATASETS = root / "datasets"
examples._download = lambda url, dst: self.parquet
def tearDown(self):
examples.DATASETS, examples._download = self.old
self.tmp.cleanup()
def wavs(self, out):
return sorted(p.name for p in out.glob("*.wav"))
def test_interrupted_extract_is_redone_to_target(self):
out = examples.DATASETS / "example_kss" / "raw"
out.mkdir(parents=True)
sf.write(out / "kss_00001.wav", np.zeros(44100, dtype="float32"), 44100) # 끊긴 흔적: 파일 1개, 표식 없음
got = examples.prepare_kss(5 / 60)
self.assertEqual(len(self.wavs(got)), 5)
self.assertEqual(sf.info(str(got / "kss_00001.wav")).frames, 44100)
self.assertAlmostEqual(float(sf.read(str(got / "kss_00001.wav"))[0][0]), 0.01, places=3) # 새로 뽑은 내용
# 끝까지 뽑은 뒤에는 다시 뽑지 않는다
mtime = (got / "kss_00003.wav").stat().st_mtime_ns
examples.prepare_kss(5 / 60)
self.assertEqual((got / "kss_00003.wav").stat().st_mtime_ns, mtime)
# 더 긴 길이를 달라면 다시 뽑는다
self.assertEqual(len(self.wavs(examples.prepare_kss(8 / 60))), 8)
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,158 @@
"""APO(apo/vccore.h, C) 와 변환기(app/mic_bridge.py, 파이썬)가 같은 공유 메모리로 맞물려 도는지.
vccore.h 를 그대로 공유 라이브러리로 컴파일해서, audiodg 가 10ms 마다 부르는 것처럼 흉내 낸다.
gcc 가 없으면 건너뛴다.
"""
import ctypes
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(HERE / "app"))
import mic_bridge as mb # noqa: E402
SHIM = r"""
#include "vccore.h"
#include <stdlib.h>
void *inst_new(uint32_t id, const vc_wchar *name) {
vc_inst *s = calloc(1, sizeof(vc_inst)); s->id = id;
for (unsigned i = 0; i < VC_NAME - 1 && name[i]; i++) s->name[i] = name[i];
return s;
}
void init_header(void *shm) { vc_init_header((vc_header *)shm); }
void process(void *st, void *shm, float *io, uint32_t frames, uint32_t ch, uint32_t rate, int64_t now) {
vc_process((vc_inst *)st, (vc_header *)shm, io, frames, ch, rate, now);
}
"""
MIC = "마이크(USB Audio Device)"
def build_core():
cc = shutil.which("gcc") or shutil.which("cc")
if not cc:
return None
d = Path(tempfile.mkdtemp())
(d / "shim.c").write_text(SHIM)
so = d / "core.so"
subprocess.run([cc, "-O2", "-shared", "-fPIC", f"-I{HERE / 'apo'}", "-o", str(so), str(d / "shim.c")], check=True)
lib = ctypes.CDLL(str(so))
lib.inst_new.restype = ctypes.c_void_p
lib.inst_new.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
lib.init_header.argtypes = [ctypes.c_void_p]
lib.process.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_int64]
return lib
class Sim:
"""audiodg 흉내: 10ms 마다 APO 인스턴스를 부르고, 시계는 테스트가 돌린다."""
def __init__(self, lib, rate=48000, ch=2):
self.lib, self.rate, self.ch = lib, rate, ch
self.buf = (ctypes.c_char * mb.SIZE)()
lib.init_header(ctypes.addressof(self.buf))
self.now = 1000
self.bridge = mb.Bridge(self.buf, clock=lambda: self.now)
self.insts = {}
def inst(self, iid, name=MIC):
if iid not in self.insts:
arr = (ctypes.c_uint16 * mb.NAME_LEN)(*mb._utf16(name))
self.insts[iid] = (self.lib.inst_new(iid, arr), arr)
return self.insts[iid][0]
def call(self, iid, mic: np.ndarray, name=MIC) -> np.ndarray:
"""mic: 모노 원래 소리 (한 번 부를 분량). 돌려주는 값: 앱이 받는 첫 채널."""
io = np.repeat(mic.astype(np.float32), self.ch).copy()
self.lib.process(self.inst(iid, name), ctypes.addressof(self.buf), io.ctypes.data, len(mic), self.ch, self.rate, self.now)
return io[:: self.ch].copy()
@unittest.skipUnless(build_core(), "C 컴파일러 없음")
class MicBridgeTest(unittest.TestCase):
def setUp(self):
self.sim = Sim(build_core())
self.n = self.sim.rate // 100 # 10ms
def voice(self, i):
t = (np.arange(self.n) + i * self.n) / self.sim.rate
return 0.3 * np.cos(2 * np.pi * 150 * t)
def test_off_passes_real_voice(self):
out = self.sim.call(1, self.voice(0))
np.testing.assert_allclose(out, self.voice(0), atol=1e-6)
self.assertEqual(self.sim.bridge.endpoints(), [MIC])
def test_on_sends_converted_voice_and_never_leaks_real_voice(self):
s, b = self.sim, self.sim.bridge
b.start(MIC, prefill_ms=60)
block = s.rate // 4 # 앱은 0.25초씩 모아 바꾼다
got, pending = [], np.zeros(0, np.float32)
for i in range(300): # 3초
s.now += 10
out = s.call(1, self.voice(i))
got.append(out)
b.beat()
pending = np.concatenate([pending, b.read(s.rate)])
while len(pending) >= block: # "변환": 부호를 뒤집어 원래 소리와 구별되게
b.write(-pending[:block])
pending = pending[block:]
y = np.concatenate(got)
x = np.concatenate([self.voice(i) for i in range(300)])
start = np.argmax(np.abs(y) > 1e-6)
# 변환된 소리가 오기 전에는 무음 (원래 목소리가 새지 않음)
self.assertTrue(np.all(y[:start] == 0))
self.assertGreaterEqual(start, block)
# 그 뒤로는 끊김 없이 변환된 소리 = 원래 소리를 일정하게(D) 늦춘 것의 부호 반대
D = next(d for d in range(start + 1) if np.allclose(y[start:start + 1000], -x[start - d:start - d + 1000], atol=1e-6))
np.testing.assert_allclose(y[start:], -x[start - D: len(y) - D], atol=1e-6)
self.assertLess(D / s.rate, 0.25 + 0.01 + 0.06 + 0.02) # 블록 + 첫 10ms + 여유 + 시계 오차
self.assertEqual(s.bridge.h.underruns, 0)
self.assertEqual(b.rate, s.rate)
def test_only_target_mic_and_one_writer(self):
s, b = self.sim, self.sim.bridge
b.start(MIC)
for i in range(20):
s.now += 10
s.call(1, self.voice(i))
s.call(2, self.voice(i)) # 같은 마이크를 다른 앱(통신 모드 등)이 쓰는 두 번째 인스턴스
other = s.call(3, self.voice(i), name="마이크(Webcam)")
np.testing.assert_allclose(other, self.voice(i), atol=1e-6) # 다른 마이크는 그대로
b.beat()
self.assertEqual(int(b.h.in_w), 20 * self.n) # 입력은 한 인스턴스만 씀 (두 번 쓰면 40)
self.assertEqual(int(b.h.owner), 1)
def test_app_gone_returns_to_real_voice(self):
s, b = self.sim, self.sim.bridge
b.start(MIC)
s.now += 10
self.assertTrue(np.all(s.call(1, self.voice(0)) == 0))
s.now += 2000 # 변환기가 죽어서 신호가 끊김
np.testing.assert_allclose(s.call(1, self.voice(1)), self.voice(1), atol=1e-6)
self.assertEqual(int(b.h.owner), 0)
def test_underrun_is_silence_then_recovers(self):
s, b = self.sim, self.sim.bridge
b.start(MIC, prefill_ms=0)
s.now += 10
s.call(1, self.voice(0))
b.read(s.rate)
b.write(np.full(self.n // 2, 0.5, np.float32)) # 반 블록만 줌
s.now += 10
out = s.call(1, self.voice(1))
self.assertTrue(np.allclose(out[: self.n // 2], 0.5) and np.all(out[self.n // 2:] == 0))
self.assertEqual(int(b.h.underruns), 1)
b.write(np.full(self.n, 0.25, np.float32))
s.now += 10
self.assertTrue(np.allclose(s.call(1, self.voice(2)), 0.25))
if __name__ == "__main__":
unittest.main()

View 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()

View File

@@ -0,0 +1,72 @@
"""'마이크 다시 연결' 이 관리자 PowerShell 에 넘기는 인자가 공백 · 한글 · 작은따옴표 · 드라이브 루트 경로에서도 깨지지 않는지."""
import os
import sys
import tempfile
import unittest
from pathlib import Path, PureWindowsPath
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app"))
os.environ.setdefault("VC_ROOT", tempfile.mkdtemp())
try:
import tkinter # noqa: F401 (voice_changer 가 불러옴)
except ImportError:
tkinter = None
def split_windows_args(s: str) -> list:
"""CommandLineToArgvW 규칙 (백슬래시 + 따옴표 처리 포함)."""
args, cur, i, quoted, has = [], [], 0, False, False
while i < len(s):
c = s[i]
if c == "\\":
n = 0
while i < len(s) and s[i] == "\\":
n += 1
i += 1
if i < len(s) and s[i] == '"':
cur.append("\\" * (n // 2))
if n % 2:
cur.append('"')
i += 1
has = True
continue
cur.append("\\" * n)
has = True
continue
if c == '"':
quoted = not quoted
has = True
elif c in " \t" and not quoted:
if has:
args.append("".join(cur))
cur, has = [], False
else:
cur.append(c)
has = True
i += 1
if has:
args.append("".join(cur))
return args
@unittest.skipUnless(tkinter, "tkinter 없음")
class ReconnectParamsTest(unittest.TestCase):
def test_korean_space_quote_path(self):
from voice_changer import reconnect_params
root = PureWindowsPath(r"C:\음성 변환기 테스트\it's here")
args = split_windows_args(reconnect_params(root))
self.assertEqual(args, ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
r"C:\음성 변환기 테스트\it's here\scripts\mic-apo.ps1", "-Install", "-Root", r"C:\음성 변환기 테스트\it's here"])
def test_drive_root(self):
from voice_changer import reconnect_params
args = split_windows_args(reconnect_params(PureWindowsPath("D:\\")))
self.assertEqual(args[4], r"D:\scripts\mic-apo.ps1")
self.assertEqual(args[-1], "D:\\.") # 닫는 따옴표가 \ 에 먹히지 않음
if __name__ == "__main__":
unittest.main()

12
voice-changer/train.bat Normal file
View 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