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

View File

@@ -0,0 +1,56 @@
// M8 파인튜닝 통합 확인: 사이트 교정(PATCH) → 학습 데이터 → Finetuner(실제 run.py) → CER 비교 → 모델 교체·되돌리기
// GVR_FINETUNE_PYTHON=../worker/.venv-ft/bin/python node --import tsx scripts/finetune-e2e.mts
// 개발 서버는 CPU 라 whisper-tiny, 몇 스텝만 돈다 (파이프라인 확인용. 실제 학습은 게임 PC GPU 에서 large-v3-turbo).
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const root = path.resolve(import.meta.dirname, '..', '..');
const src = path.join(os.homedir(), '.tmp', 'gvr-demo');
if (!fs.existsSync(path.join(src, 'gvr.sqlite'))) throw new Error('먼저 scripts/demo-stack.mts 를 돌려 시연 데이터를 만드세요');
const work = path.join(os.homedir(), '.tmp', 'gvr-ft-e2e');
fs.rmSync(work, { recursive: true, force: true });
fs.cpSync(src, work, { recursive: true, dereference: false, verbatimSymlinks: true });
process.env.GVR_FINETUNE_PYTHON ||= path.join(root, 'worker', '.venv-ft', 'bin', 'python');
const { startCore } = await import('../src/core/index.ts');
const { Finetuner } = await import('../src/main/finetune.ts');
const core = await startCore({ dataDir: work, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'ft-e2e' });
// 틀린 문장 몇 개를 사이트에서 고친 것처럼
const fixes: [string, string][] = [
['demo000', '오늘 랭겜 몇 판 할까'],
['demo003', '제트 대시로 먼저 들어갈게'],
['demo005', '스모크 깔았어 들어가'],
['demo007', '레이즈 궁 빠졌어 B 사이트 로테 하자'],
['demo012', '나 오퍼레이터 살게'],
['demo018', '정글 탑 갱 갈게 라인 당겨줘'],
['demo020', '바텀 와드 박았어 쓰레쉬 어디 있어'],
['demo026', '내일 팀플 회의 몇 시였지'],
];
for (const [id, text] of fixes) {
const r = await core.api.inject({ method: 'PATCH', url: `/api/utterances/${id}`, payload: { text } });
if (r.statusCode !== 200) throw new Error(`PATCH ${id} ${r.statusCode}`);
}
console.log(`학습 데이터 ${core.store.trainingSamples().length}개, 사이트 교정 규칙 ${core.dict.corrections().filter((c) => c).length}개`);
const ft = new Finetuner(core, () => undefined);
console.log('학습 도구', ft.python());
const before = core.settings.get().stt.realtimeModel;
const t0 = Date.now();
await ft.start({ base: 'openai/whisper-tiny', maxSteps: 3, synthCount: 16, exportAlways: true });
console.log(`소요 ${((Date.now() - t0) / 1000).toFixed(0)}초`);
console.log('결과', ft.status.lastResult);
console.log(ft.status.log.slice(-4).join('\n'));
const after = core.settings.get().stt.realtimeModel;
console.log(`실시간 모델: ${before} → ${after} (적재 ${core.stt.status.slots.realtime.state})`);
let ok = !!ft.status.lastResult;
if (ft.status.lastResult?.adopt) {
ok = ok && after !== before && core.stt.status.slots.realtime.state === 'loaded';
// 새 모델로 실제 변환
const r = await core.worker.request('transcribe', { slot: 'realtime', path: path.join(root, 'app/resources/diag/speech_ko.ogg'), hotwords: '', corrections: [], dictionary: [], target_lufs: -18, noise_sensitivity: 0.5, denoise: false, profile_lufs: null });
console.log('새 모델 변환:', r.text);
await ft.rollback();
console.log('되돌리기 후:', core.settings.get().stt.realtimeModel);
ok = ok && core.settings.get().stt.realtimeModel === before;
}
await core.stop();
console.log(ok ? 'FINETUNE E2E PASS' : 'FINETUNE E2E FAIL');
process.exit(ok ? 0 : 1);

