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>
This commit is contained in:
EJClaw
2026-10-15 02:16:08 +09:00
parent 827e9d822c
commit 5f04ccdd4e
65 changed files with 4859 additions and 9 deletions

108
app/src/main/api-types.ts Normal file
View File

@@ -0,0 +1,108 @@
// 설정 창(렌더러) ↔ Electron 메인 프로세스 IPC 계약. preload 가 window.gvr 로 노출한다.
import type { User } from '@gvr/shared';
import type { DiagItem } from '../core/diagnostics.js';
import type { BotState } from '../core/discord/bot.js';
import type { RelayStatus } from '../core/relay/client.js';
import type { Settings } from '../core/settings.js';
import type { SttStatus } from '../core/stt/pipeline.js';
export type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };
export interface GpuInfo {
gpus: { index: number; name: string; vram_total_mb: number; vram_used_mb: number; driver: string; cuda_driver?: string; compute_capability?: string }[];
recommend: { realtime: string; precise: string; compute_type: string; budget_mb: number; reason: string; supported?: boolean; warning?: string | null; precise_after_match?: boolean };
}
export interface ModelsInfo {
models: { name: string; repo: string | null; size_mb: number; installed: boolean; path?: string; meta?: any }[];
cuda_runtime: { installed: boolean; path?: string; size_mb?: number };
}
export interface DownloadProgress {
key: string; // "model:large-v3" | "cuda_runtime"
done_mb: number;
total_mb: number;
speed_mbps?: number;
eta_s?: number;
stage?: string;
state: 'running' | 'done' | 'error';
error?: string;
}
export interface FinetuneStatus {
toolsInstalled: boolean;
installing: boolean;
running: boolean;
stage: string | null;
step: number | null;
total: number | null;
samples: number;
lastResult: { cer_before: number; cer_after: number; adopt: boolean; model: string | null; at: number } | null;
activeModel: string | null;
previousModel: string | null;
log: string[];
}
export interface AppState {
version: string;
dataDir: string;
portable: boolean;
settings: Settings;
secrets: { botToken: boolean; riotApiKey: boolean; deviceKey: boolean };
secretCodec: string;
bot: BotState;
worker: { ready: boolean; lastError: string | null };
stt: SttStatus;
relay: RelayStatus;
games: { valorant: { connected: boolean; inMatch: boolean; detail?: string }; lol: { connected: boolean; inMatch: boolean; detail?: string } };
counts: { utterances: number; matches: number };
excludedUsers: { id: string; name: string }[];
autoStart: boolean;
}
export interface GvrApi {
getState(): Promise<AppState>;
onState(cb: (s: AppState) => void): () => void;
updateSettings(patch: DeepPartial<Settings>): Promise<Settings>;
setSecret(key: 'botToken' | 'riotApiKey', value: string | null): Promise<void>;
testBotToken(token?: string): Promise<{ ok: boolean; bot?: { id: string; name: string; avatar: string | null }; guilds?: { id: string; name: string }[]; error?: string }>;
restartBot(): Promise<{ ok: boolean; error?: string }>;
guildMembers(): Promise<{ id: string; name: string; avatar: string | null; bot: boolean }[]>;
previewTts(text: string, voice: string): Promise<{ ok: boolean; dataUrl?: string; error?: string }>;
gpuInfo(): Promise<GpuInfo | null>;
models(): Promise<ModelsInfo | null>;
download(target: 'model' | 'cuda_runtime', name?: string): Promise<{ ok: boolean; error?: string }>;
onProgress(cb: (p: DownloadProgress) => void): () => void;
deleteModel(name: string): Promise<{ ok: boolean; error?: string }>;
applyModels(): Promise<void>;
chooseFolder(title: string, defaultPath?: string): Promise<string | null>;
registerDevice(code: string): Promise<{ ok: boolean; error?: string }>;
unregisterDevice(): Promise<void>;
runDiagnostics(): Promise<DiagItem[]>;
onDiag(cb: (it: DiagItem) => void): () => void;
storageUsage(): Promise<{ audioBytes: number; trainingBytes: number; dbBytes: number; modelsBytes: number; freeBytes: number | null }>;
runRetention(): Promise<{ deleted: number; freedBytes: number }>;
users(): Promise<User[]>;
setRiotIds(userId: string, riotIds: string[]): Promise<void>;
setExcluded(userId: string, excluded: boolean): Promise<void>;
dictionary(): Promise<{ labels: Record<string, string>; packs: { key: string; label: string; count: number }[]; entries: { id: number; word: string; from: string | null; kind: 'hotword' | 'correction'; pack: string; source: string; enabled: boolean; hits: number }[] }>;
addWord(word: string): Promise<void>;
addCorrection(from: string, to: string): Promise<void>;
deleteDict(id: number): Promise<void>;
setDictEnabled(id: number, enabled: boolean): Promise<void>;
finetuneStatus(): Promise<FinetuneStatus>;
finetuneInstall(): Promise<{ ok: boolean; error?: string }>;
finetuneStart(): Promise<{ ok: boolean; error?: string }>;
finetuneStop(): Promise<void>;
finetuneRollback(): Promise<{ ok: boolean; error?: string }>;
clearTrainingData(): Promise<void>;
openExternal(url: string): Promise<void>;
openPath(p: string): Promise<void>;
setAutoStart(on: boolean): Promise<void>;
finishWizard(): Promise<void>;
recentLogs(): Promise<string[]>;
quit(): Promise<void>;
}
declare global {
interface Window {
gvr: GvrApi;
}
}

