Compare commits
10 Commits
5f04ccdd4e
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0635294c55 | ||
|
|
24585e3603 | ||
|
|
c32236c3b8 | ||
|
|
f26f408070 | ||
|
|
47aeef9453 | ||
|
|
8f44f22a8b | ||
|
|
ae2af637ad | ||
|
|
e6723a49ea | ||
|
|
c1b0d2a5c9 | ||
|
|
e7604206bb |
12
README.md
@@ -6,6 +6,8 @@
|
||||
- 게임 PC: 포터블 `GameVoiceRecorder.exe` 하나로 디스코드 봇, STT 엔진, 기록 저장소, 설정 화면이 돈다
|
||||
- 사이트 서버: 디스코드 로그인(서버 멤버만), 게임 PC 연결 확인·잠금 화면, 기록 중계 (기록은 게임 PC 에만 있음)
|
||||
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0) (`GameVoiceRecorder-1.0.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.0.0-portable.exe`)
|
||||
|
||||
## 진행 현황
|
||||
|
||||
@@ -15,11 +17,11 @@
|
||||
| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ✅ 완료 ([실음성 테스트](docs/dev/test-results.md)) |
|
||||
| M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ✅ 완료 · https://gvr.tkrmagid.kr 배포 |
|
||||
| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ✅ 완료 ([전체 스택 테스트](docs/dev/test-results.md)) |
|
||||
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ⏳ |
|
||||
| M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ⏳ |
|
||||
| M6 단어사전 · UI/UX | 핫워드·교정 사전, 사이트 교정 반영, 테마·애니메이션·효과음 | ⏳ |
|
||||
| M7 실사용 테스트 | 통합 테스트, 성능·안정화 | ⏳ |
|
||||
| M8 파인튜닝 | 교정 데이터 + 합성 음성 LoRA 학습, 오류율 비교 후 교체 | ⏳ |
|
||||
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ✅ 완료 (Windows 실기 확인: [기록](docs/dev/test-results.md)) |
|
||||
| M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ✅ 완료 (Windows 빌드·실행 확인) |
|
||||
| M6 단어사전 · UI/UX | 핫워드·교정 사전, 사이트 교정 반영, 테마·애니메이션·효과음 | ✅ 완료 ([사전 효과](docs/dev/test-results.md)) |
|
||||
| M7 실사용 테스트 | 통합 테스트, 성능·안정화 | ✅ 완료 (GPU 실음성: CER 3.6%, 지연 1.05초 · [기록](docs/dev/test-results.md)) |
|
||||
| M8 파인튜닝 | 교정 데이터 + 합성 음성 LoRA 학습, 오류율 비교 후 교체 | ✅ 완료 (GPU 시험 학습: CER 4.8% → 1.8%) |
|
||||
|
||||
## 저장소 구조
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { build } from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = path.dirname(new URL(import.meta.url).pathname);
|
||||
const root = import.meta.dirname; // Windows 에서 URL.pathname 은 /C:/... 라 쓰면 안 된다
|
||||
const shared = path.join(root, '..', 'packages', 'shared', 'src', 'index.ts');
|
||||
fs.writeFileSync(
|
||||
path.join(root, 'src/core/db/schema.ts'),
|
||||
|
||||
@@ -238,6 +238,7 @@ await shot(`/matches/${valId}`, 'real-match-valorant.png', 1440, 900, async () =
|
||||
});
|
||||
await shot(`/matches/${lolId}`, 'real-match-lol.png');
|
||||
await shot(`/users/${USERS[0].id}`, 'real-user.png');
|
||||
await shot('/dictionary', 'real-dictionary.png');
|
||||
await shot('/', 'real-mobile.png', 390, 844);
|
||||
// 연결 끊김 → 잠금, 다시 연결 → 해제
|
||||
core.relay.stop();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// 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).
|
||||
// 기본은 CPU whisper-tiny 몇 스텝 (파이프라인 확인용).
|
||||
// GPU 시험 학습: GVR_FT_BASE=openai/whisper-large-v3-turbo GVR_FT_STEPS=0(=epochs 기준) GVR_FT_SYNTH=300
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -35,7 +36,9 @@ 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 });
|
||||
const ftBase = process.env.GVR_FT_BASE || 'openai/whisper-tiny';
|
||||
const ftSteps = process.env.GVR_FT_STEPS !== undefined ? Number(process.env.GVR_FT_STEPS) : 3;
|
||||
await ft.start({ base: ftBase, maxSteps: ftSteps, synthCount: Number(process.env.GVR_FT_SYNTH || 16), exportAlways: ftBase.endsWith('tiny') });
|
||||
console.log(`소요 ${((Date.now() - t0) / 1000).toFixed(0)}초`);
|
||||
console.log('결과', ft.status.lastResult);
|
||||
console.log(ft.status.log.slice(-4).join('\n'));
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// M7 인식률 평가: 시연 대화 28문장(TTS)을 모델별로 변환해 CER(글자 오류율)을 잰다. 사전(핫워드+교정) 있음/없음 비교.
|
||||
// node --import tsx scripts/stt-eval.mts <models_dir> <model...>
|
||||
// GVR_EVAL_HELDOUT=0,3,5 : 파인튜닝 교정에 쓴 문장 번호. 이 문장을 뺀 CER 도 따로 보여 준다
|
||||
// GPU: GVR_EVAL_DEVICE=cuda (float16). 리눅스는 LD_LIBRARY_PATH 에 cuBLAS·cuDNN 12/9 경로가 있어야 한다.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -8,6 +10,9 @@ import { Dictionary } from '../src/core/dict/dictionary.ts';
|
||||
import { WorkerClient } from '../src/core/stt/worker.ts';
|
||||
|
||||
const [modelsDir, ...models] = process.argv.slice(2);
|
||||
const device = process.env.GVR_EVAL_DEVICE === 'cuda' ? 'cuda' : 'cpu';
|
||||
const computeType = device === 'cuda' ? 'float16' : 'int8';
|
||||
const seenIdx = new Set((process.env.GVR_EVAL_HELDOUT || '').split(',').filter(Boolean).map(Number));
|
||||
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');
|
||||
@@ -31,12 +36,14 @@ 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);
|
||||
await w.request('load', { slot: 'realtime', model, device, compute_type: computeType }, 30 * 60000);
|
||||
const loadS = (Date.now() - t0) / 1000;
|
||||
for (const useDict of [false, true]) {
|
||||
let sum = 0;
|
||||
let exact = 0;
|
||||
let ms = 0;
|
||||
let unseenSum = 0;
|
||||
let unseenN = 0;
|
||||
const rows: string[] = [];
|
||||
for (const [i, l] of lines.entries()) {
|
||||
const r = await w.request('transcribe', {
|
||||
@@ -53,13 +60,17 @@ for (const model of models) {
|
||||
const hyp = r.text ?? '';
|
||||
const c = cer(l.text, hyp);
|
||||
sum += c;
|
||||
if (!seenIdx.has(i)) {
|
||||
unseenSum += c;
|
||||
unseenN++;
|
||||
}
|
||||
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)}초`;
|
||||
const line = `${model} ${useDict ? '사전 적용' : '사전 없음'}: CER ${((sum / lines.length) * 100).toFixed(1)}% · 완전 일치 ${exact}/${lines.length} · 평균 ${(ms / lines.length / 1000).toFixed(2)}초/문장 (${device} ${computeType}) · 적재 ${loadS.toFixed(0)}초${seenIdx.size ? ` · 학습에 안 쓴 ${unseenN}문장 CER ${((unseenSum / unseenN) * 100).toFixed(1)}%` : ''}`;
|
||||
console.log(line);
|
||||
if (useDict) console.log(rows.join('\n'));
|
||||
console.log(rows.filter((r) => !r.startsWith(' =')).join('\n'));
|
||||
report.push(line);
|
||||
}
|
||||
await w.request('unload', { slot: 'realtime' });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// M1 실제 음성 E2E: 테스트봇이 음성채널에 들어가 한국어 문장을 말하면, 겜녹이(코어)가 따라 들어와 녹음 → STT → DB 저장까지.
|
||||
// node --import tsx scripts/voice-e2e.mts <guildId> <voiceChannelId>
|
||||
// 필요: secrets.json 의 겜녹이·테스트봇 토큰, worker/.venv, tiny 모델(HF 캐시)
|
||||
// M7 실사용 시험: GVR_E2E_SET=demo (시연 대화 28문장, 문장별 CER·지연), GVR_E2E_MODEL=<모델 폴더 경로>, GVR_E2E_DEVICE=cuda
|
||||
import { Client, GatewayIntentBits } from 'discord.js';
|
||||
import { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus } from '@discordjs/voice';
|
||||
import fs from 'node:fs';
|
||||
@@ -18,23 +19,30 @@ const work = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-vo
|
||||
const models = path.join(work, 'models');
|
||||
fs.mkdirSync(models, { recursive: true });
|
||||
const hf = path.join(os.homedir(), '.cache/huggingface/hub/models--Systran--faster-whisper-small/snapshots');
|
||||
const model = fs.existsSync(hf) ? 'small' : 'tiny';
|
||||
fs.symlinkSync(path.join(hf.replace('small', model), fs.readdirSync(hf.replace('small', model))[0]), path.join(models, model));
|
||||
const modelArg = process.env.GVR_E2E_MODEL;
|
||||
const model = modelArg ? path.basename(modelArg) : fs.existsSync(hf) ? 'small' : 'tiny';
|
||||
const device = process.env.GVR_E2E_DEVICE === 'cuda' ? 'cuda' : 'cpu';
|
||||
fs.symlinkSync(modelArg ? path.resolve(modelArg) : path.join(hf.replace('small', model), fs.readdirSync(hf.replace('small', model))[0]), path.join(models, model));
|
||||
fs.writeFileSync(
|
||||
path.join(work, 'settings.json'),
|
||||
JSON.stringify({
|
||||
discord: { guildId, followUserId: SPEAKER_ID, followEnabled: true, ttsEnabled: true, ttsOnNewMember: false },
|
||||
stt: { realtimeModel: model, preciseModel: model, device: 'cpu', computeType: 'int8' },
|
||||
stt: { realtimeModel: model, preciseModel: model, device, computeType: device === 'cuda' ? 'float16' : 'int8' },
|
||||
games: { valorant: false, lol: false },
|
||||
}),
|
||||
);
|
||||
process.env.GVR_RECORD_BOTS = '1';
|
||||
process.env.GVR_BOT_TOKEN = GVR_TOKEN;
|
||||
const SENTENCES = ['레이즈 궁 빠졌어 B 사이트 로테 하자', '오늘 저녁에 치킨 먹을래', '나 오퍼레이터 살게'];
|
||||
const DEMO = process.env.GVR_E2E_SET === 'demo';
|
||||
const demoSrc = fs.readFileSync(path.join(import.meta.dirname, 'demo-stack.mts'), 'utf8');
|
||||
const SENTENCES = DEMO
|
||||
? [...demoSrc.matchAll(/\{ u: \d, text: '([^']+)', at: \{ (?:val|lol|off)/g)].map((m) => m[1])
|
||||
: ['레이즈 궁 빠졌어 B 사이트 로테 하자', '오늘 저녁에 치킨 먹을래', '나 오퍼레이터 살게'];
|
||||
const clips: string[] = [];
|
||||
const clipDir = path.join(os.homedir(), '.tmp', 'gvr-e2e-clips');
|
||||
const clipDir = path.join(os.homedir(), '.tmp', DEMO ? 'gvr-demo-clips' : 'gvr-e2e-clips');
|
||||
fs.mkdirSync(clipDir, { recursive: true });
|
||||
for (const [i, s] of SENTENCES.entries()) {
|
||||
const f = path.join(clipDir, `say-${i}.webm`);
|
||||
const f = path.join(clipDir, DEMO ? `${i}.webm` : `say-${i}.webm`);
|
||||
if (!fs.existsSync(f)) await synthesize(s, i % 2 ? 'ko-KR-InJoonNeural' : 'ko-KR-SunHiNeural', f);
|
||||
clips.push(f);
|
||||
}
|
||||
@@ -61,6 +69,11 @@ try {
|
||||
await wait(() => core.bot.state.recording.active, 20000, 'gvr follows speaker');
|
||||
console.log('겜녹이 따라 들어옴 (follow):', core.bot.state.recording.channel);
|
||||
await new Promise((r) => setTimeout(r, 9000)); // 안내 음성이 끝나고 DAVE 키 교환이 안정될 때까지
|
||||
// 발화가 끝난 뒤 글자가 나오기까지 걸린 시간 (실시간 모델 지연)
|
||||
const seen = new Map<string, number>();
|
||||
const poll = setInterval(() => {
|
||||
for (const r of core.store.db.prepare(`SELECT id FROM utterances WHERE status!='pending'`).all() as { id: string }[]) if (!seen.has(r.id)) seen.set(r.id, Date.now());
|
||||
}, 100);
|
||||
const player = createAudioPlayer();
|
||||
conn.subscribe(player);
|
||||
for (const f of clips) {
|
||||
@@ -70,8 +83,33 @@ try {
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
}
|
||||
await wait(() => core.store.db.prepare(`SELECT count(*) n FROM utterances WHERE status!='pending'`).get().n >= SENTENCES.length, 90000, 'stt');
|
||||
const rows = core.store.db.prepare('SELECT user_id, started_at, ended_at, text, gain_db, status FROM utterances ORDER BY started_at').all() as any[];
|
||||
for (const r of rows) console.log(` [${r.user_id === SPEAKER_ID ? '테스트봇' : r.user_id}] ${((r.ended_at - r.started_at) / 1000).toFixed(1)}s gain ${r.gain_db?.toFixed(1)}dB ${r.status}: ${r.text}`);
|
||||
clearInterval(poll);
|
||||
const rows = core.store.db.prepare('SELECT id, user_id, started_at, ended_at, text, gain_db, status FROM utterances ORDER BY started_at').all() as any[];
|
||||
const lat = rows.map((r) => (seen.get(r.id) ?? Date.now()) - r.ended_at);
|
||||
for (const [i, r] of rows.entries()) console.log(` [${r.user_id === SPEAKER_ID ? '테스트봇' : r.user_id}] ${((r.ended_at - r.started_at) / 1000).toFixed(1)}s gain ${r.gain_db?.toFixed(1)}dB 지연 ${(lat[i] / 1000).toFixed(2)}s ${r.status}: ${r.text}`);
|
||||
const sorted = [...lat].sort((a, b) => a - b);
|
||||
console.log(`발화 ${rows.length}개 (말한 문장 ${SENTENCES.length}개) · 모델 ${model} (${device}) · 지연 중앙값 ${(sorted[Math.floor(sorted.length / 2)] / 1000).toFixed(2)}s · 최대 ${(sorted[sorted.length - 1] / 1000).toFixed(2)}s`);
|
||||
let cerAvg = 0;
|
||||
if (DEMO) {
|
||||
// 발화가 문장 수와 같으면 순서대로 짝지어 CER 을 잰다 (stt-eval 과 같은 정규화)
|
||||
const norm = (x: string) => x.replace(/[\s.,!?~]/g, '').replace(/PC방/g, '피시방').replace(/2명/g, '두명');
|
||||
const cer = (a0: string, b0: string) => {
|
||||
const a = [...norm(a0)];
|
||||
const b = [...norm(b0)];
|
||||
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);
|
||||
};
|
||||
if (rows.length === SENTENCES.length) {
|
||||
const cs = rows.map((r, i) => cer(SENTENCES[i], r.text || ''));
|
||||
cerAvg = cs.reduce((a, b) => a + b, 0) / cs.length;
|
||||
console.log(`CER ${(cerAvg * 100).toFixed(1)}% · 완전 일치 ${cs.filter((c) => c === 0).length}/${cs.length}`);
|
||||
} else {
|
||||
cerAvg = 1;
|
||||
console.log('발화 수가 문장 수와 달라 CER 을 짝지을 수 없음 (발화 분할 확인 필요)');
|
||||
}
|
||||
}
|
||||
// 녹음 제외 확인
|
||||
core.store.setExcluded(SPEAKER_ID, true);
|
||||
const before = rows.length;
|
||||
@@ -81,7 +119,7 @@ try {
|
||||
const after = (core.store.db.prepare('SELECT count(*) n FROM utterances').get() as any).n;
|
||||
console.log(`녹음 제외 후 새 발화: ${after - before}개 (0 이어야 함)`);
|
||||
const texts = rows.map((r) => r.text || '').join(' ');
|
||||
ok = rows.length >= SENTENCES.length && /레이즈|오퍼|치킨/.test(texts) && after === before;
|
||||
ok = rows.length >= SENTENCES.length && /레이즈|오퍼|치킨/.test(texts) && after === before && (!DEMO || cerAvg < 0.15);
|
||||
conn.destroy();
|
||||
await wait(() => !core.bot.state.recording.active, 20000, 'gvr leaves after speaker').catch(() => console.log('(겜녹이 퇴장 대기 시간 초과)'));
|
||||
console.log('겜녹이 퇴장:', !core.bot.state.recording.active);
|
||||
|
||||
@@ -180,7 +180,8 @@ export class Bot {
|
||||
|
||||
private updateParticipants(): void {
|
||||
const ch = this.currentChannel();
|
||||
const humans = ch ? [...ch.members.values()].filter((m) => !m.user.bot) : [];
|
||||
// GVR_RECORD_BOTS=1 (테스트봇으로 시험할 때)이면 봇도 사람처럼 센다. 안 그러면 30초 뒤 '빈 방'으로 나가 버린다.
|
||||
const humans = ch ? [...ch.members.values()].filter((m) => !m.user.bot || (process.env.GVR_RECORD_BOTS === '1' && m.id !== this.client?.user?.id)) : [];
|
||||
this.state.recording.participants = humans.map((m) => m.id);
|
||||
this.emitState();
|
||||
// 사람이 아무도 없으면 30초 뒤 나간다
|
||||
|
||||
BIN
docs/dev/screens/real-dictionary.png
Normal file
|
After Width: | Height: | Size: 128 KiB |
|
Before Width: | Height: | Size: 449 KiB After Width: | Height: | Size: 451 KiB |
|
Before Width: | Height: | Size: 380 KiB After Width: | Height: | Size: 380 KiB |
|
Before Width: | Height: | Size: 328 KiB After Width: | Height: | Size: 328 KiB |
|
Before Width: | Height: | Size: 88 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 214 KiB After Width: | Height: | Size: 215 KiB |
|
Before Width: | Height: | Size: 186 KiB After Width: | Height: | Size: 187 KiB |
|
Before Width: | Height: | Size: 169 KiB After Width: | Height: | Size: 170 KiB |
@@ -45,3 +45,86 @@ VOICE E2E PASS
|
||||
- STT(개발 서버 CPU, small) 28문장 중 15문장 완전 일치. 나머지는 띄어쓰기·문장부호·붙은 단어 차이가 대부분
|
||||
- 발견·수정: 작은 모델이 말을 못 알아들으면 핫워드 목록을 그대로 읽는 문제("가렌 점멸 빠졌어" → "탑라이너 바텀 슈퍼미니언…") → 핫워드 40개로 줄이고, 결과가 핫워드 되풀이면 핫워드 없이 다시 변환 (`worker/tests/test_hotword_echo.py`)
|
||||
- 발견·수정: ACS 가 12처럼 작게 나오던 문제 (API 는 총 전투 점수, 화면이 라운드 수로 나눔)
|
||||
|
||||
## M4 롤 연동 · 채팅 OCR (2026-10-15)
|
||||
|
||||
- `app/test/games.test.ts` — 가짜 롤 게임 클라이언트 API(2999) + LCU 로 경기 시작 → 킬·오브젝트·인게임 채팅 → 종료 → LCU 결과·타임라인 적용, 게임 시간 표시
|
||||
- 롤 경기 상세 화면(킬 위치·골드 그래프·CS·오브젝트): `docs/dev/screens/real-match-lol.png`
|
||||
- **Windows 실기 확인** (win-ci Windows 11 VM, `tools/win-ci/run.sh full`, `worker/scripts/win_smoke.py`)
|
||||
- 채팅 OCR(Windows 한국어 OCR): 예시 채팅 이미지 3줄 중 **3줄** 인식 (`[팀] 민수 (아리): 드래곤 가자` 등)
|
||||
- r3dlog 채팅 읽기 2줄, STT(tiny, CPU) 한국어 변환, 워커 pytest 41개 통과(1개는 리눅스 전용이라 건너뜀)
|
||||
- Windows 에서만 나던 문제 3개를 찾아 고침
|
||||
1. pywinrt 의 오래된 `msvcp140.dll`(14.29)이 먼저 올라가면 onnxruntime 이 `0xC0000005` 로 죽음 → onnxruntime·ctranslate2 를 먼저 적재, 빌드 전 winrt 의 msvcp140 삭제
|
||||
2. 첫 변환이 영원히 멈춤 → faulthandler 스택으로 위치 확인: 요청 스레드에서 scipy(OpenBLAS DLL)를 처음 불러올 때 멈춤 → 시작할 때 주 스레드에서 미리 적재 (pytest 373초 → 8초)
|
||||
3. 워커가 띄우는 파인튜닝 자식 프로세스가 시작 단계에서 멈춤 → 요청 파이프(stdin)를 물려주지 않음
|
||||
|
||||
## M5 exe · 설정 · 모델 (2026-10-15)
|
||||
|
||||
- Windows 빌드 (win-ci, electron-builder): `GameVoiceRecorder-1.0.0-portable.exe` 168MB(단일 파일), `GameVoiceRecorder-1.0.0-win-x64.zip` 258.6MB(폴더 포터블), 내장 STT 워커(PyInstaller) 324.8MB
|
||||
- exe 스모크(`GameVoiceRecorder.exe --smoke`): 설정 암호화 DPAPI 왕복 ✅, 워커 기동(python 3.12) ✅, GPU 감지(VM 은 GPU 없음 → CPU 경고) ✅, 사전 2,026단어 ✅, 설정 창 렌더러 ✅, 트레이 ✅
|
||||
- 워커 exe 스모크: OCR 3/3, STT, r3dlog — 파이썬 실행과 같은 결과
|
||||
- 설정 창 8개 탭 + 첫 실행 마법사 5단계: `app/src/renderer/screenshots/`
|
||||
- 모델 관리: GPU VRAM 으로 실시간/정밀 모델 추천, 모델·CUDA 런타임 다운로드(이어받기·sha256), 7일 뒤 음성 삭제(글자·경기 기록은 유지)
|
||||
|
||||
## M6 단어사전 · UI/UX (2026-10-15)
|
||||
|
||||
- 사전: 기본 묶음 8개(일상 93 · 게임 공통 104 · 롤 412 · 롤 스킬 850 · 20대 말투 69 · 대학생 76 · 발로란트 293 · 발로란트 콜아웃 101, 약 2,000단어) + 교정 규칙 28개
|
||||
- 게임 패치 데이터(Riot Data Dragon · valorant-api)로 새 요원·챔피언·맵 이름 자동 추가
|
||||
- 사이트 "단어사전" 화면에서 자주 쓰는 말·별명, 교정 규칙 추가/삭제 (`/api/dictionary`), 타임라인에서 문장을 고치면 바뀐 단어가 교정 규칙으로 자동 추가
|
||||
- 화면: `docs/dev/screens/real-dictionary.png` (전체 스택 시연 `app/scripts/demo-stack.mts` 에서 촬영)
|
||||
- 사전 효과 (GPU, 시연 대화 28문장, `app/scripts/stt-eval.mts`): large-v3-turbo CER 4.8% → **3.9%**, small 10.9% → 8.1%
|
||||
- 테마·효과음: 발로란트(빨강)×롤(금색) 테마, 효과음은 Web Audio 합성(음원 파일 없음), 애니메이션 11종 — 사이트 설정에서 끄고 켬
|
||||
- 실서버 https://gvr.tkrmagid.kr 재배포 (사전 화면 · 사이트 서버 종료 시 WebSocket 먼저 끊기 수정 포함)
|
||||
|
||||
## M7 실사용 테스트 · 안정화 (2026-10-15)
|
||||
|
||||
개발 서버 GPU(RTX 5050 8GB, 다른 서비스가 3GB 사용 중)에서 게임 PC 와 같은 GPU 경로(CUDA float16)로 측정.
|
||||
|
||||
### 실제 디스코드 음성 — `GVR_E2E_SET=demo GVR_E2E_DEVICE=cuda GVR_E2E_MODEL=<large-v3-turbo> app/scripts/voice-e2e.mts`
|
||||
|
||||
F&L "음성" 채널에서 테스트봇이 시연 대화 28문장을 연달아 말하고, 겜녹이가 따라 들어와 녹음 → STT.
|
||||
|
||||
```
|
||||
발화 28개 (말한 문장 28개) · 모델 large-v3-turbo (cuda) · 지연 중앙값 1.05s · 최대 1.86s
|
||||
CER 3.6% · 완전 일치 21/28
|
||||
녹음 제외 후 새 발화: 0개 (0 이어야 함)
|
||||
겜녹이 퇴장: true
|
||||
VOICE E2E PASS
|
||||
```
|
||||
|
||||
- 발화 분할 28/28 (문장 사이 1.5초 쉼), 지연 = 말이 끝난 뒤 사이트에 글자가 생기기까지 (첫 발화 1.86초는 모델 첫 실행)
|
||||
- 발견·수정: 테스트봇만 있는 방을 "빈 방"으로 보고 30초 뒤 나가던 문제 (`GVR_RECORD_BOTS=1` 시험 모드에서 봇도 참가자로 셈)
|
||||
|
||||
### 모델별 인식률·속도 — `GVR_EVAL_DEVICE=cuda app/scripts/stt-eval.mts`
|
||||
|
||||
시연 대화 28문장(TTS), CER = 글자 오류율(띄어쓰기·문장부호 제외).
|
||||
|
||||
| 모델 (CUDA float16) | 사전 없음 CER | 사전 적용 CER | 완전 일치 | 문장당 변환 | 적재 |
|
||||
|---|---|---|---|---|---|
|
||||
| large-v3-turbo (실시간 기본) | 4.8% | **3.9%** | 21/28 | 0.31초 | 4초 |
|
||||
| large-v3 (정밀) | 4.3% | 4.8% | 19/28 | 0.48초 | 6초 |
|
||||
| small | 10.9% | 8.1% | 17/28 | 0.16초 | 1초 미만 |
|
||||
|
||||
- 남은 오류는 대부분 비슷한 소리("대시"→"데스", "칠게"→"7개", "깔았어"→"깔아서"): 교정 사전·파인튜닝 대상
|
||||
- large-v3 는 이 짧은 게임 대화에서 turbo 보다 낫지 않음 → 실시간은 turbo, 정밀(경기 후 다시 변환)은 large-v3 그대로 두되 기본값은 GPU 여유로 고름
|
||||
- 게임 프레임 영향은 실제 게임 PC 에서만 잴 수 있다 (진단 탭 "STT 속도"로 VRAM·속도 확인, 경기 중 정밀 변환은 미루는 것이 기본값)
|
||||
|
||||
## M8 파인튜닝 (2026-10-15)
|
||||
|
||||
`GVR_FT_BASE=openai/whisper-large-v3-turbo GVR_FT_STEPS=0 GVR_FT_SYNTH=300 app/scripts/finetune-e2e.mts` — 앱의 실제 학습 경로(`Finetuner` → `finetune/run.py`)
|
||||
|
||||
- 데이터: 사이트에서 고친 문장 8개 + 사전 단어로 만든 문장을 Edge TTS 3개 음성으로 합성 300개(속도·피치 변화, 30% 배경 잡음) → 학습 281 / 검증 27
|
||||
- 학습: LoRA r=32, 3 에폭 54스텝, **394초**, 최대 VRAM **2.7GB** (RTX 5050)
|
||||
- 검증 세트 CER 9.7% → **8.3%** → 자동 교체 → 새 모델로 변환 확인 → 되돌리기 확인 (`FINETUNE E2E PASS`)
|
||||
- 시연 대화 28문장 (CUDA float16, 학습에 쓴 8문장을 뺀 20문장 따로):
|
||||
|
||||
| 모델 | 사전 없음 | 사전 적용 | 학습에 안 쓴 20문장 |
|
||||
|---|---|---|---|
|
||||
| large-v3-turbo | 4.8% | 3.9% | 2.6% |
|
||||
| large-v3-turbo-ft (이번 학습) | **1.8%** | 2.0% | **1.8%** |
|
||||
|
||||
- 발견·수정 ① 첫 시험은 GPU 메모리 부족 → 얼려 둔 원본 가중치를 bf16 으로 적재(학습하는 LoRA 만 fp32)해 VRAM 절반
|
||||
- 발견·수정 ② 첫 학습 모델은 검증 CER 은 좋아졌는데(10.2→7.9%) 실제 변환에서 문장 끝에 "끝", "댕댕댕", "끈의 주인공" 같은 말을 지어냄 (사전 없음 CER 4.8% → 21.8%).
|
||||
원인: `<|notimestamps|>` 라벨로만 학습 → 앱(faster-whisper)이 쓰는 타임스탬프 모드에서 끝맺음을 잊음. 검증도 notimestamps 로 해서 못 걸렀음.
|
||||
→ 절반은 `<|0.00|> 문장 <|말끝|>` 라벨로 학습, 검증도 타임스탬프 모드로 → 위 표처럼 사전 없이도 개선
|
||||
- 한계: 합성 음성과 시연 대화가 같은 TTS 엔진이라 실제 목소리에서는 개선 폭이 작을 수 있다. 실사용 교정 데이터가 2주쯤 쌓이면 게임 PC(RTX 5070 Ti)에서 다시 학습해 비교한다
|
||||
|
||||
BIN
docs/gemnoki-final-report.pdf
Normal file
335
docs/report/final/final-report.html
Normal file
@@ -0,0 +1,335 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>겜녹이 제작 완료 보고서 (M0~M8)</title>
|
||||
<style>
|
||||
@page { size: A4; margin: 15mm 15mm 17mm 15mm; }
|
||||
:root { --ink:#1b1f27; --muted:#5d6675; --line:#d9dee6; --soft:#f3f5f8; --accent:#ff4655; --accent2:#0fb5ae; --warn:#f2a516; --dark:#0f1923; --lol:#c8aa6e; }
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: "Noto Sans CJK KR", "NanumBarunGothic", sans-serif; color: var(--ink); font-size: 9.8pt; line-height: 1.6; margin: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||
h1, h2, h3 { font-family: "NanumSquare Neo", "Noto Sans CJK KR", sans-serif; line-height: 1.3; }
|
||||
h2 { font-size: 15.5pt; margin: 0 0 10px; padding-bottom: 6px; border-bottom: 3px solid var(--dark); break-after: avoid; }
|
||||
h2 .num { color: var(--accent); margin-right: 8px; }
|
||||
h3 { font-size: 11.2pt; margin: 14px 0 5px; color: var(--dark); break-after: avoid; }
|
||||
p { margin: 4px 0 8px; }
|
||||
code, .mono { font-family: "D2Coding ligature", "DejaVu Sans Mono", monospace; font-size: 8.6pt; }
|
||||
pre { font-family: "D2Coding ligature", "DejaVu Sans Mono", monospace; font-size: 8.3pt; background: #0f1923; color: #d8e1ea; padding: 8px 10px; border-radius: 6px; white-space: pre-wrap; break-inside: avoid; margin: 6px 0 10px; }
|
||||
.page { break-before: page; }
|
||||
table { width: 100%; border-collapse: collapse; margin: 6px 0 10px; font-size: 8.8pt; }
|
||||
th, td { border: 1px solid var(--line); padding: 4px 7px; vertical-align: top; text-align: left; }
|
||||
th { background: var(--dark); color: #fff; font-weight: 600; }
|
||||
tr { break-inside: avoid; }
|
||||
tr:nth-child(even) td { background: #fafbfc; }
|
||||
td.num, th.num { text-align: right; white-space: nowrap; }
|
||||
td.good { color: #116b47; font-weight: 700; }
|
||||
td.bad { color: #b0122a; }
|
||||
ul { margin: 4px 0 8px; padding-left: 18px; }
|
||||
li { margin: 2px 0; }
|
||||
.callout { border-left: 4px solid var(--accent); background: #fff3f4; padding: 7px 12px; margin: 8px 0; border-radius: 0 6px 6px 0; break-inside: avoid; }
|
||||
.callout.info { border-color: var(--accent2); background: #ecfaf9; }
|
||||
.callout.warn { border-color: var(--warn); background: #fff8e8; }
|
||||
.callout b.t { display: block; margin-bottom: 2px; }
|
||||
.tag { display: inline-block; font-size: 7.8pt; padding: 0 6px; border-radius: 9px; border: 1px solid var(--line); background: var(--soft); white-space: nowrap; }
|
||||
.tag.green { background: #e2f7ef; border-color: #a6e3c9; color: #116b47; }
|
||||
.tag.yellow { background: #fff2cf; border-color: #f5d27a; color: #7a5600; }
|
||||
.small { font-size: 8.3pt; color: var(--muted); }
|
||||
figure { margin: 8px 0 12px; break-inside: avoid; }
|
||||
figure img { width: 100%; border-radius: 7px; border: 1px solid #263544; display: block; }
|
||||
figcaption { font-size: 8.3pt; color: var(--muted); margin-top: 4px; }
|
||||
figcaption b { color: var(--ink); }
|
||||
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.grid2b { display: grid; grid-template-columns: 1.65fr 1fr; gap: 10px; align-items: start; }
|
||||
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 8px 0 12px; break-inside: avoid; }
|
||||
.stat { background: var(--dark); color: #fff; border-radius: 10px; padding: 9px 11px; }
|
||||
.stat .v { font-family: "NanumSquare Neo", sans-serif; font-size: 18pt; font-weight: 800; line-height: 1.1; }
|
||||
.stat .v small { font-size: 9.5pt; color: #c9d1dc; margin-left: 2px; }
|
||||
.stat .l { font-size: 7.9pt; color: #c9d1dc; margin-top: 3px; line-height: 1.35; }
|
||||
.stat:nth-child(1) .v { color: #ff7a85; } .stat:nth-child(2) .v { color: #4fd8cf; } .stat:nth-child(3) .v { color: #ffc86a; } .stat:nth-child(4) .v { color: #9fc4ff; }
|
||||
.bars { border: 1px solid var(--line); border-radius: 10px; padding: 9px 12px; background: #fcfcfb; break-inside: avoid; margin: 8px 0 10px; }
|
||||
.bars .vt { font-weight: 700; font-size: 9.4pt; font-family: "NanumSquare Neo", sans-serif; }
|
||||
.bars .vs { font-size: 8pt; color: var(--muted); margin-bottom: 6px; }
|
||||
.bar { display: flex; align-items: center; gap: 8px; margin: 4px 0; font-size: 8.4pt; }
|
||||
.bar .lab { width: 210px; flex: none; }
|
||||
.bar .track { flex: 1; height: 16px; background: #eef1f5; border-radius: 4px; overflow: hidden; }
|
||||
.bar .fill { height: 100%; border-radius: 4px; }
|
||||
.bar .val { width: 46px; text-align: right; font-weight: 700; }
|
||||
/* cover */
|
||||
.cover { height: 263mm; background: var(--dark); color: #fff; padding: 16mm 17mm; position: relative; overflow: hidden; }
|
||||
.cover .bar0 { width: 70px; height: 6px; background: var(--accent); margin-bottom: 16px; }
|
||||
.cover h1 { font-size: 29pt; margin: 0 0 6px; }
|
||||
.cover .sub { font-size: 12pt; color: #c9d1dc; margin-bottom: 14px; }
|
||||
.cover .ban { width: 100%; border-radius: 10px; border: 1px solid #2f4152; margin: 6px 0 16px; }
|
||||
.cover table.meta td { border: none; color: #c9d1dc; padding: 2px 12px 2px 0; background: transparent !important; font-size: 10pt; }
|
||||
.cover table.meta td:first-child { color: #7f8b99; width: 105px; white-space: nowrap; }
|
||||
.cover .done { display: grid; grid-template-columns: repeat(9, 1fr); gap: 5px; margin-top: 18px; }
|
||||
.cover .done div { background: #17303a; border: 1px solid #2c5a5a; border-radius: 7px; text-align: center; padding: 6px 0; font-size: 8.5pt; color: #4fd8cf; font-weight: 700; }
|
||||
.cover .foot { position: absolute; left: 17mm; bottom: 15mm; color: #7f8b99; font-size: 9pt; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<section class="cover">
|
||||
<div class="bar0"></div>
|
||||
<h1>겜녹이 제작 완료 보고서</h1>
|
||||
<div class="sub">Game Voice Recorder (GVR) · M0 기술 검증부터 M8 파인튜닝까지 전 단계</div>
|
||||
<img class="ban" src="../../../assets/app/banner.png" alt="겜녹이 배너">
|
||||
<table class="meta">
|
||||
<tr><td>작성일</td><td>2026년 10월 15일</td></tr>
|
||||
<tr><td>저장소</td><td>https://git.tkrmagid.kr/tkrmagid/game_voice_recorder (main, 커밋 24585e3)</td></tr>
|
||||
<tr><td>사이트</td><td>https://gvr.tkrmagid.kr (운영 중)</td></tr>
|
||||
<tr><td>검증 환경</td><td>개발 서버(리눅스, RTX 5050 8GB) · Windows 11 VM(win-ci) · 디스코드 F&L 서버 "음성" 채널</td></tr>
|
||||
<tr><td>결과물</td><td>GameVoiceRecorder-1.0.0-portable.exe (단일 파일) · GameVoiceRecorder-1.0.0-win-x64.zip (폴더) · 사이트 서버(Docker)</td></tr>
|
||||
</table>
|
||||
<div class="done"><div>M0 ✓</div><div>M1 ✓</div><div>M2 ✓</div><div>M3 ✓</div><div>M4 ✓</div><div>M5 ✓</div><div>M6 ✓</div><div>M7 ✓</div><div>M8 ✓</div></div>
|
||||
<div class="foot">겜녹이 · 디스코드 음성 녹음 + 한국어 STT + 발로란트/리그 오브 레전드 경기 타임라인</div>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<h2><span class="num">1</span>요약</h2>
|
||||
<p>계획서의 M0~M8 아홉 단계를 모두 만들었습니다. 단계가 끝날 때마다 Gitea 저장소에 push하고 README 진행표를 고쳤습니다. 단계마다 자동 테스트를 돌렸고, 실제 디스코드 음성채널, Windows VM, 이 서버 GPU에서도 직접 확인했습니다.</p>
|
||||
<div class="stats">
|
||||
<div class="stat"><div class="v">3.6<small>%</small></div><div class="l">실제 디스코드 음성 28문장<br>글자 오류율(CER), GPU large-v3-turbo</div></div>
|
||||
<div class="stat"><div class="v">1.05<small>초</small></div><div class="l">말이 끝난 뒤 글자가 나오기까지<br>(중앙값, 최대 1.86초)</div></div>
|
||||
<div class="stat"><div class="v">1.8<small>%</small></div><div class="l">파인튜닝 모델 CER<br>(기본 모델 4.8%, 사전 없이)</div></div>
|
||||
<div class="stat"><div class="v">3<small>/3</small></div><div class="l">Windows 롤 채팅 OCR<br>예시 3줄 모두 인식</div></div>
|
||||
</div>
|
||||
<table>
|
||||
<tr><th style="width:23%">단계</th><th>만든 것</th><th style="width:27%">확인 방법 · 결과</th></tr>
|
||||
<tr><td><b>M0</b> 기술 검증</td><td>구조 설계, STT 워커(faster-whisper), 앱 코어, 게임 PC 진단 기능</td><td>DAVE 음성 연결 1.06초, 음량 정규화·잡음 판정·사전 교정 단위 테스트</td></tr>
|
||||
<tr><td><b>M1</b> 녹음 + STT 기본</td><td>따라가기·명령 참여, TTS 안내, 유저별 Ogg 녹음, 대기열 STT, /녹음제외</td><td>실제 음성 E2E 통과 (3문장 → 3발화, 녹음 제외 즉시 반영)</td></tr>
|
||||
<tr><td><b>M2</b> 사이트 서버 · 사이트 v1</td><td>디스코드 로그인(서버 멤버만), 게임 PC 등록·중계·잠금, 타임라인·검색·실시간·따라 읽기</td><td>gvr.tkrmagid.kr 배포, 서버 통합 테스트, 실서버 WebSocket 연결</td></tr>
|
||||
<tr><td><b>M3</b> 발로란트 연동</td><td>경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과, 경기 상세(미니맵·킬피드·스코어보드)</td><td>가짜 Riot 서버 테스트, 22라운드 전체 스택 시연</td></tr>
|
||||
<tr><td><b>M4</b> 롤 연동 · 채팅 OCR</td><td>게임 클라이언트 API 이벤트, LCU 결과·타임라인, 채팅 OCR·r3dlog, 롤 경기 상세</td><td>Windows 실기: OCR 3/3, Windows 전용 문제 3개 수정</td></tr>
|
||||
<tr><td><b>M5</b> exe · 설정 · 모델</td><td>포터블 exe, 트레이, 설정 창 8탭, 첫 실행 마법사 5단계, GPU 추천·모델 다운로드, DPAPI 암호화</td><td>Windows 빌드·실행 스모크 전 항목 통과</td></tr>
|
||||
<tr><td><b>M6</b> 단어사전 · UI/UX</td><td>기본 사전 약 2,000단어 + 교정 규칙, 사이트 사전 화면, 게임 패치 이름 자동 추가, 테마·효과음</td><td>사전 적용 시 CER 4.8% → 3.9%</td></tr>
|
||||
<tr><td><b>M7</b> 실사용 테스트</td><td>GPU 실음성 시험, 모델별 인식률·속도 측정, 시험 중 찾은 문제 수정</td><td>실음성 CER 3.6%, 지연 1.05초</td></tr>
|
||||
<tr><td><b>M8</b> 파인튜닝</td><td>교정 문장 + 합성 음성 LoRA 학습 → 오류율 비교 → 자동 교체·되돌리기</td><td>GPU 학습 6.5분, CER 4.8% → 1.8%</td></tr>
|
||||
</table>
|
||||
<div class="callout warn"><b class="t">게임 PC에서만 확인할 수 있는 것</b>
|
||||
실제 발로란트·롤 경기 중 게임 API 응답, 게임 프레임 영향, RTX 5070 Ti CUDA DLL 적재는 이 서버나 VM에서 잴 수 없습니다. 모두 게임 PC 앱의 <b>진단</b> 탭에서 버튼 하나로 확인하도록 만들어 두었습니다(10장).</div>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<h2><span class="num">2</span>전체 구조</h2>
|
||||
<table>
|
||||
<tr><th style="width:22%">구성</th><th>역할</th><th style="width:28%">기술</th></tr>
|
||||
<tr><td><b>게임 PC 앱</b><br><span class="small">GameVoiceRecorder.exe</span></td><td>디스코드 봇(음성 수신·TTS 안내), 녹음 저장, STT 대기열, 게임 연동(발로란트·롤), 기록 DB, 설정 창·트레이, 사이트 중계 연결. 녹음과 기록은 게임 PC에만 저장</td><td>Electron + Node.js(TypeScript), discord.js + @discordjs/voice(DAVE), SQLite(FTS5)</td></tr>
|
||||
<tr><td><b>STT 워커</b></td><td>음량 정규화 → VAD 잡음 판정 → Whisper 변환 → 사전 교정, 채팅 OCR, r3dlog 읽기, 모델·CUDA 런타임 다운로드</td><td>Python(PyInstaller exe), faster-whisper(CTranslate2), Windows OCR</td></tr>
|
||||
<tr><td><b>파인튜닝</b></td><td>교정 문장 + 합성 음성으로 LoRA 학습, 학습 전후 CER 비교, CTranslate2로 내보내기</td><td>PyTorch, PEFT, Edge TTS (별도 환경)</td></tr>
|
||||
<tr><td><b>사이트 서버</b></td><td>디스코드 로그인(서버 멤버 확인), 게임 PC 등록·연결 확인·잠금, 기록·음성 중계(저장하지 않음)</td><td>Fastify, WebSocket, Docker(.5 서버)</td></tr>
|
||||
<tr><td><b>사이트 화면</b></td><td>타임라인·검색·필터·따라 읽기, 경기 상세(발로란트·롤), 유저별 기록, 단어사전, 교정</td><td>React + Vite</td></tr>
|
||||
</table>
|
||||
<h3>음성 한 마디가 사이트에 나오기까지</h3>
|
||||
<ol>
|
||||
<li>겜녹이 봇이 음성채널에 들어가 사람마다 따로 Opus 패킷을 받아, 말이 끊기면 발화 하나로 묶어 Ogg로 저장(재인코딩 없음)</li>
|
||||
<li>실시간 모델(large-v3-turbo)이 바로 변환하고, 경기가 끝나면 정밀 모델(large-v3)이 다시 변환(GPU 여유에 따라)</li>
|
||||
<li>사람마다 음량을 맞추고, 말소리가 없으면 Whisper를 돌리지 않음(환각 방지). 사전 핫워드·교정 규칙 적용</li>
|
||||
<li>게임 이벤트(킬·라운드·채팅)와 같은 시간축에 저장 → 사이트 서버를 거쳐 실시간으로 표시</li>
|
||||
<li>음성 파일은 7일 뒤 자동 삭제. 글자와 경기 기록은 남음</li>
|
||||
</ol>
|
||||
<h3>코드 규모와 자동 테스트</h3>
|
||||
<table>
|
||||
<tr><th>부분</th><th class="num">코드 줄 수</th><th>자동 테스트 (마지막 실행)</th></tr>
|
||||
<tr><td>앱 (코어 + 설정 창)</td><td class="num">약 8,800</td><td><code>app: npm test</code> 9개 통과, 타입 검사 오류 0</td></tr>
|
||||
<tr><td>STT 워커 + 파인튜닝</td><td class="num">약 2,900</td><td><code>worker: pytest</code> 42개 통과 (Windows 41개 통과, 1개는 리눅스 전용이라 건너뜀)</td></tr>
|
||||
<tr><td>사이트 서버</td><td class="num">약 730</td><td><code>site/server: npm test</code> 통합 테스트 통과</td></tr>
|
||||
<tr><td>사이트 화면</td><td class="num">약 4,300</td><td>타입 검사·빌드 오류 0, 헤드리스 동작 확인 18개</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<h2><span class="num">3</span>M0 · M1 — 기술 검증, 녹음 + STT</h2>
|
||||
<ul>
|
||||
<li>디스코드 DAVE(종단 간 암호화) 음성 연결: 겜녹이 봇이 1.06초 만에 연결, 유저별 음성 수신 확인</li>
|
||||
<li>음량 정규화(-30dB 작은 목소리 +24dB 보정 후 같은 문장 인식), 잡음 판정(키보드·백색 잡음·무음 → Whisper 생략)</li>
|
||||
<li>게임 PC 진단 기능: GPU·STT 속도·발로란트/롤 로컬 API·LCU 타임라인·채팅 OCR·r3dlog를 버튼 하나로 점검</li>
|
||||
</ul>
|
||||
<h3>실제 디스코드 음성 E2E (M1)</h3>
|
||||
<p>F&L 서버 "음성" 채널에서 테스트봇이 한국어 문장을 말하고, 겜녹이가 따라 들어와 녹음·변환했습니다.</p>
|
||||
<pre>겜녹이 따라 들어옴 (follow): 음성
|
||||
[테스트봇] 3.9s realtime: 레이즈 공 빠졌어 비사이트로 태하자
|
||||
[테스트봇] 3.4s realtime: 오늘 저녁에 치킨 먹을래
|
||||
[테스트봇] 2.6s realtime: 나우퍼레이터 살게
|
||||
녹음 제외 후 새 발화: 0개 (0 이어야 함)
|
||||
VOICE E2E PASS</pre>
|
||||
<p class="small">M1은 CPU small 모델이라 틀린 글자가 있습니다. 같은 시험을 GPU large-v3-turbo로 다시 한 결과는 M7(8장)에 있습니다.</p>
|
||||
|
||||
<h2 style="margin-top:18px"><span class="num">4</span>M2 · M3 — 사이트, 발로란트 연동</h2>
|
||||
<ul>
|
||||
<li>https://gvr.tkrmagid.kr: 디스코드 로그인(M&L 서버 멤버만), 게임 PC가 연결되어 있을 때만 기록을 보여 주고 끊기면 2.5초 안에 잠금</li>
|
||||
<li>타임라인: 무한 스크롤, 유저·게임·경기 필터, 검색, 실시간 추가, 재생 중 단어 강조(따라 읽기), 이어듣기, 단축키, 문장 교정</li>
|
||||
<li>발로란트: 경기 감지 → 라운드·킬·채팅 → match-details 적용. 시간은 <code>R7 · 0:38</code>(라운드 시간)과 경기 경과 시간을 같이 표시</li>
|
||||
</ul>
|
||||
<figure><img src="../../dev/screens/real-match-valorant.png"><figcaption><b>발로란트 경기 상세</b> — 라운드 띠, 미니맵 킬 위치(게임 좌표 → 지도 변환), 라운드 대화 + 킬피드, 스코어보드(ACS), 라운드별 크레딧. 실제 코어·STT 워커·사이트 서버 전체 스택에 22라운드 데이터와 TTS 대화를 넣어 촬영</figcaption></figure>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<div style="display:grid;grid-template-columns:3.1fr 1fr;gap:10px;align-items:start">
|
||||
<figure><img src="../../dev/screens/real-timeline.png"><figcaption><b>타임라인</b> — 대화와 게임 이벤트가 한 시간축에</figcaption></figure>
|
||||
<figure><img src="../../dev/screens/real-mobile.png"><figcaption><b>휴대폰 화면</b></figcaption></figure>
|
||||
</div>
|
||||
<h2><span class="num">5</span>M4 — 롤 연동 · 채팅 OCR</h2>
|
||||
<ul>
|
||||
<li>게임 클라이언트 API(2999): 킬·용·전령·바론·포탑 이벤트, 게임 시간 표시. LCU: 챔피언 선택 채팅, 경기 결과·타임라인(킬 위치·골드 차이)</li>
|
||||
<li>인게임 채팅: r3dlog에 채팅이 남으면 로그를 읽고, 없으면 화면 일부를 Windows 한국어 OCR로 읽음(같은 줄 중복 제거)</li>
|
||||
</ul>
|
||||
<figure><img src="../../dev/screens/real-match-lol.png"><figcaption><b>롤 경기 상세</b> — 킬 위치, 골드 차이 그래프, 오브젝트, 스코어보드</figcaption></figure>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<h3>Windows 실기 확인 (win-ci Windows 11 VM)</h3>
|
||||
<table>
|
||||
<tr><th>항목</th><th>결과</th></tr>
|
||||
<tr><td>롤 채팅 OCR (Windows 한국어 OCR)</td><td class="good">예시 3줄 중 3줄 인식 — <code>[팀] 민수 (아리): 드래곤 가자</code>, <code>[전체] 상대1 (가렌): gg</code>, <code>[팀] 지우 (리 신): 바텀 갱 간다</code></td></tr>
|
||||
<tr><td>r3dlog 채팅 읽기</td><td class="good">2줄 읽음 (게임 시간·팀/전체·보낸 사람·챔피언·내용)</td></tr>
|
||||
<tr><td>STT (CPU tiny)</td><td class="good">한국어 변환 정상, 워커 pytest 41개 통과</td></tr>
|
||||
</table>
|
||||
<h3>Windows에서만 나던 문제 3개 — 원인을 찾아 고침</h3>
|
||||
<table>
|
||||
<tr><th style="width:26%">증상</th><th>원인 (확인 방법)</th><th style="width:30%">수정</th></tr>
|
||||
<tr><td>OCR을 한 번 쓴 뒤 첫 변환에서 워커가 조용히 종료, PyInstaller 분석 실패</td><td>pywinrt가 넣어 둔 오래된 <code>msvcp140.dll</code>(14.29)이 먼저 올라가면 onnxruntime이 <code>0xC0000005</code>로 죽음 (불러오는 순서별 시험)</td><td>onnxruntime·ctranslate2를 먼저 적재, 빌드 전 winrt의 msvcp140 삭제</td></tr>
|
||||
<tr><td>첫 음성 변환이 응답 없이 영원히 멈춤 (pytest 373초 후 실패)</td><td>요청 처리 스레드에서 scipy(OpenBLAS DLL)를 처음 불러올 때 멈춤. faulthandler로 스택을 찍어 <code>scipy.linalg.blas</code> 적재 중임을 확인, 주 스레드에서 먼저 불러오면 정상인 것도 확인</td><td>워커 시작 때 주 스레드에서 scipy·pyloudnorm 미리 적재 → pytest 8초</td></tr>
|
||||
<tr><td>파인튜닝 요청이 120초 응답 없음</td><td>워커가 띄운 자식 프로세스가 워커의 요청 파이프(stdin)를 물려받아, 시작 단계에서 주 스레드의 읽기 대기와 엉켜 멈춤</td><td>자식 프로세스에 stdin을 넘기지 않음</td></tr>
|
||||
</table>
|
||||
|
||||
<h2 style="margin-top:16px"><span class="num">6</span>M5 — 포터블 exe · 설정 · 모델</h2>
|
||||
<table>
|
||||
<tr><th>결과물 (Windows 빌드)</th><th class="num">크기</th><th>설명</th></tr>
|
||||
<tr><td><code>GameVoiceRecorder-1.0.0-portable.exe</code></td><td class="num">168 MB</td><td>파일 하나로 실행 (실행할 때 임시 폴더에 풀림)</td></tr>
|
||||
<tr><td><code>GameVoiceRecorder-1.0.0-win-x64.zip</code></td><td class="num">259 MB</td><td>폴더 포터블 (권장: 풀 필요가 없어 시작이 빠름)</td></tr>
|
||||
<tr><td>내장 STT 워커 (PyInstaller)</td><td class="num">325 MB</td><td>zip·exe 안에 포함. 모델(1.5~2.9GB)과 CUDA 런타임(1.2GB)은 첫 실행 때 다운로드</td></tr>
|
||||
</table>
|
||||
<p><b>exe 실행 확인</b> (<code>GameVoiceRecorder.exe --smoke</code>): 설정 암호화 DPAPI 왕복 ✓ · 워커 기동 ✓ · GPU 감지(VM은 GPU가 없어 CPU 경고) ✓ · 사전 2,026단어 ✓ · 설정 창 화면 ✓ · 트레이 ✓. 워커 exe 단독 실행도 OCR 3/3·STT 통과.</p>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<div class="grid2">
|
||||
<figure><img src="../../../app/src/renderer/screenshots/wizard-3.png"><figcaption><b>첫 실행 마법사 3단계</b> — GPU VRAM을 보고 실시간/정밀 모델 추천, 다운로드(이어받기)</figcaption></figure>
|
||||
<figure><img src="../../../app/src/renderer/screenshots/settings-stt.png"><figcaption><b>설정 창 · STT 탭</b> — 모델·정밀도·잡음 민감도·음량</figcaption></figure>
|
||||
<figure><img src="../../../app/src/renderer/screenshots/settings-games.png"><figcaption><b>설정 창 · 게임 탭</b> — 발로란트·롤 연동, 채팅 OCR 영역</figcaption></figure>
|
||||
<figure><img src="../../../app/src/renderer/screenshots/settings-diag.png"><figcaption><b>설정 창 · 진단 탭</b> — 게임 PC 점검</figcaption></figure>
|
||||
</div>
|
||||
<p class="small">설정 창 화면은 가짜 데이터(RTX 5070 Ti 가정)로 띄워 찍은 것입니다. 실제 exe에서 같은 화면이 뜨는지는 Windows 스모크의 "설정 창 화면 ✓"로 확인했습니다.</p>
|
||||
|
||||
<h2 style="margin-top:14px"><span class="num">7</span>M6 — 단어사전 · UI/UX</h2>
|
||||
<ul>
|
||||
<li>기본 사전 8묶음 약 2,000단어: 일상 93 · 게임 공통 104 · 롤 412 · 롤 스킬 850 · 20대 말투 69 · 대학생 76 · 발로란트 293 · 발로란트 콜아웃 101, 교정 규칙 28개</li>
|
||||
<li>경기마다 그 경기에 나온 요원·챔피언·선수 이름을 핫워드 앞쪽에 넣음. 게임 패치 데이터로 새 이름 자동 추가</li>
|
||||
<li>사이트에서 문장을 고치면 바뀐 단어가 교정 규칙으로 자동 추가되고, 같은 문장은 파인튜닝 학습 데이터가 됨</li>
|
||||
<li>발로란트(빨강) × 롤(금색) 테마, 효과음(Web Audio로 합성해 음원 파일 없음, 종류별로 끄고 켬), 애니메이션 11종, 모션 줄이기</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<figure><img src="../../dev/screens/real-dictionary.png"><figcaption><b>사이트 단어사전 화면</b> — 묶음별 단어 수, 자주 쓰는 말·별명 추가, 교정 규칙(잘못 나온 말 → 바른 말)</figcaption></figure>
|
||||
|
||||
<h2 style="margin-top:12px"><span class="num">8</span>M7 — 실사용 테스트 (GPU)</h2>
|
||||
<p>이 서버 GPU(RTX 5050 8GB, 다른 서비스가 3GB 사용 중)에서 게임 PC와 같은 GPU 방식(CUDA float16)으로 측정했습니다.</p>
|
||||
<h3>실제 디스코드 음성 28문장</h3>
|
||||
<pre>F&L "음성" 채널 · 테스트봇이 시연 대화 28문장을 연달아 말함 → 겜녹이 따라 들어와 녹음 → STT
|
||||
발화 28개 (말한 문장 28개) · 모델 large-v3-turbo (cuda) · 지연 중앙값 1.05s · 최대 1.86s
|
||||
CER 3.6% · 완전 일치 21/28
|
||||
녹음 제외 후 새 발화: 0개 (0 이어야 함)
|
||||
겜녹이 퇴장: true
|
||||
VOICE E2E PASS</pre>
|
||||
<ul>
|
||||
<li>28문장을 28개 발화로 정확히 나눔. 지연은 말이 끝난 뒤 사이트에 글자가 생기기까지 걸린 시간(첫 발화 1.86초는 모델 첫 실행)</li>
|
||||
<li>시험 중 발견·수정: 시험용 봇만 있는 방을 "빈 방"으로 보고 30초 뒤 나가던 문제(시험 모드에서 봇도 참가자로 셈)</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<h3>모델별 인식률·속도 (시연 대화 28문장)</h3>
|
||||
<table>
|
||||
<tr><th>모델 (CUDA float16)</th><th class="num">사전 없음 CER</th><th class="num">사전 적용 CER</th><th class="num">완전 일치</th><th class="num">문장당 변환</th><th class="num">적재</th></tr>
|
||||
<tr><td>large-v3-turbo (실시간 기본)</td><td class="num">4.8%</td><td class="num good">3.9%</td><td class="num">21/28</td><td class="num">0.31초</td><td class="num">4초</td></tr>
|
||||
<tr><td>large-v3 (정밀)</td><td class="num">4.3%</td><td class="num">4.8%</td><td class="num">19/28</td><td class="num">0.48초</td><td class="num">6초</td></tr>
|
||||
<tr><td>small</td><td class="num">10.9%</td><td class="num">8.1%</td><td class="num">17/28</td><td class="num">0.16초</td><td class="num">1초 미만</td></tr>
|
||||
</table>
|
||||
<ul>
|
||||
<li>남은 오류는 대부분 소리가 비슷한 말입니다: "대시→데스", "칠게→7개", "깔았어→깔아서". 교정 사전과 파인튜닝이 맡을 부분입니다</li>
|
||||
<li>짧은 게임 대화에서는 large-v3가 turbo보다 낫지 않았습니다. 그래서 실시간은 turbo, 정밀 변환은 경기가 끝난 뒤에 하는 지금 기본값을 유지합니다</li>
|
||||
</ul>
|
||||
|
||||
<h2 style="margin-top:16px"><span class="num">9</span>M8 — 파인튜닝</h2>
|
||||
<p>앱의 실제 학습 경로를 그대로 GPU에서 돌렸습니다: 사이트 교정 → 학습 데이터 → 학습 → 학습 전후 오류율 비교 → 좋아졌을 때만 모델 교체 → 되돌리기. 결과는 <code>FINETUNE E2E PASS</code>였습니다.</p>
|
||||
<table>
|
||||
<tr><th style="width:24%">항목</th><th>내용</th></tr>
|
||||
<tr><td>학습 데이터</td><td>사이트에서 고친 문장 8개 + 사전 단어로 만든 문장을 Edge TTS 3개 음성으로 합성한 300개(속도·피치 변화, 30% 배경 잡음) → 학습 281 / 검증 27</td></tr>
|
||||
<tr><td>학습</td><td>openai/whisper-large-v3-turbo + LoRA(r=32), 3에폭 54스텝, <b>394초</b>, 최대 VRAM <b>2.7GB</b></td></tr>
|
||||
<tr><td>검증 세트 CER</td><td>9.7% → <b>8.3%</b> → 자동으로 새 모델 적용(CTranslate2 float16, 1.6GB) → 새 모델로 변환 확인 → 이전 모델로 되돌리기 확인</td></tr>
|
||||
</table>
|
||||
<div class="bars">
|
||||
<div class="vt">시연 대화 28문장 CER (낮을수록 좋음)</div>
|
||||
<div class="vs">학습에 쓴 8문장을 뺀 20문장 결과도 따로 표시</div>
|
||||
<div class="bar"><div class="lab">기본 turbo · 사전 없음</div><div class="track"><div class="fill" style="width:87%;background:#9aa6b5"></div></div><div class="val">4.8%</div></div>
|
||||
<div class="bar"><div class="lab">기본 turbo · 사전 적용</div><div class="track"><div class="fill" style="width:71%;background:#9aa6b5"></div></div><div class="val">3.9%</div></div>
|
||||
<div class="bar"><div class="lab"><b>파인튜닝</b> · 사전 없음</div><div class="track"><div class="fill" style="width:33%;background:#0fb5ae"></div></div><div class="val">1.8%</div></div>
|
||||
<div class="bar"><div class="lab"><b>파인튜닝</b> · 사전 적용</div><div class="track"><div class="fill" style="width:36%;background:#0fb5ae"></div></div><div class="val">2.0%</div></div>
|
||||
<div class="bar"><div class="lab">학습에 안 쓴 20문장: 기본 → 파인튜닝</div><div class="track"><div class="fill" style="width:47%;background:#c8aa6e"></div></div><div class="val">2.6→1.8</div></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<h3>학습하면서 찾아 고친 문제 2개</h3>
|
||||
<table>
|
||||
<tr><th style="width:26%">증상</th><th>원인</th><th style="width:32%">수정</th></tr>
|
||||
<tr><td>첫 학습이 GPU 메모리 부족으로 실패</td><td>바뀌지 않는 원본 가중치까지 fp32로 올림(3.2GB). 이 서버 GPU는 다른 서비스가 3GB를 씀</td><td>원본은 bf16, 학습하는 LoRA만 fp32 → VRAM 절반(최대 2.7GB)</td></tr>
|
||||
<tr><td>검증 CER은 좋아졌는데(10.2→7.9%) 실제 변환에서 문장 끝에 "끝", "댕댕댕", "끈의 주인공" 같은 말을 지어냄 (사전 없음 CER 4.8% → 21.8%)</td><td>타임스탬프 없는 라벨로만 학습해서, 앱(faster-whisper)이 쓰는 타임스탬프 모드에서 문장을 끝맺는 법을 잊음. 검증도 타임스탬프 없이 해서 걸러내지 못함</td><td>라벨 절반을 <code><|0.00|> 문장 <|말끝|></code> 형식으로, 검증도 타임스탬프 모드로 → 사전 없이도 1.8%</td></tr>
|
||||
</table>
|
||||
<div class="callout info"><b class="t">해석할 때 주의할 점</b>
|
||||
합성 학습 음성과 시연 대화가 같은 TTS 엔진이라, 실제 사람 목소리에서는 개선 폭이 이보다 작을 수 있습니다. 계획대로 실사용 교정 데이터가 2주쯤 쌓이면 게임 PC(RTX 5070 Ti)에서 다시 학습해 비교합니다. 앱은 오류율이 나아질 때만 새 모델로 바꾸고, 언제든 되돌릴 수 있습니다.</div>
|
||||
|
||||
<h2 style="margin-top:16px"><span class="num">10</span>게임 PC에서 처음 할 일</h2>
|
||||
<ol>
|
||||
<li><code>GameVoiceRecorder-1.0.0-win-x64.zip</code>을 원하는 폴더에 풀고 <code>GameVoiceRecorder.exe</code> 실행 → 첫 실행 마법사(봇 토큰 → 게임 선택 → 모델 다운로드 → 사전 → 사이트 등록)</li>
|
||||
<li>설정 창 <b>진단</b> 탭 → 전체 진단: RTX 5070 Ti STT 속도·VRAM, CUDA 런타임, 발로란트·롤 로컬 API, LCU 타임라인, 채팅 OCR, r3dlog 채팅</li>
|
||||
<li>사이트 등록 코드를 앱에 넣어 https://gvr.tkrmagid.kr 연결 → 친구들과 디스코드 음성방에서 발로란트·롤 한 판씩</li>
|
||||
<li>사이트 타임라인에서 틀린 문장을 고치면 교정 사전과 다음 파인튜닝 데이터가 됨</li>
|
||||
</ol>
|
||||
<h3>아직 확인하지 못한 것</h3>
|
||||
<table>
|
||||
<tr><th>항목</th><th>이유</th><th>확인 방법</th></tr>
|
||||
<tr><td>실제 경기 중 발로란트·롤 API 응답</td><td>개발 서버·VM에서 게임 실행 불가 (실제 API와 같은 구조의 가짜 서버로 전 과정 테스트함)</td><td>진단 탭 + 실제 경기 1판</td></tr>
|
||||
<tr><td>게임 프레임 영향</td><td>게임 PC에서만 측정 가능</td><td>경기 중 프레임 비교. 정밀 변환은 경기 후로 미루는 것이 기본값</td></tr>
|
||||
<tr><td>Windows CUDA DLL 적재 (RTX 5070 Ti)</td><td>VM에 GPU 없음 (GPU 경로 자체는 이 서버 RTX 5050에서 확인)</td><td>진단 탭 "STT 속도"</td></tr>
|
||||
<tr><td>실제 사람 목소리 인식률</td><td>시험은 TTS 목소리로 함</td><td>실사용 2주 후 교정률·CER</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section class="page">
|
||||
<h2><span class="num">11</span>부록 — 확인 명령과 커밋</h2>
|
||||
<h3>다시 돌려 볼 수 있는 확인 명령 (저장소 루트 기준)</h3>
|
||||
<pre># 자동 테스트
|
||||
cd app && npm test && npx tsc --noEmit -p . # 앱 9개
|
||||
cd worker && .venv/bin/python -m pytest -q # 워커 42개
|
||||
cd site/server && npm test # 사이트 서버 통합
|
||||
# 실제 디스코드 음성 (F&L "음성" 채널, GPU)
|
||||
GVR_E2E_SET=demo GVR_E2E_DEVICE=cuda GVR_E2E_MODEL=<large-v3-turbo 폴더> \
|
||||
node --import tsx app/scripts/voice-e2e.mts 789051930965835810 934817907479810048
|
||||
# 모델별 인식률 (GPU)
|
||||
GVR_EVAL_DEVICE=cuda node --import tsx app/scripts/stt-eval.mts <모델 폴더> large-v3-turbo large-v3 small
|
||||
# 파인튜닝 전체 경로 (GPU)
|
||||
GVR_FT_BASE=openai/whisper-large-v3-turbo GVR_FT_STEPS=0 GVR_FT_SYNTH=300 node --import tsx app/scripts/finetune-e2e.mts
|
||||
# Windows 검증·exe 빌드 (win-ci VM)
|
||||
tools/win-ci/run.sh full <커밋></pre>
|
||||
<h3>단계별 커밋 (Gitea main)</h3>
|
||||
<table>
|
||||
<tr><th style="width:12%">커밋</th><th>내용</th></tr>
|
||||
<tr><td><code>7c9146c</code></td><td>M0 기술 검증 — 구조 설계, STT 워커, 앱 코어, 게임 PC 진단</td></tr>
|
||||
<tr><td><code>2745af8</code></td><td>M1 녹음 + STT 기본 — 실제 디스코드 음성 E2E 통과</td></tr>
|
||||
<tr><td><code>9abda88</code></td><td>M2 사이트 서버 · 사이트 v1 — gvr.tkrmagid.kr 배포</td></tr>
|
||||
<tr><td><code>5222b3e</code></td><td>M3 발로란트 연동 — 전체 스택 시연·테스트, 핫워드 되풀이 방지</td></tr>
|
||||
<tr><td><code>827e9d8</code> · <code>e6723a4</code></td><td>M4 Windows 워커 크래시(msvcp140)·첫 변환 멈춤(scipy) 수정</td></tr>
|
||||
<tr><td><code>5f04ccd</code> · <code>ae2af63</code> · <code>8f44f22</code></td><td>M5 포터블 exe(트레이·설정 창·마법사), Windows 자식 프로세스 멈춤·빌드 경로 수정</td></tr>
|
||||
<tr><td><code>47aeef9</code></td><td>M6 단어사전 화면, 사이트 재배포</td></tr>
|
||||
<tr><td><code>f26f408</code></td><td>M4·M5 완료 기록 (Windows 실기 확인·exe 빌드)</td></tr>
|
||||
<tr><td><code>c32236c</code></td><td>M7 GPU 실사용 시험 (실제 디스코드 음성 28문장, 모델별 인식률·속도)</td></tr>
|
||||
<tr><td><code>24585e3</code></td><td>M8 GPU 파인튜닝 (large-v3-turbo LoRA, CER 4.8% → 1.8%)</td></tr>
|
||||
</table>
|
||||
<p class="small">자세한 기록: <code>docs/dev/test-results.md</code>(단계별 테스트), <code>docs/dev/ARCHITECTURE.md</code>(구조·인터페이스), <code>docs/gemnoki-project-plan.pdf</code>(설명서·계획서).</p>
|
||||
</section>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -72,7 +72,7 @@ try {
|
||||
if ($Phase -eq 'debug') {
|
||||
# 원인 조사용: worker/scripts/win_debug.py 만 돌린다 (venv 는 이전 실행 것을 그대로 씀)
|
||||
$r['debug'] = Step 'debug' {
|
||||
& $py -X faulthandler worker\scripts\win_debug.py
|
||||
& $py -X faulthandler worker\scripts\win_debug.py protocol
|
||||
"exit $LASTEXITCODE"
|
||||
}
|
||||
$sum = Join-Path $OutDir 'summary.log'
|
||||
@@ -129,9 +129,9 @@ try {
|
||||
if ($Phase -eq 'full') {
|
||||
$r['app_build'] = Step 'app_build' {
|
||||
Push-Location (Join-Path $Repo 'app')
|
||||
& npm ci --no-audit --no-fund
|
||||
& npm.cmd ci --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { Pop-Location; throw "npm ci exit $LASTEXITCODE" }
|
||||
& npm run dist:win
|
||||
& npm.cmd run dist:win
|
||||
$c = $LASTEXITCODE
|
||||
Pop-Location
|
||||
if ($c -ne 0) { throw "electron-builder exit $c" }
|
||||
@@ -146,7 +146,7 @@ try {
|
||||
if ($p.ExitCode -ne 0) { throw "app smoke exit $($p.ExitCode)" }
|
||||
}
|
||||
if ($r['app_build'] -and $r['app_smoke']) {
|
||||
foreach ($f in Get-ChildItem app\release -File -Include *.exe, *.zip) { Send-Artifact $f.Name $f.FullName }
|
||||
foreach ($f in Get-ChildItem app\release\* -File -Include *.exe, *.zip) { Send-Artifact $f.Name $f.FullName }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -78,6 +78,9 @@ uv pip install --python .venv-ft/bin/python -r gvr_worker/finetune/requirements.
|
||||
- 단계: `synth.py`(edge-tts SunHi/InJoon/Hyunsu, 속도·피치 변화, 30% 확률 배경 잡음) → `build_dataset.py`(문장 해시로 고정 검증 세트) →
|
||||
`evaluate.py`(학습 전 CER) → `train_lora.py`(LoRA r=32, q/k/v/out_proj, CUDA bf16 autocast / CPU fp32, gradient checkpointing) →
|
||||
`evaluate.py`(학습 후 CER) → `export_ct2.py`(병합 → CTranslate2 float16 → `models/<이름>-ft-<YYYYMMDD>/` + `gvr-model.json`).
|
||||
- GPU 에서는 얼려 둔 원본 가중치를 bf16 으로 올린다(LoRA 만 fp32). large-v3-turbo, 배치 4 기준 최대 VRAM 2.7GB.
|
||||
- 라벨의 절반은 `<|0.00|> 문장 <|말끝|>` 타임스탬프 형식이다. 앱은 타임스탬프 모드로 변환하므로, `<|notimestamps|>` 로만 학습하면
|
||||
끝맺음을 잊고 문장 뒤에 말을 지어낸다(M8 시험 학습에서 확인). `evaluate.py` 도 같은 이유로 타임스탬프 모드로 잰다.
|
||||
- `adopt = cer_after < cer_before` 일 때만 내보낸다(`--export-always` 로 강제). 앱은 `models` 의 `meta` 를 보고 교체/되돌리기.
|
||||
- 중지 파일(기본 `GVR-Data/finetune.stop`)이 있으면 시작하지 않고, 학습 중 생기면 어댑터를 저장하고 `stopped:true` 로 끝난다.
|
||||
- 사용자 교정 jsonl: `{"audio":"<training/xxx.ogg>","text":"<고친 문장>"}`.
|
||||
@@ -91,10 +94,17 @@ CPU 스모크 테스트(openai/whisper-tiny, 합성 30개, `--max-steps 3`)는
|
||||
- r3dlog 채팅 형식은 2024년 이전 보고 기준 추정이다. `r3dlog_check` 로 실제 로그를 확인해야 한다.
|
||||
- 잡음 판정 기준값은 추정치다. 실제 녹음으로 `noise_sensitivity` 와 `noise.py` 임계값을 조정해야 한다.
|
||||
- 정규화 음량은 16kHz 로 디코딩한 신호에서 잰다(48k 원본과 소폭 차이 가능).
|
||||
- CUDA 경로(GPU 추론, cuDNN/cuBLAS DLL 다운로드·로딩)는 이 개발 머신에서 실행하지 않았다(M0 에서 게임 PC 로 확인).
|
||||
- GPU 추론·학습은 개발 서버 RTX 5050(리눅스, CUDA float16)에서 확인했다(M7·M8, `docs/dev/test-results.md`). Windows 의 cuDNN/cuBLAS DLL 다운로드·로딩은 게임 PC 진단으로 확인한다.
|
||||
|
||||
## Windows 주의: pywinrt 의 오래된 MSVC 런타임
|
||||
|
||||
`winrt` 패키지는 `msvcp140.dll` 14.29 를 자기 폴더에 넣어 둔다. 이게 먼저 올라가면 onnxruntime(Silero VAD)이
|
||||
`0xC0000005` 로 프로세스째 죽는다 (win-ci 에서 확인: OCR 을 한 번 쓴 뒤 첫 변환에서 워커가 조용히 종료, PyInstaller 분석도 같은 이유로 실패).
|
||||
대응: ① 워커 시작 때 onnxruntime·ctranslate2 를 먼저 불러온다(`preload_native_runtimes`) ② 빌드 전에 `site-packages/winrt/msvcp140*.dll` 을 지운다(`tools/win-ci/gvr.ps1`).
|
||||
|
||||
## Windows 주의: scipy 는 주 스레드에서 먼저 불러온다
|
||||
|
||||
요청 처리 스레드에서 scipy 를 처음 import 하면 `scipy.linalg.blas`(OpenBLAS DLL) 적재 중에 프로세스가 멈춘다
|
||||
(win-ci 에서 확인: 첫 `transcribe` 의 음량 측정 `pyloudnorm` → `scipy.signal` 에서 응답 없음, faulthandler 스택으로 위치 확인).
|
||||
같은 import 를 시작할 때 주 스레드에서 먼저 하면 정상이라, `preload_native_runtimes` 가 `scipy.linalg/signal/ndimage`, `pyloudnorm` 도 미리 불러온다.
|
||||
`worker/scripts/win_debug.py protocol` 로 다시 확인할 수 있다.
|
||||
|
||||
@@ -43,7 +43,9 @@ def main() -> None:
|
||||
feats = processor.feature_extractor(audios, sampling_rate=16000, return_tensors="np").input_features
|
||||
x = torch.tensor(np.asarray(feats), dtype=dtype, device=model.device)
|
||||
with torch.inference_mode():
|
||||
ids = model.generate(input_features=x, language="ko", task="transcribe", max_new_tokens=128)
|
||||
# 앱과 같은 타임스탬프 모드로 잰다 (그래야 끝맺음을 잊은 모델을 걸러낸다)
|
||||
ids = model.generate(input_features=x, language="ko", task="transcribe", max_new_tokens=128,
|
||||
return_timestamps=True)
|
||||
hyps += [t.strip() for t in processor.batch_decode(ids, skip_special_tokens=True)]
|
||||
refs += [r["text"] for r in chunk]
|
||||
progress(stage, min(i + a.batch, len(rows)), len(rows))
|
||||
|
||||
@@ -20,6 +20,18 @@ import numpy as np
|
||||
from common import emit, load_audio, log, progress, read_jsonl
|
||||
|
||||
MAX_SAMPLES = 30 * 16000
|
||||
TS_PROB = 0.5 # 이 비율만큼은 타임스탬프가 붙은 라벨로 학습한다
|
||||
|
||||
|
||||
def speech_end_s(audio: np.ndarray, sr: int = 16000) -> float:
|
||||
"""끝의 무음을 뺀 말소리 끝 시각(초). 20ms 프레임 RMS 가 최대값 대비 -40dB 이상인 마지막 프레임."""
|
||||
hop = sr // 50
|
||||
n = len(audio) // hop
|
||||
if n == 0:
|
||||
return 0.0
|
||||
rms = np.sqrt(np.mean(audio[: n * hop].reshape(n, hop) ** 2, axis=1))
|
||||
loud = np.nonzero(rms > rms.max() * 0.01)[0]
|
||||
return float((loud[-1] + 1) * hop / sr) if len(loud) else len(audio) / sr
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -51,7 +63,9 @@ def main() -> None:
|
||||
|
||||
processor = WhisperProcessor.from_pretrained(a.base)
|
||||
processor.tokenizer.set_prefix_tokens(language="korean", task="transcribe")
|
||||
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.float32)
|
||||
# GPU(bf16)에서는 얼려 둘 원본 가중치를 bf16 으로 올려 VRAM 을 절반으로 줄인다 (large-v3-turbo: 3.2GB → 1.6GB).
|
||||
# 학습하는 LoRA 가중치만 fp32 로 둔다 (아래). CPU 는 fp32 그대로.
|
||||
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.bfloat16 if bf16 else torch.float32)
|
||||
model.config.use_cache = False
|
||||
model.generation_config.language = "ko"
|
||||
model.generation_config.task = "transcribe"
|
||||
@@ -62,6 +76,9 @@ def main() -> None:
|
||||
r=a.rank, lora_alpha=a.rank * 2, lora_dropout=0.05, bias="none",
|
||||
target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
|
||||
))
|
||||
for p in model.parameters():
|
||||
if p.requires_grad:
|
||||
p.data = p.data.float()
|
||||
model.print_trainable_parameters()
|
||||
model.to(device)
|
||||
|
||||
@@ -70,12 +87,26 @@ def main() -> None:
|
||||
raise SystemExit("학습 데이터가 없습니다")
|
||||
start_id = model.config.decoder_start_token_id
|
||||
|
||||
tok = processor.tokenizer
|
||||
eot = tok.convert_tokens_to_ids("<|endoftext|>")
|
||||
ts_prefix = [tok.convert_tokens_to_ids(t) for t in ("<|ko|>", "<|transcribe|>")]
|
||||
|
||||
def ts_token(t: float) -> int:
|
||||
return tok.convert_tokens_to_ids(f"<|{min(round(t / 0.02) * 0.02, 30.0):.2f}|>")
|
||||
|
||||
def featurize(row: dict) -> tuple[np.ndarray, list[int]]:
|
||||
audio = load_audio(row["audio"])[:MAX_SAMPLES]
|
||||
feats = processor.feature_extractor(audio, sampling_rate=16000, return_tensors="np").input_features[0]
|
||||
labels = processor.tokenizer(row["text"]).input_ids
|
||||
if labels and labels[0] == start_id: # 모델이 decoder_start 를 앞에 붙이므로 뺀다
|
||||
labels = labels[1:]
|
||||
if random.random() < TS_PROB:
|
||||
# 앱(faster-whisper)은 타임스탬프 모드로 변환한다. <|notimestamps|> 라벨로만 학습하면 그 모드에서 끝맺음
|
||||
# (끝 타임스탬프 → endoftext)을 잊어 문장 뒤에 "끝", "댕댕댕" 같은 말을 지어낸다 (시험 학습에서 확인).
|
||||
# 그래서 절반은 <|0.00|> 문장 <|말끝|> 형식으로 학습해 그 능력을 지킨다.
|
||||
text_ids = tok(row["text"], add_special_tokens=False).input_ids
|
||||
labels = [*ts_prefix, ts_token(0.0), *text_ids, ts_token(speech_end_s(audio)), eot]
|
||||
else:
|
||||
labels = tok(row["text"]).input_ids
|
||||
if labels and labels[0] == start_id: # 모델이 decoder_start 를 앞에 붙이므로 뺀다
|
||||
labels = labels[1:]
|
||||
return feats, labels
|
||||
|
||||
def batches():
|
||||
@@ -131,7 +162,8 @@ def main() -> None:
|
||||
processor.save_pretrained(str(out))
|
||||
meta = {"base": a.base, "steps": step, "total": total, "stopped": stopped, "train_samples": len(rows),
|
||||
"last_loss": None if math.isnan(last_loss) else last_loss, "seconds": round(time.time() - t0, 1),
|
||||
"device": str(device), "bf16": bf16}
|
||||
"device": str(device), "bf16": bf16,
|
||||
"peak_vram_mb": round(torch.cuda.max_memory_allocated() / 2**20) if cuda else None}
|
||||
(out / "train_meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
emit({"result": {"adapter": str(out), **meta}})
|
||||
|
||||
|
||||
@@ -68,7 +68,8 @@ def _run_smi(args: list[str]) -> str | None:
|
||||
return None
|
||||
try:
|
||||
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
out = subprocess.run([exe, *args], capture_output=True, text=True, timeout=10, creationflags=flags)
|
||||
out = subprocess.run([exe, *args], stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10,
|
||||
creationflags=flags) # stdin 을 물려주지 않는다 (main.run_finetune 참고)
|
||||
except (OSError, subprocess.TimeoutExpired) as e:
|
||||
log.info("nvidia-smi 실행 실패: %s", e)
|
||||
return None
|
||||
|
||||
@@ -148,7 +148,9 @@ def run_finetune(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
|
||||
elif v not in (None, False):
|
||||
cmd += [flag, str(v)]
|
||||
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
||||
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
# stdin 은 꼭 끊는다. 워커 stdin(요청 파이프)을 물려받으면 Windows 에서 자식의 런타임 초기화(GetFileType)가
|
||||
# 주 스레드의 읽기 대기와 엉켜 자식이 시작조차 못 하고 멈춘다 (win-ci: train 요청 120초 응답 없음).
|
||||
proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace", creationflags=flags, env={**os.environ, "PYTHONIOENCODING": "utf-8"})
|
||||
err_tail: deque[str] = deque(maxlen=30)
|
||||
|
||||
@@ -182,10 +184,14 @@ def preload_native_runtimes() -> None:
|
||||
pywinrt(winrt 패키지)는 오래된 msvcp140.dll(14.29)을 자체 폴더에 넣어 두는데, 이게 먼저 메모리에 올라가면
|
||||
나중에 onnxruntime(Silero VAD)이 0xC0000005 로 프로세스째 죽는다 (Windows 에서 확인: OCR 을 한 번 쓴 뒤
|
||||
첫 변환에서 워커가 조용히 종료). 새 런타임을 쓰는 쪽을 먼저 올리면 같은 이름의 DLL 은 그것을 재사용한다.
|
||||
|
||||
scipy(OpenBLAS DLL)는 주 스레드에서 미리 올린다. 요청 처리 스레드에서 처음 import 하면 Windows 에서
|
||||
scipy.linalg.blas 적재 중에 영원히 멈춘다 (win-ci 에서 확인: 첫 변환의 음량 측정 pyloudnorm → scipy.signal 에서 멈춤,
|
||||
같은 import 를 주 스레드에서 먼저 하면 정상).
|
||||
"""
|
||||
if sys.platform != "win32":
|
||||
return
|
||||
for mod in ("onnxruntime", "ctranslate2"):
|
||||
for mod in ("onnxruntime", "ctranslate2", "scipy.linalg", "scipy.signal", "scipy.ndimage", "pyloudnorm"):
|
||||
try:
|
||||
__import__(mod)
|
||||
except Exception as e: # noqa: BLE001
|
||||
|
||||
@@ -1,18 +1,113 @@
|
||||
"""Windows 워커 크래시 원인 조사 2: winrt 가 자체 msvcp140.dll 을 먼저 올리면 onnxruntime/ctranslate2 가 죽는가."""
|
||||
import glob
|
||||
"""Windows 워커 변환 멈춤 원인 조사 3: 변환 단계를 하나씩 따로 돌려 어디서 멈추는지 본다.
|
||||
|
||||
각 경우를 자식 프로세스로 돌리고, 150초 안에 안 끝나면 faulthandler 로 모든 스레드의 스택을 찍고 죽인다.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sp = os.path.join(sys.prefix, "Lib", "site-packages")
|
||||
for f in glob.glob(os.path.join(sp, "**", "msvcp140*.dll"), recursive=True) + glob.glob(os.path.join(sp, "**", "vcruntime140*.dll"), recursive=True):
|
||||
v = subprocess.run(["powershell", "-NoProfile", "-Command", f"(Get-Item '{f}').VersionInfo.FileVersion"], capture_output=True, text=True).stdout.strip()
|
||||
print("bundled", f.replace(sp, "site-packages"), v, flush=True)
|
||||
for code in [
|
||||
"import winrt.windows.media.ocr; import onnxruntime; print('winrt then ort ok')",
|
||||
"import winrt.windows.media.ocr; import ctranslate2; print('winrt then ct2 ok')",
|
||||
"import onnxruntime, ctranslate2; import winrt.windows.media.ocr; print('ort,ct2 then winrt ok')",
|
||||
"import gvr_worker.ocr as o; import onnxruntime; print('gvr ocr then ort ok')",
|
||||
]:
|
||||
p = subprocess.run([sys.executable, "-X", "faulthandler", "-c", code], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300, cwd=os.path.join(os.path.dirname(__file__), ".."))
|
||||
print(f"--- {code} -> exit {p.returncode} (0x{p.returncode & 0xffffffff:08X})", p.stdout.strip()[-200:], p.stderr.strip()[-600:], flush=True)
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
WORKER = os.path.dirname(HERE)
|
||||
OGG = os.path.join(WORKER, "..", "app", "resources", "diag", "speech_ko.ogg").replace("\\", "/")
|
||||
|
||||
PRE = (
|
||||
"import faulthandler, sys, time\n"
|
||||
"faulthandler.dump_traceback_later(150, exit=True)\n"
|
||||
"T=time.time()\n"
|
||||
"def p(m): print(f'{time.time()-T:6.1f}s {m}', flush=True)\n"
|
||||
)
|
||||
STEPS = (
|
||||
f"from gvr_worker import audio as A\n"
|
||||
f"prep = A.prepare('{OGG}', target_lufs=-18.0, profile_lufs=None, use_denoise=False); p(f'prepare ok {{prep.duration_s}}s')\n"
|
||||
"from gvr_worker.stt import _vad_speech\n"
|
||||
"p(f'vad {_vad_speech(prep.audio)}')\n"
|
||||
"from faster_whisper import WhisperModel\n"
|
||||
"m = WhisperModel('tiny', device='cpu', compute_type='int8', cpu_threads=CT); p('load ok')\n"
|
||||
"segs, _ = m.transcribe(prep.audio, language='ko', beam_size=1, vad_filter=VF, word_timestamps=WT); p('generator')\n"
|
||||
"p('text ' + ''.join(s.text for s in segs))\n"
|
||||
)
|
||||
CASES = {
|
||||
"plain": "CT=0; VF=False; WT=False\n",
|
||||
"vadfilter": "CT=0; VF=True; WT=False\n",
|
||||
"words": "CT=0; VF=False; WT=True\n",
|
||||
"full": "CT=0; VF=True; WT=True\n",
|
||||
"full_1thread": "CT=1; VF=True; WT=True\n",
|
||||
"preload_full": "import onnxruntime, ctranslate2; p('preloaded')\nCT=0; VF=True; WT=True\n",
|
||||
"ct2_first_full": "import ctranslate2; p('ct2 loaded')\nCT=0; VF=True; WT=True\n",
|
||||
}
|
||||
env = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
|
||||
for name, head in (CASES.items() if 'protocol' not in sys.argv else []):
|
||||
code = PRE + head + STEPS
|
||||
try:
|
||||
p = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, encoding="utf-8",
|
||||
errors="replace", timeout=240, cwd=WORKER, env=env)
|
||||
rc = f"{p.returncode} (0x{p.returncode & 0xffffffff:08X})"
|
||||
out, err = p.stdout, p.stderr
|
||||
except subprocess.TimeoutExpired as e:
|
||||
rc, out, err = "TIMEOUT", str(e.stdout or ""), str(e.stderr or "")
|
||||
print(f"===== {name} -> exit {rc}", flush=True)
|
||||
print(out.strip()[-1500:], flush=True)
|
||||
if err.strip():
|
||||
print("--- stderr", flush=True)
|
||||
print(err.strip()[-3500:], flush=True)
|
||||
|
||||
# 실제 워커 프로토콜 그대로 (pytest·win_smoke 와 같은 경로). 멈추면 200초 뒤 모든 스레드 스택을 파일로 남긴다.
|
||||
import json
|
||||
import queue
|
||||
import tempfile
|
||||
import threading
|
||||
|
||||
def run_protocol(name, pre=''):
|
||||
print(f"===== protocol {name}", flush=True)
|
||||
data = tempfile.mkdtemp(prefix="gvr-dbg-")
|
||||
dump = os.path.join(data, "stack.txt")
|
||||
boot = (pre + "import faulthandler, os, runpy, sys\n"
|
||||
"f = open(os.environ['GVR_DUMP'], 'w')\n"
|
||||
"faulthandler.dump_traceback_later(200, exit=True, file=f)\n"
|
||||
"sys.argv = ['gvr_worker']\n"
|
||||
"runpy.run_module('gvr_worker', run_name='__main__')\n")
|
||||
wp = subprocess.Popen([sys.executable, "-c", boot], cwd=WORKER, env={**env, "GVR_DATA_DIR": data, "GVR_DUMP": dump},
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8")
|
||||
q: "queue.Queue[str]" = queue.Queue()
|
||||
errs: list = []
|
||||
threading.Thread(target=lambda: [q.put(l) for l in wp.stdout], daemon=True).start()
|
||||
threading.Thread(target=lambda: [errs.append(l.rstrip()) for l in wp.stderr], daemon=True).start()
|
||||
|
||||
|
||||
def req(rid, op, timeout, **kw):
|
||||
wp.stdin.write(json.dumps({"id": rid, "op": op, **kw}, ensure_ascii=False) + "\n")
|
||||
wp.stdin.flush()
|
||||
while True:
|
||||
line = q.get(timeout=timeout)
|
||||
msg = json.loads(line)
|
||||
if msg.get("id") == rid and "event" not in msg:
|
||||
return msg
|
||||
|
||||
|
||||
try:
|
||||
for rid, op, to, kw in [
|
||||
("1", "download", 900, {"target": "model", "name": "tiny"}),
|
||||
("2", "load", 300, {"slot": "realtime", "model": "tiny", "device": "cpu", "compute_type": "int8"}),
|
||||
("3", "transcribe", 260, {"slot": "realtime", "path": OGG, "hotwords": "", "corrections": [], "dictionary": [],
|
||||
"target_lufs": -18, "noise_sensitivity": 0.5, "denoise": False, "profile_lufs": None}),
|
||||
]:
|
||||
r = req(rid, op, to, **kw)
|
||||
print(op, json.dumps(r, ensure_ascii=False)[:400], flush=True)
|
||||
except queue.Empty:
|
||||
print("응답 없음 (멈춤)", flush=True)
|
||||
wp.stdin.close()
|
||||
try:
|
||||
wp.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
wp.kill()
|
||||
wp.wait()
|
||||
print("worker exit", wp.returncode, flush=True)
|
||||
print("--- stderr tail\n" + "\n".join(errs[-30:]), flush=True)
|
||||
if os.path.exists(dump):
|
||||
st = open(dump, encoding="utf-8", errors="replace").read()
|
||||
print("--- stack dump (앞)\n" + st[:5000], flush=True)
|
||||
print("--- stack dump (뒤)\n" + st[-2500:], flush=True)
|
||||
|
||||
|
||||
run_protocol('as-is')
|
||||
run_protocol('scipy-main-thread', 'import pyloudnorm, scipy.signal\n')
|
||||
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -27,7 +28,15 @@ class Worker:
|
||||
env=env, cwd=str(ROOT / "worker"), text=True, encoding="utf-8", bufsize=1)
|
||||
self.seq = 0
|
||||
self.err: list[str] = []
|
||||
self.out: "queue.Queue[str | None]" = queue.Queue()
|
||||
threading.Thread(target=self._drain, daemon=True).start()
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
|
||||
def _read(self) -> None:
|
||||
assert self.p.stdout
|
||||
for line in self.p.stdout:
|
||||
self.out.put(line)
|
||||
self.out.put(None)
|
||||
|
||||
def _drain(self) -> None:
|
||||
assert self.p.stderr
|
||||
@@ -40,15 +49,19 @@ class Worker:
|
||||
assert self.p.stdin and self.p.stdout
|
||||
self.p.stdin.write(json.dumps({"id": rid, "op": op, **kw}, ensure_ascii=False) + "\n")
|
||||
self.p.stdin.flush()
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
line = self.p.stdout.readline()
|
||||
if not line:
|
||||
deadline = time.time() + timeout
|
||||
while True:
|
||||
try:
|
||||
line = self.out.get(timeout=max(deadline - time.time(), 0.1))
|
||||
except queue.Empty:
|
||||
# 워커가 멈춘 경우: 무한 대기하지 않고 죽인 뒤 실패로 끝낸다
|
||||
self.p.kill()
|
||||
raise TimeoutError(f"{op} {timeout}s 응답 없음: " + "\n".join(self.err[-20:])) from None
|
||||
if line is None:
|
||||
raise RuntimeError("worker exited: " + "\n".join(self.err[-20:]))
|
||||
msg = json.loads(line)
|
||||
if msg.get("id") == rid and "event" not in msg:
|
||||
return msg
|
||||
raise TimeoutError(op)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||