69
app/scripts/stt-eval.mts Normal file
View File

@@ -0,0 +1,69 @@
// M7 인식률 평가: 시연 대화 28문장(TTS)을 모델별로 변환해 CER(글자 오류율)을 잰다. 사전(핫워드+교정) 있음/없음 비교.
// node --import tsx scripts/stt-eval.mts <models_dir> <model...>
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store } from '../src/core/db/db.ts';
import { Dictionary } from '../src/core/dict/dictionary.ts';
import { WorkerClient } from '../src/core/stt/worker.ts';
const [modelsDir, ...models] = process.argv.slice(2);
const root = path.resolve(import.meta.dirname, '..', '..');
const clipDir = path.join(os.homedir(), '.tmp', 'gvr-demo-clips');
const demo = fs.readFileSync(path.join(import.meta.dirname, 'demo-stack.mts'), 'utf8');
const lines = [...demo.matchAll(/\{ u: \d, text: '([^']+)', at: \{ (val|lol|off)/g)].map((m) => ({ text: m[1], ctx: m[2] === 'val' ? 'valorant' : m[2] === 'lol' ? 'lol' : 'none' })) as { text: string; ctx: 'valorant' | 'lol' | 'none' }[];
const norm = (s: string) => s.replace(/[\s.,!?~]/g, '').replace(/PC방/g, '피시방').replace(/2명/g, '두명');
function cer(ref: string, hyp: string): number {
const a = [...norm(ref)];
const b = [...norm(hyp)];
const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...new Array(b.length).fill(0)]);
for (let j = 1; j <= b.length; j++) d[0][j] = j;
for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
return d[a.length][b.length] / Math.max(1, a.length);
}
const tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp', 'gvr-eval-'));
const store = new Store(path.join(tmp, 'db.sqlite'));
const dict = new Dictionary(store, path.join(root, 'app', 'resources'), () => ({}));
dict.seed();
const w = new WorkerClient({ cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker'), env: { GVR_DATA_DIR: tmp, GVR_MODELS_DIR: modelsDir, GVR_LOG_LEVEL: 'WARNING' } });
w.start();
await new Promise((r) => w.once('ready', r));
const report: string[] = [];
for (const model of models) {
const t0 = Date.now();
await w.request('load', { slot: 'realtime', model, device: 'cpu', compute_type: 'int8' }, 30 * 60000);
const loadS = (Date.now() - t0) / 1000;
for (const useDict of [false, true]) {
let sum = 0;
let exact = 0;
let ms = 0;
const rows: string[] = [];
for (const [i, l] of lines.entries()) {
const r = await w.request('transcribe', {
slot: 'realtime',
path: path.join(clipDir, `${i}.ogg`),
hotwords: useDict ? dict.hotwords(l.ctx) : '',
corrections: useDict ? dict.corrections() : [],
dictionary: useDict ? dict.candidates(l.ctx) : [],
target_lufs: -18,
noise_sensitivity: 0.5,
denoise: false,
profile_lufs: null,
}, 10 * 60000);
const hyp = r.text ?? '';
const c = cer(l.text, hyp);
sum += c;
if (c === 0) exact++;
ms += r.elapsed_ms;
rows.push(` ${c === 0 ? '=' : c < 0.15 ? '≈' : '≠'} ${l.text} → ${hyp}`);
}
const line = `${model} ${useDict ? '사전 적용' : '사전 없음'}: CER ${((sum / lines.length) * 100).toFixed(1)}% · 완전 일치 ${exact}/${lines.length} · 평균 ${(ms / lines.length / 1000).toFixed(2)}초/문장 (CPU int8) · 적재 ${loadS.toFixed(0)}초`;
console.log(line);
if (useDict) console.log(rows.join('\n'));
report.push(line);
}
await w.request('unload', { slot: 'realtime' });
}
console.log('\n== 요약 ==\n' + report.join('\n'));
await w.stop();
process.exit(0);