277
app/src/main/finetune.ts Normal file
View File

@@ -0,0 +1,277 @@
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import https from 'node:https';
import path from 'node:path';
import type { Core } from '../core/index.js';
import { logger } from '../core/util/log.js';
import type { FinetuneStatus } from './api-types.js';
import { finetuneScriptsDir } from './paths.js';
const log = logger('finetune');
const PY_EMBED = 'https://www.python.org/ftp/python/3.11.9/python-3.11.9-embed-amd64.zip';
const GET_PIP = 'https://bootstrap.pypa.io/get-pip.py';
/**
* 파인튜닝 (M8, 보고서 5-5). 학습 도구(torch·transformers·peft)는 exe 에 넣지 않고 처음 쓸 때
* GVR-Data/finetune-env 에 내려받는다 (Windows: 임베디드 파이썬 3.11 + pip, 약 3GB).
* 게임이 실행 중이면 시작하지 않고, 학습 중 게임이 켜지면 중지 파일을 만들어 바로 멈춘다.
*/
export class Finetuner {
status: FinetuneStatus;
private nightlyTimer: NodeJS.Timeout | null = null;
private watch: NodeJS.Timeout | null = null;
constructor(
private core: Core,
private onChange: () => void,
) {
const last = core.store.meta('finetune_last');
this.status = {
toolsInstalled: !!this.python(),
installing: false,
running: false,
stage: null,
step: null,
total: null,
samples: core.store.trainingSamples().length,
lastResult: last ? JSON.parse(last) : null,
activeModel: core.settings.get().finetune.activeModel,
previousModel: core.settings.get().finetune.previousModel,
log: [],
};
}
private envDir(): string {
return path.join(this.core.paths().dataDir, 'finetune-env');
}
/** 학습용 파이썬 */
python(): string | null {
if (process.env.GVR_FINETUNE_PYTHON && fs.existsSync(process.env.GVR_FINETUNE_PYTHON)) return process.env.GVR_FINETUNE_PYTHON;
const p = process.platform === 'win32' ? path.join(this.envDir(), 'python.exe') : path.join(this.envDir(), 'bin', 'python');
return fs.existsSync(p) && fs.existsSync(path.join(this.envDir(), '.gvr-ready')) ? p : null;
}
refresh(): FinetuneStatus {
this.status.toolsInstalled = !!this.python();
this.status.samples = this.core.store.trainingSamples().length;
this.status.activeModel = this.core.settings.get().finetune.activeModel;
this.status.previousModel = this.core.settings.get().finetune.previousModel;
return this.status;
}
private push(line: string): void {
this.status.log.push(`${new Date().toLocaleTimeString('ko-KR', { hour12: false })} ${line}`);
if (this.status.log.length > 200) this.status.log.splice(0, this.status.log.length - 200);
log.info(line);
this.onChange();
}
private inGame(): boolean {
const g = this.core.games.status();
return g.valorant.inMatch || g.lol.inMatch;
}
// ------------------------------------------------------------------ 학습 도구 설치
async install(): Promise<void> {
if (this.status.installing) return;
if (process.platform !== 'win32') throw new Error('학습 도구 자동 설치는 Windows 에서만 지원합니다 (개발 환경은 GVR_FINETUNE_PYTHON 사용)');
this.status.installing = true;
this.onChange();
const dir = this.envDir();
try {
fs.mkdirSync(dir, { recursive: true });
const zip = path.join(dir, 'python-embed.zip');
this.push('임베디드 파이썬 내려받는 중');
await download(PY_EMBED, zip);
await run('powershell.exe', ['-NoProfile', '-Command', `Expand-Archive -Force -Path '${zip}' -DestinationPath '${dir}'`], (l) => this.push(l));
fs.rmSync(zip, { force: true });
// site-packages 와 pip 를 쓰려면 ._pth 에서 import site 를 켠다
for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('._pth'))) {
const p = path.join(dir, f);
fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replace('#import site', 'import site') + '\nLib\\site-packages\n');
}
const getPip = path.join(dir, 'get-pip.py');
await download(GET_PIP, getPip);
const py = path.join(dir, 'python.exe');
this.push('pip 설치');
await run(py, [getPip, '--no-warn-script-location'], (l) => this.push(l));
this.push('PyTorch (CUDA 12.8) 설치 - 약 2.5GB, 시간이 걸립니다');
await run(py, ['-m', 'pip', 'install', '--no-warn-script-location', 'torch', '--index-url', 'https://download.pytorch.org/whl/cu128'], (l) => this.push(l));
this.push('학습 라이브러리 설치');
await run(py, ['-m', 'pip', 'install', '--no-warn-script-location', '-r', path.join(finetuneScriptsDir(), 'requirements.txt')], (l) => this.push(l));
fs.writeFileSync(path.join(dir, '.gvr-ready'), new Date().toISOString());
this.push('학습 도구 설치 완료');
} finally {
this.status.installing = false;
this.refresh();
this.onChange();
}
}
// ------------------------------------------------------------------ 학습
async start(opts: { maxSteps?: number; base?: string; synthCount?: number; exportAlways?: boolean } = {}): Promise<void> {
if (this.status.running) throw new Error('이미 학습 중입니다');
const py = this.python();
if (!py) throw new Error('학습 도구가 설치되지 않았습니다');
if (this.inGame()) throw new Error('게임 중에는 학습을 시작하지 않습니다');
const data = this.core.paths().dataDir;
const stopFile = path.join(data, 'finetune.stop');
fs.rmSync(stopFile, { force: true });
const work = path.join(data, 'finetune', new Date().toISOString().replace(/[:.]/g, '-'));
fs.mkdirSync(work, { recursive: true });
// 입력: 사용자가 고친 문장 + 음성 조각, 사전 단어, 합성용 문장
const samples = this.core.store.trainingSamples().filter((s) => fs.existsSync(s.audio_path));
fs.writeFileSync(path.join(work, 'corrections.jsonl'), samples.map((s) => JSON.stringify({ audio: s.audio_path, text: s.text })).join('\n'));
const words = [...new Set(this.core.dict.candidates('valorant').concat(this.core.dict.candidates('lol'), this.core.dict.candidates('none')))];
fs.writeFileSync(path.join(work, 'words.txt'), words.join('\n'));
fs.writeFileSync(path.join(work, 'sentences.txt'), makeSentences(this.core).join('\n'));
this.status = { ...this.status, running: true, stage: '준비', step: null, total: null };
this.push(`학습 시작: 교정 문장 ${samples.length}개, 사전 ${words.length}단어`);
// 학습 중 게임이 켜지면 중지 파일
this.watch = setInterval(() => {
if (this.inGame() && !fs.existsSync(stopFile)) {
fs.writeFileSync(stopFile, 'game');
this.push('게임이 시작되어 학습을 멈춥니다');
}
}, 3000);
const s = this.core.settings.get();
const base = opts.base || (s.stt.realtimeModel.includes('turbo') || s.stt.realtimeModel.includes('-ft-') ? 'openai/whisper-large-v3-turbo' : `openai/whisper-${s.stt.realtimeModel}`);
try {
const res = await this.core.worker.request(
'train',
{
python: py,
args: {
base,
sentences: path.join(work, 'sentences.txt'),
dictionary: path.join(work, 'words.txt'),
user_corrections: path.join(work, 'corrections.jsonl'),
stop_file: stopFile,
work,
max_steps: opts.maxSteps || undefined,
synth_count: opts.synthCount || undefined,
export_always: opts.exportAlways || undefined,
},
},
0,
(ev) => {
if (ev.event === 'progress') {
this.status.stage = ev.stage ?? this.status.stage;
this.status.step = ev.step ?? null;
this.status.total = ev.total ?? null;
this.onChange();
}
},
);
const result = { cer_before: res.cer_before, cer_after: res.cer_after, adopt: !!res.adopt, model: res.model_name ?? res.model ?? null, at: Date.now() };
this.status.lastResult = result;
this.core.store.setMeta('finetune_last', JSON.stringify(result));
this.push(`학습 끝: 오류율 ${(res.cer_before * 100).toFixed(1)}% → ${(res.cer_after * 100).toFixed(1)}% ${res.adopt ? '(개선 → 새 모델 적용)' : '(개선 없음 → 기존 모델 유지)'}${res.stopped ? ' · 중간에 멈춤' : ''}`);
if (res.adopt && result.model) await this.adopt(result.model);
} catch (e: any) {
this.push(`학습 실패: ${e.message}`);
throw e;
} finally {
if (this.watch) clearInterval(this.watch);
this.watch = null;
this.status.running = false;
this.status.stage = null;
this.refresh();
this.onChange();
}
}
stop(): void {
fs.writeFileSync(path.join(this.core.paths().dataDir, 'finetune.stop'), 'user');
this.push('학습 중지 요청');
}
private async adopt(model: string): Promise<void> {
const s = this.core.settings.get();
this.core.settings.update({ stt: { realtimeModel: model }, finetune: { activeModel: model, previousModel: s.stt.realtimeModel } });
await this.core.stt.load('realtime', model);
}
async rollback(): Promise<void> {
const prev = this.core.settings.get().finetune.previousModel;
if (!prev) throw new Error('되돌릴 이전 모델이 없습니다');
const cur = this.core.settings.get().stt.realtimeModel;
this.core.settings.update({ stt: { realtimeModel: prev }, finetune: { activeModel: null, previousModel: cur } });
await this.core.stt.load('realtime', prev);
this.push(`이전 모델로 되돌림: ${prev}`);
}
/** 매일 새벽 4시 30분 자동 학습 (설정이 켜져 있고, 교정 문장이 20개 이상이고, 게임 중이 아닐 때) */
scheduleNightly(): void {
if (this.nightlyTimer) clearTimeout(this.nightlyTimer);
const now = new Date();
const next = new Date(now);
next.setHours(4, 30, 0, 0);
if (next <= now) next.setDate(next.getDate() + 1);
this.nightlyTimer = setTimeout(async () => {
const s = this.core.settings.get();
if (s.finetune.schedule === 'nightly' && this.python() && !this.inGame() && this.core.store.trainingSamples().length >= 20) {
await this.start().catch(() => undefined);
}
this.scheduleNightly();
}, next.getTime() - now.getTime());
}
dispose(): void {
if (this.nightlyTimer) clearTimeout(this.nightlyTimer);
if (this.watch) clearInterval(this.watch);
}
}
/** 합성 음성용 문장: 사전 단어를 실제로 쓰는 말투 틀에 넣는다 */
export function makeSentences(core: Pick<Core, 'dict'>): string[] {
const val = core.dict.candidates('valorant');
const lol = core.dict.candidates('lol');
const pick = (a: string[], i: number) => a[(i * 7919) % a.length];
const T_VAL = ['{w} 궁 빠졌어', '{w} 쪽으로 로테 하자', '나 {w} 살게', '{w} 조심해 거기 있어', '{w} 봤어 하나 체력 낮아', '이번 라운드 {w} 쓰자'];
const T_LOL = ['{w} 점멸 빠졌어', '{w} 치자 다 모여', '{w} 갱 온다 조심', '{w} 궁 있어 한타 열자', '{w} 와드 박아 줘', '{w} 잡으면 바로 귀환'];
const out: string[] = [];
for (let i = 0; i < 150 && val.length; i++) out.push(T_VAL[i % T_VAL.length].replace('{w}', pick(val, i)));
for (let i = 0; i < 150 && lol.length; i++) out.push(T_LOL[i % T_LOL.length].replace('{w}', pick(lol, i)));
return out;
}
function download(url: string, dest: string, redirects = 5): Promise<void> {
return new Promise((resolve, reject) => {
https
.get(url, (res) => {
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirects > 0) {
res.resume();
return void download(res.headers.location, dest, redirects - 1).then(resolve, reject);
}
if (res.statusCode !== 200) return reject(new Error(`다운로드 실패 ${res.statusCode}: ${url}`));
const f = fs.createWriteStream(dest);
res.pipe(f);
f.on('finish', () => f.close(() => resolve()));
f.on('error', reject);
})
.on('error', reject);
});
}
function run(cmd: string, args: string[], onLine: (l: string) => void): Promise<void> {
return new Promise((resolve, reject) => {
const p = spawn(cmd, args, { windowsHide: true });
let last = 0;
const handle = (d: Buffer) => {
for (const l of d.toString().split(/\r?\n/)) {
// pip 진행 표시가 너무 많아서 2초에 한 줄만
if (l.trim() && Date.now() - last > 2000) {
last = Date.now();
onLine(l.trim().slice(0, 200));
}
}
};
p.stdout.on('data', handle);
p.stderr.on('data', handle);
p.on('error', reject);
p.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`${path.basename(cmd)} 종료 코드 ${code}`))));
});
}

