Files
game_voice_recorder/app/src/renderer/mock-gvr.ts
EJClaw 5f04ccdd4e M5: 포터블 exe 앱 (트레이·설정 창·첫 실행 마법사) + M6 사전 기능
- app/src/main: Electron 메인(트레이 상태 아이콘, 설정 창, 단일 실행, DPAPI safeStorage, 스모크 모드), IPC(window.gvr), 파인튜닝 관리
- app/src/renderer: 설정 8개 탭 + 5단계 첫 실행 마법사 (React)
- electron-builder: GameVoiceRecorder.exe, zip(폴더 포터블) + 단일 exe 포터블, 워커·리소스 포함
- 사전: 사이트에서 단어·교정 규칙 추가/삭제(/api/dictionary), 게임 패치 이름 자동 추가, 묶음별 중복 허용 + DB 마이그레이션
- 사이트 서버: 종료 시 WebSocket 먼저 끊기(재시작 멈춤 수정) + 재연결 테스트
- scripts/finetune-e2e.mts, stt-eval.mts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 02:16:08 +09:00

509 lines
21 KiB
TypeScript

// 브라우저 개발/스크린샷용 가짜 GvrApi. window.gvr 가 없을 때만 쓴다.
// URL 옵션: ?first=1 (첫 실행 · 마법사), ?nogpu=1 (GPU 없음), ?empty=1 (봇 토큰 없음), ?dl=0.6 (다운로드 시작 위치 비율)
import type { User } from '@gvr/shared';
import type { DiagItem } from '../core/diagnostics';
import type { Settings } from '../core/settings';
import type { AppState, DownloadProgress, FinetuneStatus, GvrApi, ModelsInfo } from '../main/api-types';
import { MODEL_META } from './models-meta';
import { deepMerge, sleep } from './util';
const MB = 1024 * 1024;
function defaults(): Settings {
return {
version: 1,
firstRunDone: false,
discord: {
guildId: null,
followUserId: null,
followEnabled: true,
commandsEnabled: true,
ttsEnabled: true,
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
},
games: { valorant: true, lol: true, lolChatOcr: true, lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 }, lolLogsDir: null },
stt: {
realtimeModel: 'large-v3-turbo',
preciseModel: 'large-v3',
device: 'cuda',
computeType: 'float16',
modelsDir: null,
reprocessAfterMatch: true,
gameVramReserveMb: 3072,
},
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
dictionary: {
packs: { valorant: true, valorant_callouts: true, lol: true, lol_skills: true, game: true, daily: true, university: true, slang20s: true },
applySiteCorrections: true,
},
storage: { audioDir: null, retentionDays: 7 },
site: { serverUrl: 'https://gvr.tkrmagid.kr', deviceId: null, deviceName: 'GAME-PC' },
general: { autoStart: false, sfx: true },
finetune: { schedule: 'off', activeModel: null, previousModel: null },
};
}
/** 0.6초짜리 "띵-동" WAV (미리듣기 대용) */
function beepWav(): string {
const rate = 16000;
const n = Math.floor(rate * 0.6);
const buf = new DataView(new ArrayBuffer(44 + n * 2));
const str = (o: number, s: string) => [...s].forEach((c, i) => buf.setUint8(o + i, c.charCodeAt(0)));
str(0, 'RIFF');
buf.setUint32(4, 36 + n * 2, true);
str(8, 'WAVEfmt ');
buf.setUint32(16, 16, true);
buf.setUint16(20, 1, true);
buf.setUint16(22, 1, true);
buf.setUint32(24, rate, true);
buf.setUint32(28, rate * 2, true);
buf.setUint16(32, 2, true);
buf.setUint16(34, 16, true);
str(36, 'data');
buf.setUint32(40, n * 2, true);
for (let i = 0; i < n; i++) {
const f = i < n / 2 ? 880 : 660;
const env = Math.sin((Math.PI * (i % (n / 2))) / (n / 2));
buf.setInt16(44 + i * 2, Math.sin((2 * Math.PI * f * i) / rate) * 9000 * env, true);
}
let bin = '';
const bytes = new Uint8Array(buf.buffer);
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
return 'data:audio/wav;base64,' + btoa(bin);
}
export function createMockGvr(): GvrApi {
const q = new URLSearchParams(location.search);
const first = q.has('first');
const noToken = first || q.has('empty');
const noGpu = q.has('nogpu');
const dlStart = Math.min(0.95, Math.max(0, Number(q.get('dl') ?? 0) || 0));
const now = Date.now();
const settings = defaults();
settings.firstRunDone = !first;
if (!noToken) {
settings.discord.guildId = 'g1';
settings.discord.followUserId = 'u1';
settings.site.deviceId = 'dev_8f2c';
}
const state: AppState = {
version: '1.0.0',
dataDir: 'D:\\겜녹이\\GVR-Data',
portable: true,
settings,
secrets: { botToken: !noToken, riotApiKey: false, deviceKey: !noToken },
secretCodec: 'dpapi',
bot: noToken
? { status: 'off', error: null, user: null, guild: null, guilds: [], recording: { active: false, channel: null, channelId: null, since: null, participants: [], reason: null } }
: {
status: 'ready',
error: null,
user: { id: 'b1', name: '겜녹이#4821', avatar: null },
guild: { id: 'g1', name: '우리 겜방', icon: null },
guilds: [{ id: 'g1', name: '우리 겜방' }],
recording: { active: true, channel: '🎮 발로란트', channelId: 'c1', since: now - 23 * 60000, participants: ['민준', '서연', '지호'], reason: 'follow' },
},
worker: { ready: true, lastError: null },
stt: {
worker: 'ready',
slots: { realtime: { model: 'large-v3-turbo', state: first ? 'missing' : 'loaded' }, precise: { model: 'large-v3', state: 'empty' } },
queue: 0,
processing: null,
device: 'cuda:0',
lastError: null,
},
relay: noToken
? { state: 'off', error: null, since: null, serverUrl: null }
: { state: 'online', error: null, since: now - 3600000, serverUrl: 'https://gvr.tkrmagid.kr' },
games: {
valorant: { connected: true, inMatch: false, detail: 'Riot Client 연결됨 · 대기실' },
lol: { connected: false, inMatch: false, detail: '클라이언트 꺼짐' },
},
counts: { utterances: 1824, matches: 37 },
excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }],
autoStart: false,
};
const models: ModelsInfo = {
models: Object.entries(MODEL_META).map(([name, m]) => ({
name,
repo: name,
size_mb: m.sizeMb,
installed: !first && name === 'large-v3-turbo',
})),
cuda_runtime: { installed: !first, size_mb: 1210 },
};
const users: User[] = [
{ id: 'u1', name: '민준', color: '#3987e5', avatar: null, excluded: false, riot: [{ puuid: 'p1', riotId: '민준#KR1' }] },
{ id: 'u2', name: '서연', color: '#e5743f', avatar: null, excluded: false, riot: [{ puuid: 'p2', riotId: '서연이#0505' }, { puuid: 'p2b', riotId: '서연부캐#KR2' }] },
{ id: 'u3', name: '지호', color: '#1fb383', avatar: null, excluded: false, riot: [] },
{ id: 'u4', name: '현우', color: '#c98500', avatar: null, excluded: true, riot: [{ puuid: 'p4', riotId: 'HW#7777' }] },
];
let dictId = 100;
const dict = {
labels: { site: '사이트 교정', user: '사용자 단어', valorant: '발로란트', lol: '리그 오브 레전드' } as Record<string, string>,
packs: [
{ key: 'valorant', label: '발로란트', count: 288 },
{ key: 'valorant_callouts', label: '발로란트 콜아웃', count: 101 },
{ key: 'lol', label: '리그 오브 레전드', count: 412 },
{ key: 'lol_skills', label: '롤 스킬 이름', count: 850 },
{ key: 'game', label: '게임 공통', count: 104 },
{ key: 'daily', label: '일상', count: 93 },
{ key: 'university', label: '대학생', count: 76 },
{ key: 'slang20s', label: '20대 말투', count: 69 },
],
entries: [
{ id: 1, word: '레이즈', from: '레이저', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: true, hits: 41 },
{ id: 2, word: 'B 사이트', from: '비 싸이트', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: true, hits: 17 },
{ id: 3, word: '제트', from: '젯트', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: true, hits: 9 },
{ id: 4, word: '바론', from: '바롱', kind: 'correction' as const, pack: 'corrections', source: 'builtin', enabled: false, hits: 0 },
{ id: 5, word: '민준', from: '민중', kind: 'correction' as const, pack: 'site', source: 'site', enabled: true, hits: 12 },
{ id: 6, word: '서연이', from: '서여니', kind: 'correction' as const, pack: 'site', source: 'site', enabled: true, hits: 5 },
{ id: 7, word: '한타', from: '한따', kind: 'correction' as const, pack: 'user', source: 'user', enabled: true, hits: 3 },
{ id: 8, word: '민준', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
{ id: 9, word: '서연이', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
{ id: 10, word: '헤드 원탭', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
{ id: 11, word: '조별과제', from: null, kind: 'hotword' as const, pack: 'user', source: 'user', enabled: true, hits: 0 },
],
};
const ft: FinetuneStatus = first
? { toolsInstalled: false, installing: false, running: false, stage: null, step: null, total: null, samples: 0, lastResult: null, activeModel: null, previousModel: null, log: [] }
: {
toolsInstalled: true,
installing: false,
running: false,
stage: null,
step: null,
total: null,
samples: 342,
lastResult: { cer_before: 0.142, cer_after: 0.097, adopt: true, model: 'turbo-ft-1012', at: now - 2 * 86400000 },
activeModel: 'turbo-ft-1012',
previousModel: 'large-v3-turbo',
log: [
'[03:00:02] 학습 데이터 342문장 (교정 118 + 합성 224)',
'[03:00:40] LoRA r=32 · lr 1e-4 · 3 epoch',
'[03:41:15] 검증 CER 14.2% → 9.7%',
'[03:43:02] CTranslate2 변환 완료 → turbo-ft-1012',
'[03:43:03] 새 모델 채택 (이전 모델 보관)',
],
};
const listeners = new Set<(s: AppState) => void>();
const progressL = new Set<(p: DownloadProgress) => void>();
const diagL = new Set<(it: DiagItem) => void>();
const emit = () => {
const snap = structuredClone(state);
listeners.forEach((l) => l(snap));
};
// 녹음 참가자/대기열이 조금씩 바뀌는 흉내
setInterval(() => {
state.stt.queue = Math.random() < 0.7 ? 0 : Math.floor(Math.random() * 3);
emit();
}, 4000);
const api: GvrApi = {
async getState() {
await sleep(80);
return structuredClone(state);
},
onState(cb) {
listeners.add(cb);
return () => listeners.delete(cb);
},
async updateSettings(patch) {
state.settings = deepMerge(state.settings, patch);
emit();
return structuredClone(state.settings);
},
async setSecret(key, value) {
await sleep(150);
state.secrets[key] = !!value;
emit();
},
async testBotToken(token) {
await sleep(900);
if (token !== undefined && token.length < 20) return { ok: false, error: '토큰이 올바르지 않습니다 (401 Unauthorized)' };
if (token === undefined && !state.secrets.botToken) return { ok: false, error: '저장된 토큰이 없습니다' };
return {
ok: true,
bot: { id: 'b1', name: '겜녹이#4821', avatar: null },
guilds: [
{ id: 'g1', name: '우리 겜방' },
{ id: 'g2', name: '과제 스터디' },
],
};
},
async restartBot() {
state.bot.status = 'connecting';
emit();
await sleep(900);
state.bot = {
...state.bot,
status: 'ready',
error: null,
user: { id: 'b1', name: '겜녹이#4821', avatar: null },
guilds: [
{ id: 'g1', name: '우리 겜방' },
{ id: 'g2', name: '과제 스터디' },
],
guild: state.settings.discord.guildId === 'g2' ? { id: 'g2', name: '과제 스터디', icon: null } : { id: 'g1', name: '우리 겜방', icon: null },
};
emit();
return { ok: true };
},
async guildMembers() {
await sleep(300);
return [
{ id: 'u1', name: '민준', avatar: null, bot: false },
{ id: 'u2', name: '서연', avatar: null, bot: false },
{ id: 'u3', name: '지호', avatar: null, bot: false },
{ id: 'u4', name: '현우', avatar: null, bot: false },
{ id: 'b1', name: '겜녹이', avatar: null, bot: true },
{ id: 'b2', name: 'MEE6', avatar: null, bot: true },
];
},
async previewTts() {
await sleep(500);
return { ok: true, dataUrl: beepWav() };
},
async gpuInfo() {
await sleep(250);
if (noGpu) return null;
return {
gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070 Ti', vram_total_mb: 16303, vram_used_mb: 1180, driver: '581.42', cuda_driver: '13.0', compute_capability: '12.0' }],
recommend: {
realtime: 'large-v3-turbo',
precise: 'large-v3',
compute_type: 'float16',
budget_mb: 13231,
reason: 'VRAM 16GB에서 게임 예약 3GB를 빼도 실시간·정밀 모델을 함께 둘 수 있습니다',
supported: true,
warning: null,
precise_after_match: true,
},
};
},
async models() {
await sleep(150);
return structuredClone(models);
},
async download(target, name) {
const key = target === 'cuda_runtime' ? 'cuda_runtime' : `model:${name}`;
const total = target === 'cuda_runtime' ? 1210 : (models.models.find((m) => m.name === name)?.size_mb ?? 1000);
let done = total * dlStart;
while (done < total) {
await sleep(250);
const speed = 34 + Math.random() * 8;
done = Math.min(total, done + speed * 0.25);
const p: DownloadProgress = { key, done_mb: done, total_mb: total, speed_mbps: speed, eta_s: (total - done) / speed, state: 'running', stage: target === 'cuda_runtime' ? 'cuBLAS · cuDNN' : 'model.bin' };
progressL.forEach((l) => l(p));
}
if (target === 'cuda_runtime') models.cuda_runtime.installed = true;
else {
const m = models.models.find((x) => x.name === name);
if (m) m.installed = true;
}
progressL.forEach((l) => l({ key, done_mb: total, total_mb: total, state: 'done' }));
return { ok: true };
},
onProgress(cb) {
progressL.add(cb);
return () => progressL.delete(cb);
},
async deleteModel(name) {
await sleep(300);
const m = models.models.find((x) => x.name === name);
if (m) m.installed = false;
return { ok: true };
},
async applyModels() {
state.stt.slots.realtime = { model: state.settings.stt.realtimeModel, state: 'loading' };
emit();
await sleep(1200);
state.stt.slots.realtime.state = 'loaded';
state.stt.slots.precise = { model: state.settings.stt.preciseModel, state: 'empty' };
emit();
},
async chooseFolder(_title, defaultPath) {
await sleep(200);
return defaultPath ? defaultPath.replace(/[^\\]*$/, '') + '새 폴더' : 'D:\\GameVoiceRecorder\\models';
},
async registerDevice(code) {
await sleep(800);
if (code.trim().length < 6) return { ok: false, error: '코드가 맞지 않거나 만료되었습니다' };
state.settings.site.deviceId = 'dev_' + Math.random().toString(16).slice(2, 6);
state.secrets.deviceKey = true;
state.relay = { state: 'connecting', error: null, since: null, serverUrl: state.settings.site.serverUrl };
emit();
setTimeout(() => {
state.relay = { state: 'online', error: null, since: Date.now(), serverUrl: state.settings.site.serverUrl };
emit();
}, 900);
return { ok: true };
},
async unregisterDevice() {
await sleep(300);
state.settings.site.deviceId = null;
state.secrets.deviceKey = false;
state.relay = { state: 'off', error: null, since: null, serverUrl: null };
emit();
},
async runDiagnostics() {
const items: DiagItem[] = [
{ id: 'os', label: '운영체제', ok: true, detail: 'Windows 11 Pro 24H2 (x64)' },
{ id: 'gpu', label: 'GPU', ok: !noGpu, detail: noGpu ? 'NVIDIA GPU를 찾지 못했습니다' : 'NVIDIA GeForce RTX 5070 Ti · VRAM 16GB · 드라이버 581.42' },
{ id: 'cuda', label: 'CUDA 런타임', ok: models.cuda_runtime.installed, detail: models.cuda_runtime.installed ? 'cuBLAS 12.8 · cuDNN 9.5 로드됨' : '설치되지 않음 (STT 모델 탭에서 다운로드)' },
{ id: 'worker', label: 'STT 엔진', ok: true, detail: 'gvr-worker 1.0.0 · faster-whisper 1.2 · CTranslate2 4.6' },
{ id: 'stt', label: 'STT 속도', ok: true, detail: 'large-v3-turbo · 5초 음성 0.41초 (RTF 0.08)' },
{ id: 'discord', label: '디스코드 봇', ok: state.bot.status === 'ready', detail: state.bot.status === 'ready' ? '겜녹이#4821 · 음성 · 슬래시 명령 권한 정상' : '봇이 연결되지 않았습니다' },
{ id: 'tts', label: 'TTS 안내 음성', ok: true, detail: 'Edge TTS 응답 0.6초' },
{ id: 'valorant', label: '발로란트 로컬 API', ok: true, detail: 'Riot Client 연결됨 (lockfile)' },
{ id: 'lol', label: '롤 Live Client API', ok: null, detail: '게임이 꺼져 있어 확인할 수 없습니다' },
{ id: 'ocr', label: '롤 채팅 OCR', ok: null, detail: '게임이 꺼져 있어 확인할 수 없습니다' },
{ id: 'relay', label: '사이트 서버', ok: state.relay.state === 'online', detail: state.relay.state === 'online' ? 'gvr.tkrmagid.kr 연결됨 · 왕복 38ms' : '등록되지 않음' },
{ id: 'disk', label: '저장 공간', ok: true, detail: 'D: 여유 412GB' },
];
const out: DiagItem[] = [];
for (const it of items) {
await sleep(280);
out.push(it);
diagL.forEach((l) => l(it));
}
return out;
},
onDiag(cb) {
diagL.add(cb);
return () => diagL.delete(cb);
},
async storageUsage() {
await sleep(200);
return { audioBytes: 412 * MB, trainingBytes: 96 * MB, dbBytes: 38 * MB, modelsBytes: 4.6 * 1024 * MB, freeBytes: 412 * 1024 * MB };
},
async runRetention() {
await sleep(900);
return { deleted: 37, freedBytes: 52 * MB };
},
async users() {
await sleep(150);
return structuredClone(users);
},
async setRiotIds(userId, riotIds) {
await sleep(150);
const u = users.find((x) => x.id === userId);
if (u) u.riot = riotIds.map((r, i) => ({ puuid: `${userId}-${i}`, riotId: r }));
},
async setExcluded(userId, excluded) {
const u = users.find((x) => x.id === userId);
if (u) u.excluded = excluded;
},
async dictionary() {
await sleep(150);
return structuredClone(dict);
},
async addWord(word) {
dict.entries.push({ id: ++dictId, word, from: null, kind: 'hotword', pack: 'user', source: 'user', enabled: true, hits: 0 });
},
async addCorrection(from, to) {
dict.entries.push({ id: ++dictId, word: to, from, kind: 'correction', pack: 'user', source: 'user', enabled: true, hits: 0 });
},
async deleteDict(id) {
dict.entries = dict.entries.filter((e) => e.id !== id);
},
async setDictEnabled(id, enabled) {
const e = dict.entries.find((x) => x.id === id);
if (e) e.enabled = enabled;
},
async finetuneStatus() {
return structuredClone(ft);
},
async finetuneInstall() {
ft.installing = true;
ft.log.push('[설치] PyTorch · PEFT 내려받는 중');
setTimeout(() => {
ft.installing = false;
ft.toolsInstalled = true;
ft.log.push('[설치] 완료');
}, 4000);
return { ok: true };
},
async finetuneStart() {
if (ft.samples < 50) return { ok: false, error: '학습 문장이 부족합니다 (최소 50문장)' };
ft.running = true;
ft.stage = '학습';
ft.step = 0;
ft.total = 300;
ft.log.push('[학습] 시작');
const t = setInterval(() => {
if (!ft.running) return clearInterval(t);
ft.step = Math.min(300, (ft.step ?? 0) + 12);
if (ft.step >= 300) {
ft.running = false;
ft.stage = null;
ft.log.push('[학습] 완료 · CER 9.7% → 9.1% · 채택');
ft.lastResult = { cer_before: 0.097, cer_after: 0.091, adopt: true, model: 'turbo-ft-1015', at: Date.now() };
clearInterval(t);
}
}, 500);
return { ok: true };
},
async finetuneStop() {
ft.running = false;
ft.stage = null;
ft.log.push('[학습] 중지됨');
},
async finetuneRollback() {
await sleep(400);
if (!ft.previousModel) return { ok: false, error: '되돌릴 이전 모델이 없습니다' };
ft.activeModel = ft.previousModel;
ft.previousModel = null;
return { ok: true };
},
async clearTrainingData() {
await sleep(400);
ft.samples = 0;
},
async openExternal(url) {
window.open(url, '_blank');
},
async openPath(p) {
console.info('[mock] openPath', p);
},
async setAutoStart(on) {
state.autoStart = on;
state.settings.general.autoStart = on;
emit();
},
async finishWizard() {
await sleep(300);
state.settings.firstRunDone = true;
emit();
},
async recentLogs() {
await sleep(150);
return [
'2026-10-15 21:02:11 INFO bot 준비 완료: 겜녹이#4821 (서버 1곳)',
'2026-10-15 21:02:12 INFO worker STT 엔진 시작 · cuda:0 · large-v3-turbo float16',
'2026-10-15 21:02:15 INFO relay 사이트 서버 연결됨 (gvr.tkrmagid.kr)',
'2026-10-15 21:05:40 INFO bot 민준 님을 따라 🎮 발로란트 입장 · TTS 안내',
'2026-10-15 21:05:41 INFO recorder 녹음 시작 (참가자 3명)',
'2026-10-15 21:09:03 INFO bot 현우: /녹음제외',
'2026-10-15 21:12:30 INFO games 발로란트 경기 시작 · 어센트 · 경쟁전',
'2026-10-15 21:14:02 WARN stt 대기열 4건 (경기 중 · 낮은 우선순위)',
'2026-10-15 21:25:44 INFO stt utt_8c1f → "B 사이트 레이즈 둘" (0.38초)',
];
},
async quit() {
console.info('[mock] quit');
},
};
return api;
}