288
app/src/main/ipc.ts Normal file
View File

@@ -0,0 +1,288 @@
import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
import { toUser } from '../core/api/server.js';
import { runDiagnostics } from '../core/diagnostics.js';
import { synthesize } from '../core/discord/tts.js';
import type { Core } from '../core/index.js';
import { registerDevice } from '../core/relay/client.js';
import { dirSize } from '../core/retention.js';
import type { AppState, DownloadProgress, GvrApi } from './api-types.js';
import type { Finetuner } from './finetune.js';
type Handlers = { [K in keyof GvrApi]?: (...args: any[]) => any };
export function buildState(core: Core, opts: { dataDir: string; portable: boolean }): AppState {
const s = core.settings.get();
return {
version: core.version,
dataDir: opts.dataDir,
portable: opts.portable,
settings: s,
secrets: { botToken: core.settings.hasSecret('botToken'), riotApiKey: core.settings.hasSecret('riotApiKey'), deviceKey: core.settings.hasSecret('deviceKey') },
secretCodec: core.settings.codecName,
bot: core.bot.state,
worker: { ready: core.worker.ready, lastError: core.worker.lastError },
stt: core.stt.status,
relay: core.relay.status,
games: core.games.status() as AppState['games'],
counts: core.store.counts(),
excludedUsers: core.store
.listUsers()
.filter((u) => u.excluded)
.map((u) => ({ id: u.id, name: u.name })),
autoStart: app.getLoginItemSettings().openAtLogin,
};
}
/** 설정 창의 window.gvr 요청 처리 (api-types.ts GvrApi) */
export function registerIpc(core: Core, ft: Finetuner, ctx: { dataDir: string; portable: boolean; win: () => BrowserWindow | null; finishWizard: () => void; quit: () => void }) {
const send = (ch: string, payload: unknown) => ctx.win()?.webContents.send(ch, payload);
const progress = (p: DownloadProgress) => send('gvr:progress', p);
const h: Handlers = {
getState: () => buildState(core, ctx),
updateSettings: (patch) => core.settings.update(patch),
setSecret: (key, value) => core.settings.setSecret(key, value),
testBotToken: async (token?: string) => {
const t = token || core.settings.getSecret('botToken');
if (!t) return { ok: false, error: '봇 토큰을 입력해 주세요' };
const get = (p: string) => fetch(`https://discord.com/api/v10${p}`, { headers: { authorization: `Bot ${t}` } });
try {
const me = await get('/users/@me');
if (me.status === 401) return { ok: false, error: '봇 토큰이 올바르지 않습니다' };
if (!me.ok) return { ok: false, error: `디스코드 응답 ${me.status}` };
const u: any = await me.json();
const gs: any[] = await (await get('/users/@me/guilds')).json();
return {
ok: true,
bot: { id: u.id, name: u.username, avatar: u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png` : null },
guilds: gs.map((g) => ({ id: g.id, name: g.name })),
};
} catch (e: any) {
return { ok: false, error: `연결 실패: ${e.message}` };
}
},
restartBot: async () => {
await core.bot.stop();
await core.startBot();
return core.bot.state.status === 'ready' || core.bot.state.status === 'connecting' ? { ok: true } : { ok: false, error: core.bot.state.error ?? '봇을 시작하지 못했습니다' };
},
guildMembers: async () => {
const g = core.bot.guild();
if (!g) return [];
const ms = await g.members.fetch().catch(() => g.members.cache);
return [...ms.values()].map((m) => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 64 }), bot: m.user.bot })).sort((a, b) => a.name.localeCompare(b.name, 'ko'));
},
previewTts: async (text: string, voice: string) => {
try {
const f = path.join(core.paths().tts, `preview-${Date.now()}.webm`);
await synthesize(text, voice, f);
const data = fs.readFileSync(f);
fs.rmSync(f, { force: true });
return { ok: true, dataUrl: `data:audio/webm;base64,${data.toString('base64')}` };
} catch (e: any) {
return { ok: false, error: `음성 합성 실패: ${e.message}` };
}
},
gpuInfo: () => core.worker.request('gpu_info', {}, 30000).catch(() => null),
models: () => core.worker.request('models', {}, 30000).catch(() => null),
download: async (target: 'model' | 'cuda_runtime', name?: string) => {
const key = target === 'model' ? `model:${name}` : 'cuda_runtime';
progress({ key, done_mb: 0, total_mb: 0, state: 'running' });
try {
await core.worker.request('download', { target, name }, 0, (ev) => {
if (ev.event === 'progress') progress({ key, done_mb: ev.done_mb, total_mb: ev.total_mb, speed_mbps: ev.speed_mbps, eta_s: ev.eta_s, stage: ev.stage, state: 'running' });
});
progress({ key, done_mb: 1, total_mb: 1, state: 'done' });
if (target === 'cuda_runtime') {
// 받은 DLL 은 워커를 다시 띄워야 적용된다
await core.worker.stop();
core.worker.start();
} else await core.stt.prepareModels();
return { ok: true };
} catch (e: any) {
progress({ key, done_mb: 0, total_mb: 0, state: 'error', error: e.message });
return { ok: false, error: e.message };
}
},
deleteModel: async (name: string) => {
if (!/^[\w.\-]+$/.test(name)) return { ok: false, error: '잘못된 모델 이름' };
for (const slot of ['realtime', 'precise'] as const) if (core.stt.status.slots[slot].model === name) await core.stt.unload(slot);
fs.rmSync(path.join(core.paths().models, name), { recursive: true, force: true });
return { ok: true };
},
applyModels: async () => {
await core.stt.unload('realtime');
await core.stt.unload('precise');
core.stt.status.slots.realtime.model = null;
core.stt.status.slots.precise.model = null;
await core.stt.prepareModels();
},
chooseFolder: async (title: string, defaultPath?: string) => {
const w = ctx.win();
const r = w ? await dialog.showOpenDialog(w, { title, defaultPath, properties: ['openDirectory', 'createDirectory'] }) : await dialog.showOpenDialog({ title, defaultPath, properties: ['openDirectory', 'createDirectory'] });
return r.canceled ? null : r.filePaths[0];
},
registerDevice: async (code: string) => {
const s = core.settings.get();
try {
const r = await registerDevice(s.site.serverUrl, code, s.site.deviceName);
core.settings.update({ site: { deviceId: r.deviceId } });
core.settings.setSecret('deviceKey', r.deviceKey);
core.relay.restart();
return { ok: true };
} catch (e: any) {
return { ok: false, error: e.message };
}
},
unregisterDevice: () => {
core.settings.update({ site: { deviceId: null } });
core.settings.setSecret('deviceKey', null);
core.relay.restart();
},
runDiagnostics: async () => {
const s = core.settings.get();
return runDiagnostics({
worker: core.worker,
resourcesDir: core.resourcesDir,
logsDir: core.paths().logs,
model: s.stt.realtimeModel,
device: s.stt.device,
computeType: s.stt.computeType,
lolLogsDir: s.games.lolLogsDir,
onItem: (it) => send('gvr:diag', it),
});
},
storageUsage: async () => {
const p = core.paths();
let free: number | null = null;
try {
const st = fs.statfsSync(p.dataDir);
free = st.bavail * st.bsize;
} catch {
/* 지원 안 함 */
}
return {
audioBytes: dirSize(p.audio),
trainingBytes: dirSize(p.training),
dbBytes: ['', '-wal', '-shm'].reduce((n, x) => n + (fs.existsSync(p.db + x) ? fs.statSync(p.db + x).size : 0), 0),
modelsBytes: dirSize(p.models),
freeBytes: free,
};
},
runRetention: () => core.retention.run(),
users: () => {
const acc = core.store.listAccounts();
return core.store.listUsers().map((u) => toUser(u, acc));
},
setRiotIds: (userId: string, riotIds: string[]) => {
const cur = core.store.listAccounts().filter((a) => a.user_id === userId);
const next = riotIds
.map((r) => r.trim())
.filter((r) => /^.+#.+$/.test(r))
.map((r) => cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r });
core.store.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id })));
},
setExcluded: (userId: string, excluded: boolean) => {
core.store.setExcluded(userId, excluded);
core.bus.live({ type: 'users.updated', data: [] });
},
dictionary: () => {
const rows = core.store.listDict();
const counts = new Map<string, number>();
for (const r of rows) if (r.kind === 'hotword' && r.source === 'builtin') counts.set(r.pack, (counts.get(r.pack) || 0) + 1);
return {
labels: core.dict.labels,
packs: [...counts.entries()].map(([key, count]) => ({ key, label: core.dict.labels[key] ?? key, count })),
entries: rows
.filter((r) => r.source !== 'builtin' || r.kind === 'correction')
.map((r) => ({ id: r.id, word: r.word, from: r.from_text || null, kind: r.kind, pack: r.pack, source: r.source, enabled: !!r.enabled, hits: r.hits })),
};
},
addWord: (word: string) => {
const w = word.trim();
if (w) core.store.addDict({ word: w, pack: 'user', kind: 'hotword', from_text: '', source: 'user' });
core.dict.invalidate();
},
addCorrection: (from: string, to: string) => {
if (from.trim() && to.trim()) core.store.addDict({ word: to.trim(), pack: 'user', kind: 'correction', from_text: from.trim(), source: 'user' });
core.dict.invalidate();
},
deleteDict: (id: number) => {
core.store.deleteDict(id);
core.dict.invalidate();
},
setDictEnabled: (id: number, enabled: boolean) => {
core.store.setDictEnabled(id, enabled);
core.dict.invalidate();
},
finetuneStatus: () => ft.refresh(),
finetuneInstall: async () => {
try {
await ft.install();
return { ok: true };
} catch (e: any) {
return { ok: false, error: e.message };
}
},
finetuneStart: async () => {
try {
void ft.start().catch(() => undefined);
await new Promise((r) => setTimeout(r, 300));
return ft.status.running ? { ok: true } : { ok: false, error: ft.status.log[ft.status.log.length - 1] ?? '시작하지 못했습니다' };
} catch (e: any) {
return { ok: false, error: e.message };
}
},
finetuneStop: () => ft.stop(),
finetuneRollback: async () => {
try {
await ft.rollback();
return { ok: true };
} catch (e: any) {
return { ok: false, error: e.message };
}
},
clearTrainingData: () => {
for (const s of core.store.trainingSamples()) fs.rmSync(s.audio_path, { force: true });
core.store.clearTraining();
},
openExternal: (url: string) => {
if (/^https?:\/\//.test(url)) return shell.openExternal(url);
},
openPath: (p: string) => shell.openPath(p),
setAutoStart: (on: boolean) => {
app.setLoginItemSettings({ openAtLogin: on, path: process.env.PORTABLE_EXECUTABLE_FILE || process.execPath, args: ['--hidden'] });
core.settings.update({ general: { autoStart: on } });
},
finishWizard: () => {
core.settings.update({ firstRunDone: true });
ctx.finishWizard();
},
recentLogs: () => {
try {
const dir = core.paths().logs;
const f = fs.readdirSync(dir).filter((x) => x.startsWith('gvr-')).sort().pop();
if (!f) return [];
return fs.readFileSync(path.join(dir, f), 'utf8').trimEnd().split('\n').slice(-300);
} catch {
return [];
}
},
quit: () => ctx.quit(),
};
for (const [name, fn] of Object.entries(h)) {
ipcMain.handle(`gvr:${name}`, async (_e, ...args) => fn!(...args));
}
}

207
app/src/main/main.ts Normal file
View File

@@ -0,0 +1,207 @@
// 겜녹이 Electron 메인 프로세스: 트레이 아이콘 + 설정 창 + 첫 실행 마법사. 실제 일은 코어(src/core)가 한다.
import { app, BrowserWindow, Menu, nativeImage, safeStorage, shell, Tray } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
import { startCore, type Core } from '../core/index.js';
import { plainCodec, type SecretCodec } from '../core/settings.js';
import { logger } from '../core/util/log.js';
import { Finetuner } from './finetune.js';
import { buildState, registerIpc } from './ipc.js';
import { brandDir, rendererDir, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
const log = logger('app');
const argv = process.argv.slice(1);
const flag = (name: string) => argv.includes(`--${name}`);
const opt = (name: string) => argv.find((a) => a.startsWith(`--${name}=`))?.split('=').slice(1).join('=');
const SMOKE = flag('smoke');
app.setAppUserModelId('kr.tkrmagid.gvr');
if (!SMOKE && !app.requestSingleInstanceLock()) {
app.quit();
process.exit(0);
}
let core: Core | null = null;
let ft: Finetuner | null = null;
let win: BrowserWindow | null = null;
let tray: Tray | null = null;
let quitting = false;
const dataDir = resolveDataDir(opt('data-dir'));
function dpapiCodec(): SecretCodec {
// Windows: safeStorage = DPAPI (현재 사용자 계정에 묶인 암호화, N-03)
if (safeStorage.isEncryptionAvailable()) return { name: process.platform === 'win32' ? 'dpapi' : 'os-keychain', encrypt: (s) => safeStorage.encryptString(s), decrypt: (b) => safeStorage.decryptString(b) };
return plainCodec;
}
function trayImage(state: 'idle' | 'rec' | 'off'): Electron.NativeImage {
const f = path.join(brandDir(), state === 'idle' ? 'tray.png' : `tray-${state}.png`);
const img = nativeImage.createFromPath(fs.existsSync(f) ? f : path.join(brandDir(), 'tray.png'));
const hi = f.replace('.png', '@2x.png');
if (fs.existsSync(hi)) img.addRepresentation({ scaleFactor: 2, buffer: fs.readFileSync(hi) });
return img;
}
function openWindow(route?: string): void {
if (!core) return;
const r = route ?? (core.settings.get().firstRunDone ? '/settings/discord' : '/wizard');
if (win && !win.isDestroyed()) {
win.webContents.executeJavaScript(`location.hash = ${JSON.stringify('#' + r)}`).catch(() => undefined);
win.show();
win.focus();
return;
}
win = new BrowserWindow({
width: 1100,
height: 760,
minWidth: 960,
minHeight: 640,
title: core.settings.get().firstRunDone ? '겜녹이 · 설정' : '겜녹이 · 첫 실행 설정',
icon: path.join(brandDir(), 'icon.png'),
backgroundColor: '#0b141c',
autoHideMenuBar: true,
show: false,
webPreferences: { preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, sandbox: true, nodeIntegration: false },
});
win.setMenu(null);
win.on('page-title-updated', (e) => e.preventDefault());
win.loadFile(path.join(rendererDir(), 'index.html'), { hash: r });
win.once('ready-to-show', () => win?.show());
// 창을 닫아도 트레이에서 계속 돈다 (녹음·사이트 연결 유지)
win.on('close', (e) => {
if (!quitting) {
e.preventDefault();
win?.hide();
}
});
win.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//.test(url)) void shell.openExternal(url);
return { action: 'deny' };
});
}
function updateTray(): void {
if (!tray || !core) return;
const st = core.bot.state;
const rel = core.relay.status;
const rec = st.recording.active;
const state = rec ? 'rec' : rel.state === 'online' && st.status === 'ready' ? 'idle' : 'off';
tray.setImage(trayImage(state));
const lines = [
'겜녹이',
rec ? `🔴 녹음 중 · ${st.recording.channel} (${st.recording.participants.length}명)` : st.status === 'ready' ? '대기 중' : st.status === 'error' ? `봇 오류: ${st.error}` : '봇 꺼짐',
`사이트 ${rel.state === 'online' ? '연결됨' : '연결 안 됨'} · STT 대기 ${core.stt.status.queue}`,
];
tray.setToolTip(lines.join('\n'));
}
function buildTrayMenu(): void {
if (!tray || !core) return;
const c = core;
tray.setContextMenu(
Menu.buildFromTemplate([
{ label: '겜녹이 설정 열기', click: () => openWindow() },
{ label: '사이트 열기 (gvr.tkrmagid.kr)', click: () => void shell.openExternal(c.settings.get().site.serverUrl) },
{ type: 'separator' },
{ label: '녹음 종료 (음성채널에서 나가기)', click: () => c.bot.leave('tray'), enabled: c.bot.state.recording.active },
{ label: '진단', click: () => openWindow('/settings/diag') },
{ label: '데이터 폴더 열기', click: () => void shell.openPath(dataDir) },
{ type: 'separator' },
{ label: '종료', click: () => void quit() },
]),
);
}
async function quit(): Promise<void> {
if (quitting) return;
quitting = true;
try {
ft?.dispose();
await core?.stop();
} catch (e) {
log.error('종료 중 오류', e);
}
tray?.destroy();
app.exit(0);
}
async function smoke(): Promise<void> {
// 배포 전 확인 (win-ci): 코어 시작 → 워커 hello → DB·설정·암호화 → 결과 JSON → 종료
const out: Record<string, unknown> = { version: app.getVersion(), dataDir, resources: resourcesDir() };
let code = 1;
try {
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), codec: dpapiCodec() });
out.codec = c.settings.codecName;
const ready = await new Promise<any>((res) => {
if (c.worker.ready) return res(true);
const t = setTimeout(() => res(false), 120000);
c.worker.once('ready', (r) => {
clearTimeout(t);
res(r);
});
});
out.worker = ready;
out.gpu = await c.worker.request('gpu_info', {}, 30000).catch((e) => String(e));
c.settings.setSecret('riotApiKey', 'smoke-test');
out.secretRoundTrip = c.settings.getSecret('riotApiKey') === 'smoke-test';
c.settings.setSecret('riotApiKey', null);
out.dict = c.store.listDict().length;
out.renderer = fs.existsSync(path.join(rendererDir(), 'index.html'));
out.tray = fs.existsSync(path.join(brandDir(), 'tray.png'));
code = ready && out.secretRoundTrip && out.renderer && out.tray ? 0 : 1;
await c.stop();
} catch (e: any) {
out.error = e.stack || e.message;
}
fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(path.join(dataDir, 'smoke.json'), JSON.stringify(out, null, 2));
app.exit(code);
}
app.whenReady().then(async () => {
if (SMOKE) return smoke();
core = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), codec: dpapiCodec() });
const c = core;
ft = new Finetuner(c, () => win?.webContents.send('gvr:state', buildState(c, { dataDir, portable: app.isPackaged })));
ft.scheduleNightly();
registerIpc(c, ft, {
dataDir,
portable: app.isPackaged,
win: () => (win && !win.isDestroyed() ? win : null),
finishWizard: () => win?.setTitle('겜녹이 · 설정'),
quit: () => void quit(),
});
tray = new Tray(trayImage('off'));
tray.on('click', () => openWindow());
buildTrayMenu();
updateTray();
setInterval(() => {
updateTray();
buildTrayMenu();
if (win && !win.isDestroyed() && win.isVisible()) win.webContents.send('gvr:state', buildState(c, { dataDir, portable: app.isPackaged }));
}, 1500);
if (!flag('hidden') || !c.settings.get().firstRunDone) openWindow();
if (process.env.GVR_CAPTURE_DIR) void captureScreens(process.env.GVR_CAPTURE_DIR);
});
/** 개발용: 실제 앱 화면을 차례로 캡처 (GVR_CAPTURE_DIR=폴더) */
async function captureScreens(dir: string): Promise<void> {
fs.mkdirSync(dir, { recursive: true });
const routes = (process.env.GVR_CAPTURE_ROUTES || '/wizard,/settings/discord,/settings/stt,/settings/storage,/settings/diag').split(',');
await new Promise((r) => setTimeout(r, 6000));
for (const r of routes) {
openWindow(r);
await new Promise((res) => setTimeout(res, Number(process.env.GVR_CAPTURE_WAIT || 3500)));
const img = await win!.webContents.capturePage();
fs.writeFileSync(path.join(dir, `app${r.replace(/\//g, '-')}.png`), img.toPNG());
}
await quit();
}
app.on('second-instance', () => openWindow());
app.on('window-all-closed', () => {
/* 트레이에서 계속 */
});
app.on('before-quit', () => {
quitting = true;
});

57
app/src/main/paths.ts Normal file
View File

@@ -0,0 +1,57 @@
import { app } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
/** 개발 중 app/ 폴더 (dist/main.cjs 기준 한 단계 위) */
export const appRoot = path.resolve(__dirname, '..');
export function isPortable(): boolean {
return app.isPackaged;
}
/**
* 데이터 폴더: exe 옆 GVR-Data (포터블). 단일 exe 포터블이면 PORTABLE_EXECUTABLE_DIR 옆.
* 쓸 수 없는 위치(Program Files 등)면 %APPDATA%\GameVoiceRecorder\GVR-Data.
*/
export function resolveDataDir(argDir?: string): string {
if (argDir) return argDir;
if (process.env.GVR_DATA_DIR) return process.env.GVR_DATA_DIR;
if (!app.isPackaged) return path.join(appRoot, '.gvr-data');
const base = process.env.PORTABLE_EXECUTABLE_DIR || path.dirname(process.execPath);
const d = path.join(base, 'GVR-Data');
try {
fs.mkdirSync(d, { recursive: true });
fs.accessSync(d, fs.constants.W_OK);
return d;
} catch {
return path.join(app.getPath('appData'), 'GameVoiceRecorder', 'GVR-Data');
}
}
export function resourcesDir(): string {
return app.isPackaged ? path.join(process.resourcesPath, 'gvr') : path.join(appRoot, 'resources');
}
export function brandDir(): string {
return app.isPackaged ? path.join(process.resourcesPath, 'brand') : path.join(appRoot, '..', 'assets', 'app');
}
export function rendererDir(): string {
return path.join(appRoot, 'dist', 'renderer');
}
/** STT 워커 실행 방법: 배포본은 PyInstaller exe, 개발은 worker/.venv 의 파이썬 */
export function workerCommand(): { cmd: string; args: string[]; cwd?: string } {
if (app.isPackaged) {
const exe = path.join(process.resourcesPath, 'worker', process.platform === 'win32' ? 'gvr-worker.exe' : 'gvr-worker');
return { cmd: exe, args: [], cwd: path.dirname(exe) };
}
const wdir = path.join(appRoot, '..', 'worker');
const py = process.env.GVR_WORKER_PYTHON || path.join(wdir, '.venv', process.platform === 'win32' ? 'Scripts\\python.exe' : 'bin/python');
return { cmd: py, args: ['-m', 'gvr_worker'], cwd: wdir };
}
/** 파인튜닝 스크립트 위치 (워커 패키지 안의 finetune/) */
export function finetuneScriptsDir(): string {
return app.isPackaged ? path.join(process.resourcesPath, 'worker', '_internal', 'gvr_worker', 'finetune') : path.join(appRoot, '..', 'worker', 'gvr_worker', 'finetune');
}

21
app/src/main/preload.ts Normal file
View File

@@ -0,0 +1,21 @@
import { contextBridge, ipcRenderer } from 'electron';
// window.gvr — api-types.ts 의 GvrApi. 이벤트 3개(onState, onProgress, onDiag)만 구독형이고 나머지는 invoke.
const METHODS = [
'getState', 'updateSettings', 'setSecret', 'testBotToken', 'restartBot', 'guildMembers', 'previewTts', 'gpuInfo', 'models',
'download', 'deleteModel', 'applyModels', 'chooseFolder', 'registerDevice', 'unregisterDevice', 'runDiagnostics', 'storageUsage',
'runRetention', 'users', 'setRiotIds', 'setExcluded', 'dictionary', 'addWord', 'addCorrection', 'deleteDict', 'setDictEnabled',
'finetuneStatus', 'finetuneInstall', 'finetuneStart', 'finetuneStop', 'finetuneRollback', 'clearTrainingData', 'openExternal',
'openPath', 'setAutoStart', 'finishWizard', 'recentLogs', 'quit',
];
const api: Record<string, unknown> = {};
for (const m of METHODS) api[m] = (...args: unknown[]) => ipcRenderer.invoke(`gvr:${m}`, ...args);
const sub = (ch: string) => (cb: (v: unknown) => void) => {
const h = (_e: unknown, v: unknown) => cb(v);
ipcRenderer.on(ch, h);
return () => ipcRenderer.removeListener(ch, h);
};
api.onState = sub('gvr:state');
api.onProgress = sub('gvr:progress');
api.onDiag = sub('gvr:diag');
contextBridge.exposeInMainWorld('gvr', api);