M0: 기술 검증 - 구조 설계, STT 워커, 앱 코어, 게임 PC 진단

- docs/dev/ARCHITECTURE.md: 코어-워커-사이트 인터페이스 계약
- worker/: faster-whisper 한국어 STT, 음량 정규화, 4단계 잡음 판정, 사전 교정, GPU 감지·모델/CUDA 다운로드, 롤 채팅 OCR·r3dlog, 파인튜닝 파이프라인 (39 tests)
- app/src/core: 디스코드 DAVE 음성 녹음(Ogg Opus), STT 대기열, 발로란트/롤 로컬 API 어댑터, 타임라인·기록 API, 사이트 중계, 7일 음성 삭제, 진단
- tools/gen-dictionary.mjs: 공식 게임 데이터 기반 기본 단어사전 (1993단어)
- M0 결과: DAVE 연결 1.06s Ready, CPU tiny STT 3.6s→0.31s, 가짜 Riot 서버 통합 테스트 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 01:17:48 +09:00
parent 4596989ba7
commit 7c9146cd2d
95 changed files with 18435 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
node_modules/
dist/
release/
*.log
.gvr-data/
.voice-smoke/
.DS_Store

48
README.md Normal file
View File

@@ -0,0 +1,48 @@
# 겜녹이 (Game Voice Recorder, GVR)
디스코드 음성채널에 봇이 들어가 참가자 각자의 목소리를 따로 녹음하고, 게임 PC의 NVIDIA GPU로 한국어 텍스트(STT)로 바꾼 뒤,
발로란트·리그 오브 레전드 경기 데이터(킬·라운드·오브젝트·인게임 채팅)와 같은 타임라인에 묶어 https://gvr.tkrmagid.kr 에서 보고 듣는 프로그램입니다.
- 게임 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 기술 검증 | DAVE 음성 연결, faster-whisper STT·음량·잡음·사전, 게임 로컬 API 처리, 게임 PC 진단 기능 | ✅ 완료 ([결과](docs/dev/M0-verification.md)) |
| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ⏳ |
| M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ⏳ |
| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ⏳ |
| M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ⏳ |
| M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ⏳ |
| M6 단어사전 · UI/UX | 핫워드·교정 사전, 사이트 교정 반영, 테마·애니메이션·효과음 | ⏳ |
| M7 실사용 테스트 | 통합 테스트, 성능·안정화 | ⏳ |
| M8 파인튜닝 | 교정 데이터 + 합성 음성 LoRA 학습, 오류율 비교 후 교체 | ⏳ |
## 저장소 구조
```
app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript)
worker/ STT 워커 (Python, faster-whisper, OCR, 모델 관리, 파인튜닝)
site/server/ 사이트 서버 (Fastify, Discord OAuth2, 기기 중계)
site/web/ 사이트 화면 (React + Vite)
packages/shared/ 앱·사이트 공통 타입
deploy/ 사이트 서버 배포 (.5 Docker, gvr.tkrmagid.kr)
tools/ 사전 생성기 등
docs/ 설명서·계획서, 개발 문서, 브랜드
assets/ 앱·사이트 아이콘·배너
```
## 개발
```bash
# STT 워커
cd worker && uv venv --python 3.11 .venv && uv pip install --python .venv/bin/python -r requirements-dev.txt
.venv/bin/python -m pytest -q
# 앱 코어 (헤드리스)
cd app && npm install && npm test
npm run core -- --diagnose # 게임 PC 진단 (GPU·STT 속도·Riot API·OCR)
```

5
app/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules/
dist/
release/
.gvr-data/
.voice-smoke/

6230
app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
app/package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "gvr-app",
"productName": "겜녹이",
"version": "1.0.0",
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
"private": true,
"main": "dist/main.cjs",
"author": "tkrmagid",
"license": "UNLICENSED",
"scripts": {
"build": "node build.mjs",
"typecheck": "tsc --noEmit -p .",
"test": "node --import tsx --test test/*.test.ts",
"core": "node --import tsx src/core/cli.ts",
"start": "npm run build && electron .",
"dist:win": "npm run build && electron-builder --win --x64"
},
"dependencies": {
"@discordjs/voice": "^0.19.2",
"better-sqlite3": "^12.11.1",
"discord.js": "^14.27.0",
"fastify": "^5.6.1",
"msedge-tts": "^2.0.3",
"prism-media": "^1.3.5",
"ws": "^8.18.3"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/node": "^22.18.0",
"@types/ws": "^8.18.1",
"electron": "^38.8.6",
"electron-builder": "^26.0.12",
"esbuild": "^0.25.10",
"tsx": "^4.20.6",
"typescript": "^5.9.3"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

View File

@@ -0,0 +1,114 @@
[
{
"from": "레이저",
"to": "레이즈"
},
{
"from": "비 싸이트",
"to": "B 사이트"
},
{
"from": "비싸이트",
"to": "B사이트"
},
{
"from": "에이 싸이트",
"to": "A 사이트"
},
{
"from": "에이싸이트",
"to": "A사이트"
},
{
"from": "씨 싸이트",
"to": "C 사이트"
},
{
"from": "비 사이트",
"to": "B 사이트"
},
{
"from": "에이 사이트",
"to": "A 사이트"
},
{
"from": "로태",
"to": "로테"
},
{
"from": "오퍼래이터",
"to": "오퍼레이터"
},
{
"from": "반달",
"to": "밴달"
},
{
"from": "펜텀",
"to": "팬텀"
},
{
"from": "쉐리프",
"to": "셰리프"
},
{
"from": "세리프",
"to": "셰리프"
},
{
"from": "디퓨저",
"to": "디퓨즈"
},
{
"from": "킬 조이",
"to": "킬조이"
},
{
"from": "브림 스톤",
"to": "브림스톤"
},
{
"from": "아스트로",
"to": "아스트라"
},
{
"from": "클로버",
"to": "클로브"
},
{
"from": "드레곤",
"to": "드래곤"
},
{
"from": "드라곤",
"to": "드래곤"
},
{
"from": "협곡에 전령",
"to": "협곡의 전령"
},
{
"from": "억재기",
"to": "억제기"
},
{
"from": "점명",
"to": "점멸"
},
{
"from": "텔 포",
"to": "텔포"
},
{
"from": "리신",
"to": "리 신"
},
{
"from": "쓰레시",
"to": "쓰레쉬"
},
{
"from": "팀 플",
"to": "팀플"
}
]

File diff suppressed because it is too large Load Diff

Binary file not shown.

16
app/scripts/vc-list.mts Normal file
View File

@@ -0,0 +1,16 @@
import { Client, GatewayIntentBits, ChannelType } from 'discord.js';
import fs from 'node:fs';
const s = JSON.parse(fs.readFileSync('/home/claude/.config/ejclaw/secrets.json', 'utf8')).credentials['discord.com/bot/game-voice-recorder'];
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
c.once('clientReady', async () => {
const g = c.guilds.cache.first()!;
console.log('guild', g.name, g.id, 'members', g.memberCount);
for (const ch of g.channels.cache.values()) {
if (ch.type === ChannelType.GuildVoice) {
const perms = ch.permissionsFor(c.user!)!;
console.log(ch.id, ch.name, 'members:', [...ch.members.values()].map((m) => m.displayName + (m.user.bot ? '(bot)' : '')).join(','), 'connect', perms.has('Connect'), 'speak', perms.has('Speak'));
}
}
await c.destroy();
});
await c.login(s.token);

View File

@@ -0,0 +1,50 @@
// M0 검증: 겜녹이 봇이 DAVE(E2EE) 음성채널에 실제로 붙는지, TTS 안내를 재생하는지, (말하는 사람이 있으면) 유저별 수신이 되는지.
// node --import tsx scripts/voice-smoke.mts <channelId> [seconds]
import { Client, GatewayIntentBits } from 'discord.js';
import { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus, EndBehaviorType } from '@discordjs/voice';
import fs from 'node:fs';
import path from 'node:path';
import { OggOpusWriter } from '../src/core/discord/ogg.ts';
const chId = process.argv[2];
const secs = Number(process.argv[3] || 10);
const outDir = process.env.OUT_DIR || path.resolve('.voice-smoke');
fs.mkdirSync(outDir, { recursive: true });
const token = process.env.GVR_BOT_TOKEN || JSON.parse(fs.readFileSync('/home/claude/.config/ejclaw/secrets.json', 'utf8')).credentials['discord.com/bot/game-voice-recorder'].token;
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
c.once('clientReady', async () => {
const ch: any = await c.channels.fetch(chId);
console.log('channel', ch.name);
const t0 = Date.now();
const conn = joinVoiceChannel({ channelId: ch.id, guildId: ch.guild.id, adapterCreator: ch.guild.voiceAdapterCreator, selfDeaf: false, selfMute: false, daveEncryption: true });
conn.on('stateChange', (o, n) => console.log(`state ${o.status} -> ${n.status} (+${Date.now() - t0}ms)`));
try {
await entersState(conn, VoiceConnectionStatus.Ready, 20000);
} catch (e) {
console.log('FAIL: not ready', e);
process.exit(2);
}
const net: any = (conn.state as any).networking?.state;
console.log('READY in', Date.now() - t0, 'ms; encryption mode:', net?.connectionData?.encryptionMode, '; DAVE protocol:', net?.dave?.protocolVersion ?? net?.dave?.session?.protocolVersion ?? 'n/a');
const player = createAudioPlayer();
conn.subscribe(player);
player.play(createAudioResource(fs.createReadStream(path.resolve('resources/tts/announce-default.webm')), { inputType: StreamType.WebmOpus }));
await entersState(player, AudioPlayerStatus.Playing, 5000).then(() => console.log('TTS playing')).catch(() => console.log('TTS did not start'));
const got: Record<string, number> = {};
conn.receiver.speaking.on('start', (uid) => {
if (conn.receiver.subscriptions.has(uid)) return;
const w = new OggOpusWriter(path.join(outDir, `${uid}-${Date.now()}.ogg`));
const s = conn.receiver.subscribe(uid, { end: { behavior: EndBehaviorType.AfterSilence, duration: 800 } });
s.on('data', (p: Buffer) => {
got[uid] = (got[uid] || 0) + 1;
w.write(p);
});
s.once('end', () => w.close());
});
await new Promise((r) => setTimeout(r, secs * 1000));
console.log('received packets per user:', JSON.stringify(got));
conn.destroy();
await c.destroy();
process.exit(0);
});
await c.login(token);

248
app/src/core/api/server.ts Normal file
View File

@@ -0,0 +1,248 @@
import Fastify, { type FastifyInstance } from 'fastify';
import fs from 'node:fs';
import path from 'node:path';
import type { MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
import type { Store, UserRow } from '../db/db.js';
import type { Dictionary } from '../dict/dictionary.js';
import type { GameManager } from '../games/manager.js';
import type { Settings } from '../settings.js';
import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js';
import type { Bus } from '../util/events.js';
export interface ApiDeps {
store: Store;
timeline: Timeline;
games: GameManager;
dict: Dictionary;
bus: Bus;
settings: () => Settings;
trainingDir: () => string;
overviewExtra: () => { guild: Overview['guild']; recording: Overview['recording'] };
version: string;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
export function toUser(u: UserRow, accounts: { user_id: string; puuid: string; riot_id: string }[]): User {
return {
id: u.id,
name: u.name,
color: u.color,
avatar: u.avatar,
excluded: !!u.excluded,
riot: accounts.filter((a) => a.user_id === u.id).map((a) => ({ puuid: a.puuid, riotId: a.riot_id })),
};
}
/** 사이트에서 쓰는 기록 API (docs/dev/ARCHITECTURE.md 4장). 사이트 서버가 그대로 중계한다. */
export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
const app = Fastify({ logger: false, bodyLimit: 1024 * 1024 });
const { store, timeline } = d;
const users = (): User[] => {
const acc = store.listAccounts();
return store.listUsers().map((u) => toUser(u, acc));
};
app.get('/api/overview', async (): Promise<Overview> => {
const extra = d.overviewExtra();
const gs = d.games.status();
return {
guild: extra.guild,
recording: extra.recording,
users: users(),
games: { valorant: { connected: gs.valorant.connected, inMatch: gs.valorant.inMatch }, lol: { connected: gs.lol.connected, inMatch: gs.lol.inMatch } },
counts: store.counts(),
version: d.version,
};
});
app.get('/api/users', async () => users());
app.get<{ Params: { id: string } }>('/api/users/:id', async (req, reply): Promise<UserProfile | void> => {
const u = store.getUser(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
const st = store.db
.prepare('SELECT count(*) n, coalesce(sum(ended_at-started_at),0) ms FROM utterances WHERE user_id=? AND (noise=0 OR corrected=1)')
.get(u.id) as { n: number; ms: number };
const texts = store.db
.prepare('SELECT text FROM utterances WHERE user_id=? AND text IS NOT NULL AND (noise=0 OR corrected=1) ORDER BY started_at DESC LIMIT 3000')
.all(u.id) as { text: string }[];
const freq = new Map<string, number>();
for (const t of texts)
for (const raw of t.text.split(/\s+/)) {
const w = raw.replace(/[.,!?~…"'()\[\]]/g, '');
if ([...w].length < 2 || STOP.has(w)) continue;
freq.set(w, (freq.get(w) || 0) + 1);
}
const topWords = [...freq.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, 30)
.map(([w, n]) => ({ w, n }));
const puuids = store
.listAccounts()
.filter((a) => a.user_id === u.id)
.map((a) => a.puuid)
.filter(Boolean);
const matchIds = new Set<string>(
(store.db.prepare('SELECT DISTINCT match_id FROM utterances WHERE user_id=? AND match_id IS NOT NULL').all(u.id) as { match_id: string }[]).map((r) => r.match_id),
);
if (puuids.length) {
const ph = puuids.map(() => '?').join(',');
for (const r of store.db.prepare(`SELECT DISTINCT match_id FROM game_events WHERE actor_puuid IN (${ph}) OR target_puuid IN (${ph})`).all(...puuids, ...puuids) as { match_id: string }[])
matchIds.add(r.match_id);
}
const matches = store.listMatches({ ids: [...matchIds], limit: 50 }).map((m) => d.games.summary(m));
return { user: toUser(u, store.listAccounts()), stats: { talkMs: st.ms, count: st.n, topWords }, matches };
});
app.get<{ Querystring: Record<string, string> }>('/api/timeline', async (req) => {
const q = req.query;
const tq: TimelineQuery = {
users: q.users ? q.users.split(',').filter(Boolean) : undefined,
game: q.game === 'valorant' || q.game === 'lol' || q.game === 'none' ? q.game : undefined,
match: q.match || undefined,
from: q.from ? Number(q.from) : undefined,
to: q.to ? Number(q.to) : undefined,
q: q.q || undefined,
types: q.types ? q.types.split(',').filter(Boolean) : undefined,
hideNoise: q.hideNoise === '1' || q.hideNoise === 'true',
cursor: q.cursor || undefined,
limit: q.limit ? Number(q.limit) : undefined,
order: q.order === 'asc' ? 'asc' : 'desc',
};
return timeline.query(tq);
});
app.get<{ Params: { id: string } }>('/api/audio/:id', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
if (!u.audio_path || u.audio_deleted || !fs.existsSync(u.audio_path)) return reply.code(410).send({ error: 'audio_deleted' });
const size = fs.statSync(u.audio_path).size;
const range = req.headers.range;
reply.header('content-type', 'audio/ogg').header('accept-ranges', 'bytes').header('cache-control', 'private, max-age=86400');
const m = range ? /bytes=(\d*)-(\d*)/.exec(range) : null;
if (m) {
const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]));
const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;
if (start >= size) return reply.code(416).header('content-range', `bytes */${size}`).send();
const buf = Buffer.alloc(end - start + 1);
const fd = fs.openSync(u.audio_path, 'r');
fs.readSync(fd, buf, 0, buf.length, start);
fs.closeSync(fd);
return reply.code(206).header('content-range', `bytes ${start}-${end}/${size}`).send(buf);
}
return reply.send(fs.readFileSync(u.audio_path));
});
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
const q = req.query;
return store
.listMatches({ game: q.game || undefined, before: q.before ? Number(q.before) : undefined, limit: q.limit ? Math.min(Number(q.limit), 200) : 50 })
.map((m) => d.games.summary(m));
});
app.get<{ Params: { id: string } }>('/api/matches/:id', async (req, reply): Promise<MatchDetail | void> => {
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const det = safeJson<any>(m.detail, {});
const sum = d.games.summary(m);
const accounts = store.listAccounts();
const userOf = (puuid: string) => accounts.find((a) => a.puuid === puuid)?.user_id;
const players: MatchPlayer[] = (det.players || []).map((p: any) => ({
puuid: p.puuid,
name: p.name ?? '?',
tag: p.tag,
team: p.team,
ally: p.ally ?? (det.self ? p.team === (det.players || []).find((x: any) => x.puuid === det.self)?.team : false),
character: p.character ?? { id: '', name: '?', icon: null },
kills: p.kills ?? 0,
deaths: p.deaths ?? 0,
assists: p.assists ?? 0,
score: p.score,
cs: p.cs,
gold: p.gold,
level: p.level,
items: p.items,
rank: p.rank ?? null,
userId: p.puuid ? userOf(p.puuid) : undefined,
}));
const evRows = store.events(m.id);
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[];
const vmap = m.game === 'valorant' ? d.games.assets.valMap(m.map) : null;
return {
...sum,
players,
rounds: m.game === 'valorant' ? det.roundsDetail ?? roundsFromTable(store, m.id, m.clock_offset) : undefined,
goldDiff: m.game === 'lol' ? det.goldDiff ?? [] : undefined,
events: evRows.map((e) => timeline.eventItem(e)),
utterances: utts.map((u) => timeline.utteranceItem(u)),
mapTransform:
m.game === 'valorant'
? vmap
? { valorant: { xMultiplier: vmap.xMultiplier, yMultiplier: vmap.yMultiplier, xScalarToAdd: vmap.xScalarToAdd, yScalarToAdd: vmap.yScalarToAdd } }
: null
: { lol: { minX: -120, minY: -120, maxX: 14870, maxY: 14980 } },
};
});
app.patch<{ Params: { id: string }; Body: { text?: string } }>('/api/utterances/:id', async (req, reply) => {
const u = store.getUtterance(req.params.id);
if (!u) return reply.code(404).send({ error: 'not_found' });
const text = String(req.body?.text ?? '').trim().slice(0, 1000);
if (!text) return reply.code(400).send({ error: 'empty_text' });
const old = u.text ?? u.raw_text ?? '';
const words = realignWords(safeJson<Word[]>(u.words, []), text, (u.ended_at - u.started_at) / 1000);
store.correctUtterance(u.id, text, words);
const s = d.settings();
if (s.dictionary.applySiteCorrections && old) d.dict.learn(old, text);
// 학습 데이터: 고친 문장 + 음성 조각 (자동 삭제 제외, A3). 녹음 제외 유저는 넣지 않는다.
const user = store.getUser(u.user_id);
if (u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path) && !user?.excluded) {
const dir = d.trainingDir();
fs.mkdirSync(dir, { recursive: true });
const dest = path.join(dir, `${u.id}.ogg`);
if (!fs.existsSync(dest)) fs.copyFileSync(u.audio_path, dest);
store.addTrainingSample({ id: u.id, utterance_id: u.id, text, audio_path: dest });
}
const item = timeline.utteranceItem(store.getUtterance(u.id)!);
d.bus.live({ type: 'utterance.updated', data: item });
return item;
});
app.get('/api/dictionary', async () => ({
labels: d.dict.labels,
entries: store.listDict().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 })),
}));
return app;
}
function roundsFromTable(store: Store, matchId: string, offset: number) {
return store.rounds(matchId).map((r) => ({
num: r.num,
startedAt: r.started_at + offset,
endedAt: r.ended_at + offset,
win: !!r.win,
result: r.result ?? '',
score: { ally: r.ally_score ?? 0, enemy: r.enemy_score ?? 0 },
economy: safeJson(r.economy, {}),
}));
}
/** 고친 문장에 단어 시각을 다시 붙인다. 단어 수가 같으면 기존 시각, 다르면 길이 비례 배분 */
export function realignWords(old: Word[], text: string, durationS: number): Word[] {
const toks = text.split(/\s+/).filter(Boolean);
if (old.length === toks.length) return toks.map((w, i) => ({ ...old[i], w }));
const start = old.length ? old[0].s : 0;
const end = old.length ? old[old.length - 1].e : durationS;
const total = toks.reduce((n, t) => n + [...t].length, 0) || 1;
let t = start;
return toks.map((w) => {
const len = ((end - start) * [...w].length) / total;
const out = { w, s: round2(t), e: round2(t + len) };
t += len;
return out;
});
}
const round2 = (x: number) => Math.round(x * 100) / 100;

44
app/src/core/cli.ts Normal file
View File

@@ -0,0 +1,44 @@
// 헤드리스 실행 (리눅스 개발·테스트용). Electron 없이 코어만 돈다.
// GVR_DATA_DIR=... GVR_BOT_TOKEN=... npm run core
// npm run core -- --diagnose (M0 진단만 돌리고 종료)
import path from 'node:path';
import { runDiagnostics } from './diagnostics.js';
import { WorkerClient } from './stt/worker.js';
import { startCore } from './index.js';
async function main() {
const root = path.resolve(__dirname, '..', '..');
const dataDir = process.env.GVR_DATA_DIR || path.join(root, '.gvr-data');
const py = process.env.GVR_WORKER_PYTHON || path.join(root, '..', 'worker', '.venv', 'bin', 'python');
const worker = { cmd: py, args: ['-m', 'gvr_worker'], cwd: path.join(root, '..', 'worker') };
if (process.argv.includes('--diagnose')) {
const w = new WorkerClient({ ...worker, env: { GVR_DATA_DIR: dataDir, GVR_MODELS_DIR: process.env.GVR_MODELS_DIR || path.join(dataDir, 'models') } });
w.start();
await new Promise((r) => w.once('ready', r));
const items = await runDiagnostics({
worker: w,
resourcesDir: path.join(root, 'resources'),
logsDir: path.join(dataDir, 'logs'),
model: process.env.GVR_DIAG_MODEL || 'large-v3-turbo',
device: process.env.GVR_DIAG_DEVICE || 'cuda',
computeType: process.env.GVR_DIAG_COMPUTE || 'float16',
onItem: (it) => console.log(`${it.ok === null ? '·' : it.ok ? '✔' : '✘'} ${it.label}: ${it.detail}`),
});
await w.stop();
process.exit(items.some((i) => i.ok === false) ? 1 : 0);
}
const core = await startCore({
dataDir,
resourcesDir: path.join(root, 'resources'),
worker,
version: process.env.npm_package_version || '1.0.0',
apiPort: Number(process.env.GVR_API_PORT || 0),
});
const shutdown = async () => {
await core.stop();
process.exit(0);
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
void main();

399
app/src/core/db/db.ts Normal file
View File

@@ -0,0 +1,399 @@
import Database from 'better-sqlite3';
import fs from 'node:fs';
import path from 'node:path';
import { SCHEMA_SQL } from './schema.js';
import { colorFor } from '../util/ids.js';
export interface UserRow {
id: string;
name: string;
color: string;
avatar: string | null;
excluded: number;
gain_lufs: number | null;
gain_n: number;
updated_at: number;
}
export interface UtteranceRow {
rowid?: number;
id: string;
session_id: string | null;
user_id: string;
started_at: number;
ended_at: number;
audio_path: string | null;
audio_deleted: number;
text: string | null;
raw_text: string | null;
words: string;
noise: number;
noise_reason: string | null;
confidence: number | null;
lufs: number | null;
gain_db: number;
model: string | null;
status: string;
match_id: string | null;
corrected: number;
attempts: number;
created_at: number;
}
export interface MatchRow {
id: string;
game: 'valorant' | 'lol';
started_at: number;
ended_at: number | null;
map: string | null;
mode: string | null;
queue: string | null;
result: string | null;
detail: string | null;
status: string;
clock_offset: number;
}
export interface RoundRow {
match_id: string;
num: number;
started_at: number;
combat_at: number;
ended_at: number;
win: number | null;
result: string | null;
ally_score: number | null;
enemy_score: number | null;
economy: string | null;
}
export interface EventRow {
id: string;
match_id: string;
game: 'valorant' | 'lol';
type: string;
ts: number;
game_time_ms: number | null;
round: number | null;
actor_puuid: string | null;
target_puuid: string | null;
data: string;
}
export interface DictRow {
id: number;
word: string;
pack: string;
kind: 'hotword' | 'correction';
from_text: string;
source: 'builtin' | 'user' | 'site';
enabled: number;
hits: number;
created_at: number;
}
export class Store {
readonly db: Database.Database;
constructor(file: string) {
fs.mkdirSync(path.dirname(file), { recursive: true });
this.db = new Database(file);
this.db.exec(SCHEMA_SQL);
}
close(): void {
this.db.close();
}
// ---------------------------------------------------------------- users
upsertUser(u: { id: string; name: string; avatar: string | null }): UserRow {
const now = Date.now();
this.db
.prepare(
`INSERT INTO users(id,name,color,avatar,updated_at) VALUES(?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name, avatar=excluded.avatar, updated_at=excluded.updated_at`,
)
.run(u.id, u.name, colorFor(u.id), u.avatar, now);
return this.getUser(u.id)!;
}
getUser(id: string): UserRow | undefined {
return this.db.prepare('SELECT * FROM users WHERE id=?').get(id) as UserRow | undefined;
}
listUsers(): UserRow[] {
return this.db.prepare('SELECT * FROM users ORDER BY name').all() as UserRow[];
}
setExcluded(id: string, excluded: boolean): void {
this.db.prepare('UPDATE users SET excluded=?, updated_at=? WHERE id=?').run(excluded ? 1 : 0, Date.now(), id);
}
/** 유저 평소 음량 누적 평균 (최근값에 가중치) */
updateGainProfile(id: string, lufs: number): void {
const u = this.getUser(id);
if (!u) return;
const n = Math.min(u.gain_n, 49);
const next = u.gain_lufs === null ? lufs : (u.gain_lufs * n + lufs) / (n + 1);
this.db.prepare('UPDATE users SET gain_lufs=?, gain_n=? WHERE id=?').run(next, u.gain_n + 1, id);
}
listAccounts(): { user_id: string; puuid: string; riot_id: string }[] {
return this.db.prepare('SELECT * FROM game_accounts').all() as any[];
}
setAccounts(userId: string, accounts: { puuid: string; riotId: string }[]): void {
const tx = this.db.transaction(() => {
this.db.prepare('DELETE FROM game_accounts WHERE user_id=?').run(userId);
for (const a of accounts)
this.db.prepare('INSERT OR REPLACE INTO game_accounts(user_id,puuid,riot_id) VALUES(?,?,?)').run(userId, a.puuid, a.riotId);
});
tx();
}
userIdForPuuid(puuid: string): string | undefined {
const r = this.db.prepare('SELECT user_id FROM game_accounts WHERE puuid=?').get(puuid) as any;
return r?.user_id;
}
// ---------------------------------------------------------------- sessions
startSession(id: string, guildId: string, channelId: string, channelName: string | null, at: number): void {
this.db
.prepare('INSERT INTO sessions(id,guild_id,channel_id,channel_name,started_at) VALUES(?,?,?,?,?)')
.run(id, guildId, channelId, channelName, at);
}
endSession(id: string, at: number): void {
this.db.prepare('UPDATE sessions SET ended_at=? WHERE id=?').run(at, id);
}
// ---------------------------------------------------------------- utterances
insertUtterance(u: Pick<UtteranceRow, 'id' | 'session_id' | 'user_id' | 'started_at' | 'ended_at' | 'audio_path' | 'match_id'>): UtteranceRow {
this.db
.prepare(
`INSERT INTO utterances(id,session_id,user_id,started_at,ended_at,audio_path,match_id,created_at)
VALUES(@id,@session_id,@user_id,@started_at,@ended_at,@audio_path,@match_id,@created_at)`,
)
.run({ ...u, created_at: Date.now() });
return this.getUtterance(u.id)!;
}
getUtterance(id: string): UtteranceRow | undefined {
return this.db.prepare('SELECT rowid,* FROM utterances WHERE id=?').get(id) as UtteranceRow | undefined;
}
updateUtteranceResult(
id: string,
r: {
text: string | null;
raw_text: string | null;
words: unknown[];
noise: boolean;
noise_reason: string | null;
confidence: number | null;
lufs: number | null;
gain_db: number;
model: string;
status: 'realtime' | 'precise';
},
): void {
// 사용자가 이미 고친 문장은 재변환 결과로 덮어쓰지 않는다
this.db
.prepare(
`UPDATE utterances SET
text = CASE WHEN corrected=1 THEN text ELSE @text END,
raw_text=@raw_text,
words = CASE WHEN corrected=1 THEN words ELSE @words END,
noise=@noise, noise_reason=@noise_reason, confidence=@confidence, lufs=@lufs, gain_db=@gain_db,
model=@model, status=@status
WHERE id=@id`,
)
.run({ ...r, id, words: JSON.stringify(r.words), noise: r.noise ? 1 : 0 });
}
markUtteranceFailed(id: string): void {
this.db.prepare(`UPDATE utterances SET status='failed', attempts=attempts+1 WHERE id=?`).run(id);
}
bumpAttempt(id: string): number {
this.db.prepare('UPDATE utterances SET attempts=attempts+1 WHERE id=?').run(id);
return (this.db.prepare('SELECT attempts FROM utterances WHERE id=?').get(id) as any)?.attempts ?? 0;
}
pendingUtterances(): UtteranceRow[] {
return this.db
.prepare(`SELECT rowid,* FROM utterances WHERE status='pending' AND audio_deleted=0 ORDER BY started_at`)
.all() as UtteranceRow[];
}
/** 경기 후 정밀 재변환 대상 */
realtimeUtterancesInRange(from: number, to: number): UtteranceRow[] {
return this.db
.prepare(
`SELECT rowid,* FROM utterances WHERE status IN ('realtime','pending') AND audio_deleted=0 AND corrected=0
AND started_at>=? AND started_at<=? ORDER BY started_at`,
)
.all(from, to) as UtteranceRow[];
}
correctUtterance(id: string, text: string, words: unknown[]): void {
this.db.prepare('UPDATE utterances SET text=?, words=?, corrected=1, noise=0 WHERE id=?').run(text, JSON.stringify(words), id);
}
assignMatch(matchId: string, from: number, to: number): number {
return this.db
.prepare('UPDATE utterances SET match_id=? WHERE started_at>=? AND started_at<=? AND (match_id IS NULL OR match_id=?)')
.run(matchId, from, to, matchId).changes;
}
/** 보관 기간 지난 음성 파일 목록 */
expiredAudio(before: number): { id: string; audio_path: string }[] {
return this.db
.prepare('SELECT id, audio_path FROM utterances WHERE audio_deleted=0 AND audio_path IS NOT NULL AND started_at<?')
.all(before) as any[];
}
markAudioDeleted(id: string): void {
this.db.prepare('UPDATE utterances SET audio_deleted=1 WHERE id=?').run(id);
}
// ---------------------------------------------------------------- matches
upsertMatch(m: Partial<MatchRow> & { id: string; game: 'valorant' | 'lol'; started_at: number }): MatchRow {
const cur = this.getMatch(m.id);
const row: MatchRow = {
ended_at: null,
map: null,
mode: null,
queue: null,
result: null,
detail: null,
status: 'live',
clock_offset: 0,
...(cur || {}),
...stripUndef(m),
} as MatchRow;
this.db
.prepare(
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset)
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset)
ON CONFLICT(id) DO UPDATE SET started_at=@started_at, ended_at=@ended_at, map=@map, mode=@mode, queue=@queue,
result=@result, detail=@detail, status=@status, clock_offset=@clock_offset`,
)
.run(row);
return this.getMatch(m.id)!;
}
getMatch(id: string): MatchRow | undefined {
return this.db.prepare('SELECT * FROM matches WHERE id=?').get(id) as MatchRow | undefined;
}
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[] }): MatchRow[] {
const where: string[] = [];
const args: any[] = [];
if (opts.game) {
where.push('game=?');
args.push(opts.game);
}
if (opts.before) {
where.push('started_at<?');
args.push(opts.before);
}
if (opts.ids) {
if (!opts.ids.length) return [];
where.push(`id IN (${opts.ids.map(() => '?').join(',')})`);
args.push(...opts.ids);
}
return this.db
.prepare(`SELECT * FROM matches ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY started_at DESC LIMIT ?`)
.all(...args, opts.limit ?? 50) as MatchRow[];
}
/** ts 시점에 진행 중이던 경기 */
matchAt(ts: number): MatchRow | undefined {
return this.db
.prepare('SELECT * FROM matches WHERE started_at<=? AND (ended_at IS NULL OR ended_at>=?) ORDER BY started_at DESC LIMIT 1')
.get(ts, ts) as MatchRow | undefined;
}
replaceRounds(matchId: string, rounds: RoundRow[]): void {
const tx = this.db.transaction(() => {
this.db.prepare('DELETE FROM rounds WHERE match_id=?').run(matchId);
const st = this.db.prepare(
`INSERT INTO rounds(match_id,num,started_at,combat_at,ended_at,win,result,ally_score,enemy_score,economy)
VALUES(@match_id,@num,@started_at,@combat_at,@ended_at,@win,@result,@ally_score,@enemy_score,@economy)`,
);
for (const r of rounds) st.run(r);
});
tx();
}
rounds(matchId: string): RoundRow[] {
return this.db.prepare('SELECT * FROM rounds WHERE match_id=? ORDER BY num').all(matchId) as RoundRow[];
}
roundsForMatches(ids: string[]): Map<string, RoundRow[]> {
const out = new Map<string, RoundRow[]>();
if (!ids.length) return out;
const rows = this.db
.prepare(`SELECT * FROM rounds WHERE match_id IN (${ids.map(() => '?').join(',')}) ORDER BY num`)
.all(...ids) as RoundRow[];
for (const r of rows) {
if (!out.has(r.match_id)) out.set(r.match_id, []);
out.get(r.match_id)!.push(r);
}
return out;
}
// ---------------------------------------------------------------- events
insertEvent(e: EventRow): boolean {
return (
this.db
.prepare(
`INSERT OR IGNORE INTO game_events(id,match_id,game,type,ts,game_time_ms,round,actor_puuid,target_puuid,data)
VALUES(@id,@match_id,@game,@type,@ts,@game_time_ms,@round,@actor_puuid,@target_puuid,@data)`,
)
.run(e).changes > 0
);
}
replaceEvents(matchId: string, types: string[], events: EventRow[]): void {
const tx = this.db.transaction(() => {
this.db
.prepare(`DELETE FROM game_events WHERE match_id=? AND type IN (${types.map(() => '?').join(',')})`)
.run(matchId, ...types);
for (const e of events) this.insertEvent(e);
});
tx();
}
events(matchId: string): EventRow[] {
return this.db.prepare('SELECT * FROM game_events WHERE match_id=? ORDER BY ts').all(matchId) as EventRow[];
}
// ---------------------------------------------------------------- dictionary
addDict(d: Omit<DictRow, 'id' | 'created_at' | 'hits' | 'enabled'> & { enabled?: number }): void {
this.db
.prepare(
`INSERT INTO dictionary(word,pack,kind,from_text,source,enabled,created_at) VALUES(?,?,?,?,?,?,?)
ON CONFLICT(kind,word,from_text) DO UPDATE SET pack=excluded.pack, enabled=excluded.enabled`,
)
.run(d.word, d.pack, d.kind, d.from_text ?? '', d.source, d.enabled ?? 1, Date.now());
}
listDict(): DictRow[] {
return this.db.prepare('SELECT * FROM dictionary ORDER BY pack, word').all() as DictRow[];
}
deleteDict(id: number): void {
this.db.prepare('DELETE FROM dictionary WHERE id=?').run(id);
}
setDictEnabled(id: number, enabled: boolean): void {
this.db.prepare('UPDATE dictionary SET enabled=? WHERE id=?').run(enabled ? 1 : 0, id);
}
hitDict(words: string[]): void {
const st = this.db.prepare(`UPDATE dictionary SET hits=hits+1 WHERE kind='hotword' AND word=?`);
for (const w of words) st.run(w);
}
// ---------------------------------------------------------------- training
addTrainingSample(s: { id: string; utterance_id: string; text: string; audio_path: string }): void {
this.db
.prepare(
`INSERT INTO training_samples(id,utterance_id,text,audio_path,created_at) VALUES(?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET text=excluded.text`,
)
.run(s.id, s.utterance_id, s.text, s.audio_path, Date.now());
}
trainingSamples(): { id: string; utterance_id: string; text: string; audio_path: string; used: number; created_at: number }[] {
return this.db.prepare('SELECT * FROM training_samples ORDER BY created_at').all() as any[];
}
clearTraining(): void {
this.db.prepare('DELETE FROM training_samples').run();
}
// ---------------------------------------------------------------- stats
counts(): { utterances: number; matches: number } {
const u = (this.db.prepare('SELECT count(*) n FROM utterances').get() as any).n;
const m = (this.db.prepare('SELECT count(*) n FROM matches').get() as any).n;
return { utterances: u, matches: m };
}
meta(key: string): string | undefined {
return (this.db.prepare('SELECT value FROM meta WHERE key=?').get(key) as any)?.value;
}
setMeta(key: string, value: string): void {
this.db.prepare('INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, value);
}
}
function stripUndef<T extends object>(o: T): Partial<T> {
const out: any = {};
for (const [k, v] of Object.entries(o)) if (v !== undefined) out[k] = v;
return out;
}

138
app/src/core/db/schema.sql Normal file
View File

@@ -0,0 +1,138 @@
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
color TEXT NOT NULL,
avatar TEXT,
excluded INTEGER NOT NULL DEFAULT 0,
gain_lufs REAL,
gain_n INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS game_accounts (
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
puuid TEXT NOT NULL,
riot_id TEXT NOT NULL,
PRIMARY KEY (user_id, puuid)
);
CREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
channel_name TEXT,
started_at INTEGER NOT NULL,
ended_at INTEGER
);
CREATE TABLE IF NOT EXISTS utterances (
id TEXT PRIMARY KEY,
session_id TEXT,
user_id TEXT NOT NULL,
started_at INTEGER NOT NULL,
ended_at INTEGER NOT NULL,
audio_path TEXT,
audio_deleted INTEGER NOT NULL DEFAULT 0,
text TEXT,
raw_text TEXT,
words TEXT NOT NULL DEFAULT '[]',
noise INTEGER NOT NULL DEFAULT 0,
noise_reason TEXT,
confidence REAL,
lufs REAL,
gain_db REAL NOT NULL DEFAULT 0,
model TEXT,
status TEXT NOT NULL DEFAULT 'pending',
match_id TEXT,
corrected INTEGER NOT NULL DEFAULT 0,
attempts INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);
CREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);
CREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);
CREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);
CREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');
CREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN
INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));
END;
CREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN
INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));
END;
CREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN
INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));
INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));
END;
CREATE TABLE IF NOT EXISTS matches (
id TEXT PRIMARY KEY,
game TEXT NOT NULL,
started_at INTEGER NOT NULL,
ended_at INTEGER,
map TEXT,
mode TEXT,
queue TEXT,
result TEXT,
detail TEXT,
status TEXT NOT NULL DEFAULT 'live',
clock_offset INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);
CREATE TABLE IF NOT EXISTS rounds (
match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,
num INTEGER NOT NULL,
started_at INTEGER NOT NULL,
combat_at INTEGER NOT NULL,
ended_at INTEGER NOT NULL,
win INTEGER,
result TEXT,
ally_score INTEGER,
enemy_score INTEGER,
economy TEXT,
PRIMARY KEY (match_id, num)
);
CREATE TABLE IF NOT EXISTS game_events (
id TEXT PRIMARY KEY,
match_id TEXT NOT NULL,
game TEXT NOT NULL,
type TEXT NOT NULL,
ts INTEGER NOT NULL,
game_time_ms INTEGER,
round INTEGER,
actor_puuid TEXT,
target_puuid TEXT,
data TEXT NOT NULL DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);
CREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);
CREATE TABLE IF NOT EXISTS dictionary (
id INTEGER PRIMARY KEY AUTOINCREMENT,
word TEXT NOT NULL,
pack TEXT NOT NULL,
kind TEXT NOT NULL,
from_text TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
hits INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
UNIQUE (kind, word, from_text)
);
CREATE TABLE IF NOT EXISTS training_samples (
id TEXT PRIMARY KEY,
utterance_id TEXT,
text TEXT NOT NULL,
audio_path TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);

View File

@@ -0,0 +1,2 @@
// 자동 생성: schema.sql 사본 (npm run build 가 다시 만든다)
export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n";

157
app/src/core/diagnostics.ts Normal file
View File

@@ -0,0 +1,157 @@
import fs from 'node:fs';
import path from 'node:path';
import { basicAuth, findLcu, readLockfile, request, riotClientLockfilePath } from './games/riot.js';
import { decodePresence } from './games/valorant.js';
import type { WorkerClient } from './stt/worker.js';
export interface DiagItem {
id: string;
label: string;
ok: boolean | null; // null = 확인 불가(게임 꺼짐 등)
detail: string;
data?: unknown;
}
/**
* M0 기술 검증을 게임 PC 에서 그대로 돌리는 진단. 설정 창 "진단" 탭과 `--diagnose` 에서 쓴다.
* 결과 JSON 은 GVR-Data/logs/diagnostics-<시각>.json 에 남는다.
*/
export async function runDiagnostics(opts: {
worker: WorkerClient;
resourcesDir: string;
logsDir: string;
model: string;
device: string;
computeType: string;
lolLogsDir?: string | null;
onItem?: (it: DiagItem) => void;
}): Promise<DiagItem[]> {
const out: DiagItem[] = [];
const add = (it: DiagItem) => {
out.push(it);
opts.onItem?.(it);
};
// 1. GPU
try {
const g = await opts.worker.request('gpu_info', {}, 30000);
const gpu = g.gpus?.[0];
add({
id: 'gpu',
label: 'NVIDIA GPU',
ok: !!gpu,
detail: gpu ? `${gpu.name} · VRAM ${(gpu.vram_total_mb / 1024).toFixed(1)}GB · 드라이버 ${gpu.driver} (CUDA ${gpu.cuda_driver ?? '?'})` : 'NVIDIA GPU 를 찾지 못했습니다',
data: g,
});
} catch (e: any) {
add({ id: 'gpu', label: 'NVIDIA GPU', ok: false, detail: e.message });
}
// 2. STT 속도·VRAM
try {
const models = await opts.worker.request('models', {}, 30000);
const m = (models.models || []).find((x: any) => x.name === opts.model);
if (!m?.installed) add({ id: 'stt', label: `STT 속도 (${opts.model})`, ok: null, detail: '모델이 아직 없습니다. STT 모델 탭에서 내려받은 뒤 다시 실행하세요.' });
else {
const t0 = Date.now();
const ld = await opts.worker.request('load', { slot: 'precise', model: opts.model, device: opts.device, compute_type: opts.computeType }, 15 * 60000);
const loadMs = Date.now() - t0;
const sample = path.join(opts.resourcesDir, 'diag', 'speech_ko.ogg');
const runs: number[] = [];
let text = '';
for (let i = 0; i < 3; i++) {
const r = await opts.worker.request('transcribe', { slot: 'precise', path: sample, hotwords: '레이즈 로테 B 사이트', corrections: [], dictionary: [], target_lufs: -18, noise_sensitivity: 0.5, denoise: false, profile_lufs: null }, 120000);
runs.push(r.elapsed_ms);
text = r.text ?? '';
}
const g = await opts.worker.request('gpu_info', {}, 30000).catch(() => null);
await opts.worker.request('unload', { slot: 'precise' }, 60000).catch(() => undefined);
const dur = 3.6;
const best = Math.min(...runs);
add({
id: 'stt',
label: `STT 속도 (${opts.model})`,
ok: best < dur * 1000,
detail: `적재 ${(loadMs / 1000).toFixed(1)}초 · ${dur}초 음성 변환 ${best}ms (실시간의 ${(dur * 1000 / best).toFixed(1)}배) · VRAM 사용 ${g?.gpus?.[0]?.vram_used_mb ?? '?'}MB · "${text}"${ld?.fallback ? ' · GPU 없음 → CPU' : ''}`,
data: { loadMs, runs, text, gpu: g },
});
}
} catch (e: any) {
add({ id: 'stt', label: `STT 속도 (${opts.model})`, ok: false, detail: e.message });
}
// 3. 발로란트 (Riot Client 로컬 API)
const lf = readLockfile(riotClientLockfilePath());
if (!lf) add({ id: 'valorant', label: '발로란트 로컬 API', ok: null, detail: 'Riot 클라이언트가 실행 중이 아닙니다 (발로란트를 켜고 다시 실행)' });
else {
try {
const h = { authorization: basicAuth(lf.password) };
const ent = await request(`https://127.0.0.1:${lf.port}/entitlements/v1/token`, { headers: h, local: true });
const pres = await request(`https://127.0.0.1:${lf.port}/chat/v4/presences`, { headers: h, local: true });
const mine = (pres.data?.presences || []).find((p: any) => p.puuid === ent.data?.subject && p.product === 'valorant');
const p = mine?.private ? decodePresence(mine.private) : null;
add({
id: 'valorant',
label: '발로란트 로컬 API',
ok: ent.status === 200,
detail: ent.status === 200 ? `로그인 확인 · 상태 ${p?.state ?? '발로란트 꺼짐'}${p?.map ? ` · 맵 ${p.map}` : ''}` : `인증 실패 (${ent.status})`,
data: { presence: p },
});
} catch (e: any) {
add({ id: 'valorant', label: '발로란트 로컬 API', ok: false, detail: e.message });
}
}
// 4. 롤 게임 클라이언트 API · LCU
try {
const r = await request('https://127.0.0.1:2999/liveclientdata/gamestats', { local: true, timeoutMs: 1500 });
add({ id: 'lol-live', label: '롤 게임 클라이언트 API (2999)', ok: r.status === 200, detail: r.status === 200 ? `게임 중 · 게임 시간 ${Math.round(r.data.gameTime)}초` : `응답 ${r.status}` });
} catch {
add({ id: 'lol-live', label: '롤 게임 클라이언트 API (2999)', ok: null, detail: '게임 중이 아닙니다 (롤 게임에 들어가서 실행하면 확인됩니다)' });
}
const lcu = await findLcu().catch(() => null);
if (!lcu) add({ id: 'lcu', label: '롤 클라이언트 (LCU)', ok: null, detail: '롤 클라이언트가 실행 중이 아닙니다' });
else {
const h = { authorization: basicAuth(lcu.password) };
const base = `https://127.0.0.1:${lcu.port}`;
const me = await request(`${base}/lol-summoner/v1/current-summoner`, { headers: h, local: true }).catch(() => null);
// 최근 경기 하나로 타임라인(킬 위치·골드) 조회가 되는지
const hist = await request(`${base}/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=0&endIndex=1`, { headers: h, local: true }).catch(() => null);
const gid = hist?.data?.games?.games?.[0]?.gameId;
const tl = gid ? await request(`${base}/lol-match-history/v1/game-timelines/${gid}`, { headers: h, local: true }).catch(() => null) : null;
add({
id: 'lcu',
label: '롤 클라이언트 (LCU) · 타임라인',
ok: me?.status === 200,
detail: `${me?.data?.gameName ? `로그인: ${me.data.gameName}#${me.data.tagLine}` : '로그인 정보 없음'} · 최근 경기 타임라인 ${tl?.status === 200 && tl.data?.frames ? `조회 가능 (프레임 ${tl.data.frames.length})` : gid ? '조회 불가 → 킬 위치·골드 그래프에 공식 API 키 필요' : '최근 경기 없음'}`,
data: { installDir: lcu.installDir, timeline: tl?.status ?? null },
});
}
// 5. 채팅 OCR (한국어 OCR 설치 여부 + 정확도)
try {
const r = await opts.worker.request('ocr_image', { path: path.join(opts.resourcesDir, 'diag', 'lol-chat-sample.png'), lang: 'ko' }, 60000);
const lines: string[] = (r.lines || []).map((l: any) => l.text ?? l);
const expect = ['드래곤 가자', 'gg', '바텀 갱 간다'];
const hit = expect.filter((e) => lines.some((l) => l.replace(/\s/g, '').includes(e.replace(/\s/g, '')))).length;
add({ id: 'ocr', label: '채팅 OCR (한국어)', ok: hit >= 2, detail: `예시 3줄 중 ${hit}줄 인식: ${lines.join(' / ')}`, data: r });
} catch (e: any) {
add({ id: 'ocr', label: '채팅 OCR (한국어)', ok: false, detail: e.message });
}
// 6. r3dlog 채팅
const logs = opts.lolLogsDir || (lcu?.installDir ? path.join(lcu.installDir, 'Logs', 'GameLogs') : null);
if (!logs || !fs.existsSync(logs)) add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: null, detail: '로그 폴더를 찾지 못했습니다 (롤을 한 판 한 뒤 확인)' });
else {
try {
const r = await opts.worker.request('r3dlog_check', { logs_dir: logs }, 30000);
add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: r.found_chat, detail: r.found_chat ? `채팅이 남아 있음 → OCR 대신 사용 (${r.file})` : '로그에 채팅이 없음 → 화면 OCR 사용', data: r });
} catch (e: any) {
add({ id: 'r3dlog', label: '롤 로그 파일 채팅', ok: false, detail: e.message });
}
}
fs.mkdirSync(opts.logsDir, { recursive: true });
fs.writeFileSync(path.join(opts.logsDir, `diagnostics-${new Date().toISOString().replace(/[:.]/g, '-')}.json`), JSON.stringify(out, null, 2));
return out;
}

View File

@@ -0,0 +1,177 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Store, DictRow } from '../db/db.js';
import { logger } from '../util/log.js';
const log = logger('dict');
export type DictContext = 'valorant' | 'lol' | 'none';
/** 상황별로 우선 쓰는 묶음 (앞쪽이 우선) */
const CONTEXT_PACKS: Record<DictContext, string[]> = {
valorant: ['site', 'user', 'valorant', 'valorant_callouts', 'game', 'slang20s', 'daily'],
lol: ['site', 'user', 'lol', 'lol_skills', 'game', 'slang20s', 'daily'],
none: ['site', 'user', 'daily', 'university', 'slang20s', 'game', 'valorant', 'lol'],
};
/** Whisper 프롬프트 길이 제한 때문에 핫워드는 이 정도까지만 */
const MAX_HOTWORDS = 60;
export interface PackFile {
meta: { generatedAt: string };
packs: Record<string, { label: string; words: string[] }>;
}
export class Dictionary {
private cache: { rows: DictRow[]; at: number } | null = null;
labels: Record<string, string> = { site: '사이트 교정', user: '사용자 단어' };
constructor(
private store: Store,
private resourcesDir: string,
private enabledPacks: () => Record<string, boolean>,
) {}
/** 기본 사전을 DB 에 넣는다. 파일이 바뀌었을 때만. */
seed(): void {
const packFile = path.join(this.resourcesDir, 'dictionary', 'packs.json');
const corrFile = path.join(this.resourcesDir, 'dictionary', 'corrections.json');
let data: PackFile;
try {
data = JSON.parse(fs.readFileSync(packFile, 'utf8'));
} catch (e) {
log.warn(`기본 사전 파일 없음: ${packFile}`);
return;
}
for (const [k, p] of Object.entries(data.packs)) this.labels[k] = p.label;
const version = data.meta.generatedAt;
if (this.store.meta('dict_version') === version) return;
const corrections: { from: string; to: string }[] = fs.existsSync(corrFile) ? JSON.parse(fs.readFileSync(corrFile, 'utf8')) : [];
const tx = this.store.db.transaction(() => {
this.store.db.prepare(`DELETE FROM dictionary WHERE source='builtin'`).run();
for (const [pack, p] of Object.entries(data.packs))
for (const w of p.words) this.store.addDict({ word: w, pack, kind: 'hotword', from_text: '', source: 'builtin' });
for (const c of corrections)
this.store.addDict({ word: c.to, pack: 'corrections', kind: 'correction', from_text: c.from, source: 'builtin' });
});
tx();
this.store.setMeta('dict_version', version);
this.cache = null;
log.info(`기본 사전 적재: ${Object.values(data.packs).reduce((n, p) => n + p.words.length, 0)}단어, 교정 ${corrections.length}개`);
}
invalidate(): void {
this.cache = null;
}
private rows(): DictRow[] {
if (!this.cache || Date.now() - this.cache.at > 60000) this.cache = { rows: this.store.listDict(), at: Date.now() };
return this.cache.rows;
}
private packOn(pack: string): boolean {
if (pack === 'site' || pack === 'user' || pack === 'corrections') return true;
const en = this.enabledPacks();
// 하위 묶음은 상위 묶음 설정을 따른다 (valorant_callouts → valorant)
const parent = pack.split('_')[0];
return en[pack] ?? en[parent] ?? true;
}
/** extra: 지금 경기에 나온 요원·챔피언·선수 이름 (가장 먼저 넣는다) */
hotwords(ctx: DictContext, extra: string[] = []): string {
const order = CONTEXT_PACKS[ctx];
const rows = this.rows().filter((r) => r.kind === 'hotword' && r.enabled && this.packOn(r.pack) && order.includes(r.pack));
// 묶음 순서 → 많이 나온 단어 → 사전 파일 순서(중요한 고유명사가 앞에 있음)
rows.sort((a, b) => order.indexOf(a.pack) - order.indexOf(b.pack) || b.hits - a.hits || a.id - b.id);
const out: string[] = [];
const seen = new Set<string>();
for (const w of extra) {
const t = w.trim();
if (!t || seen.has(t)) continue;
seen.add(t);
out.push(t);
}
for (const r of rows) {
if (seen.has(r.word)) continue;
seen.add(r.word);
out.push(r.word);
if (out.length >= MAX_HOTWORDS) break;
}
return out.join(' ');
}
corrections(): { from: string; to: string }[] {
return this.rows()
.filter((r) => r.kind === 'correction' && r.enabled && r.from_text)
.map((r) => ({ from: r.from_text, to: r.word }));
}
/** 자모 유사도 교정 후보 (상황 묶음의 단어, 2글자 이상) */
candidates(ctx: DictContext): string[] {
const order = CONTEXT_PACKS[ctx];
const set = new Set<string>();
for (const r of this.rows())
if (r.kind === 'hotword' && r.enabled && this.packOn(r.pack) && order.includes(r.pack) && r.word.length >= 2) set.add(r.word);
return [...set];
}
/**
* 사이트에서 고친 문장을 사전에 반영한다. 단어 단위로 맞춰 보고 바뀐 단어를 교정 규칙으로,
* 고친 쪽 단어를 핫워드로 넣는다. 반환: 추가된 규칙 수
*/
learn(raw: string, corrected: string): number {
const pairs = diffWords(raw, corrected);
let n = 0;
for (const [from, to] of pairs) {
if (!from || !to || from === to || from.length > 20 || to.length > 20) continue;
this.store.addDict({ word: to, pack: 'site', kind: 'correction', from_text: from, source: 'site' });
this.store.addDict({ word: to.replace(/\s+/g, ''), pack: 'site', kind: 'hotword', from_text: '', source: 'site' });
n++;
}
if (n) this.invalidate();
return n;
}
}
/**
* 두 문장을 단어 단위로 정렬(LCS)해서 바뀐 구간 쌍을 돌려준다.
* 예: "레이저 궁 빠졌어" → "레이즈 궁 빠졌어" ⇒ [["레이저","레이즈"]]
*/
export function diffWords(a: string, b: string): [string, string][] {
const x = a.trim().split(/\s+/).filter(Boolean);
const y = b.trim().split(/\s+/).filter(Boolean);
const n = x.length;
const m = y.length;
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) dp[i][j] = x[i] === y[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
const out: [string, string][] = [];
let i = 0;
let j = 0;
let bufA: string[] = [];
let bufB: string[] = [];
const flush = () => {
if (bufA.length && bufB.length) {
if (bufA.length === bufB.length && bufA.length > 1) {
// 단어 수가 같으면 한 단어씩 짝짓되, 한 글자짜리("비")는 문맥 없이 규칙이 되면 위험하니 다음 단어와 묶는다
let i = 0;
while (i < bufA.length) {
let j = i + 1;
while (j < bufA.length && [...bufA.slice(i, j).join('')].length < 2) j++;
out.push([bufA.slice(i, j).join(' '), bufB.slice(i, j).join(' ')]);
i = j;
}
} else out.push([bufA.join(' '), bufB.join(' ')]);
}
bufA = [];
bufB = [];
};
while (i < n || j < m) {
if (i < n && j < m && x[i] === y[j]) {
flush();
i++;
j++;
} else if (j < m && (i >= n || dp[i][j + 1] >= dp[i + 1][j])) bufB.push(y[j++]);
else bufA.push(x[i++]);
}
flush();
return out;
}

318
app/src/core/discord/bot.ts Normal file
View File

@@ -0,0 +1,318 @@
import {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
type AudioPlayer,
type VoiceConnection,
} from '@discordjs/voice';
import {
ChannelType,
Client,
Events,
GatewayIntentBits,
MessageFlags,
type ChatInputCommandInteraction,
type Guild,
type GuildMember,
type VoiceBasedChannel,
type VoiceState,
} from 'discord.js';
import fs from 'node:fs';
import type { Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { Bus } from '../util/events.js';
import { newId } from '../util/ids.js';
import { logger } from '../util/log.js';
import type { Recorder } from './recorder.js';
import type { Announcer } from './tts.js';
const log = logger('bot');
export const COMMANDS = [
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
];
export interface BotState {
status: 'off' | 'connecting' | 'ready' | 'error';
error: string | null;
user: { id: string; name: string; avatar: string | null } | null;
guild: { id: string; name: string; icon: string | null } | null;
guilds: { id: string; name: string }[];
recording: { active: boolean; channel: string | null; channelId: string | null; since: number | null; participants: string[]; reason: 'follow' | 'command' | null };
}
/**
* 디스코드 봇: 나를 따라 음성채널에 들어가거나(/녹음시작) 명령으로 참여하고, TTS 로 녹음 사실을 알린다 (Q7, Q8).
* 채팅 메시지는 보내지 않는다. 명령 응답은 본인에게만 보인다.
*/
export class Bot {
client: Client | null = null;
private connection: VoiceConnection | null = null;
private player: AudioPlayer | null = null;
private sessionId: string | null = null;
private emptyTimer: NodeJS.Timeout | null = null;
state: BotState = {
status: 'off',
error: null,
user: null,
guild: null,
guilds: [],
recording: { active: false, channel: null, channelId: null, since: null, participants: [], reason: null },
};
constructor(
private store: Store,
private recorder: Recorder,
private announcer: Announcer,
private bus: Bus,
private settings: () => Settings,
private onGuild?: (guildId: string) => void,
) {}
async start(token: string): Promise<void> {
await this.stop();
this.state.status = 'connecting';
this.state.error = null;
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers],
});
this.client = client;
client.on(Events.ClientReady, () => void this.onReady());
client.on(Events.VoiceStateUpdate, (o, n) => void this.onVoiceState(o, n).catch((e) => log.error('voiceState 처리 오류', e)));
client.on(Events.InteractionCreate, (i) => {
if (i.isChatInputCommand()) void this.onCommand(i).catch((e) => log.error('명령 처리 오류', e));
});
client.on(Events.Error, (e) => log.error('discord 오류', e));
client.on(Events.GuildCreate, () => this.refreshGuilds());
try {
await client.login(token);
} catch (e: any) {
this.state.status = 'error';
this.state.error = e?.message?.includes('TOKEN_INVALID') || e?.code === 'TokenInvalid' ? '봇 토큰이 올바르지 않습니다' : e.message;
this.client = null;
throw e;
}
}
async stop(): Promise<void> {
this.leave('stop');
if (this.client) {
await this.client.destroy();
this.client = null;
}
this.state.status = 'off';
}
private refreshGuilds(): void {
if (!this.client) return;
this.state.guilds = [...this.client.guilds.cache.values()].map((g) => ({ id: g.id, name: g.name }));
}
guild(): Guild | null {
if (!this.client) return null;
const id = this.settings().discord.guildId;
return (id && this.client.guilds.cache.get(id)) || this.client.guilds.cache.first() || null;
}
private async onReady(): Promise<void> {
const c = this.client!;
this.state.status = 'ready';
this.state.user = { id: c.user!.id, name: c.user!.username, avatar: c.user!.displayAvatarURL({ size: 128 }) };
this.refreshGuilds();
const g = this.guild();
log.info(`봇 로그인: ${c.user!.tag}, 서버 ${this.state.guilds.map((x) => x.name).join(', ')}`);
if (!g) return;
this.state.guild = { id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) };
this.onGuild?.(g.id);
if (this.settings().discord.commandsEnabled) {
try {
await g.commands.set(COMMANDS);
log.info('슬래시 명령 등록 완료');
} catch (e) {
log.warn('슬래시 명령 등록 실패', e);
}
}
// 이미 따라갈 유저가 음성채널에 있으면 바로 들어간다
const follow = this.settings().discord.followUserId;
if (follow && this.settings().discord.followEnabled) {
const m = await g.members.fetch(follow).catch(() => null);
if (m?.voice.channel) await this.join(m.voice.channel, 'follow');
}
}
private async onVoiceState(o: VoiceState, n: VoiceState): Promise<void> {
const g = this.guild();
if (!g || n.guild.id !== g.id) return;
const s = this.settings().discord;
const uid = n.id;
if (uid === this.client?.user?.id) {
// 누군가 봇을 끊었으면 세션 종료
if (o.channelId && !n.channelId) this.leave('kicked');
return;
}
// 따라가기
if (s.followEnabled && s.followUserId === uid && o.channelId !== n.channelId) {
if (n.channel) await this.join(n.channel, 'follow');
else if (this.state.recording.reason === 'follow') this.leave('follow-left');
}
const myCh = this.state.recording.channelId;
if (!myCh) return;
// 새 사람이 들어오면 안내를 다시 튼다
if (n.channelId === myCh && o.channelId !== myCh && n.member && !n.member.user.bot) {
this.touchUser(n.member);
this.updateParticipants();
if (s.ttsEnabled && s.ttsOnNewMember) void this.announce();
}
if (o.channelId === myCh && n.channelId !== myCh) this.updateParticipants();
}
private touchUser(m: GuildMember): void {
this.store.upsertUser({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }) });
}
private updateParticipants(): void {
const ch = this.currentChannel();
const humans = ch ? [...ch.members.values()].filter((m) => !m.user.bot) : [];
this.state.recording.participants = humans.map((m) => m.id);
this.emitState();
// 사람이 아무도 없으면 30초 뒤 나간다
if (this.emptyTimer) clearTimeout(this.emptyTimer);
this.emptyTimer = null;
if (ch && humans.length === 0) this.emptyTimer = setTimeout(() => this.leave('empty'), 30000);
}
private currentChannel(): VoiceBasedChannel | null {
const id = this.state.recording.channelId;
if (!id || !this.client) return null;
const ch = this.client.channels.cache.get(id);
return ch && (ch.type === ChannelType.GuildVoice || ch.type === ChannelType.GuildStageVoice) ? (ch as VoiceBasedChannel) : null;
}
async join(channel: VoiceBasedChannel, reason: 'follow' | 'command'): Promise<void> {
if (this.state.recording.channelId === channel.id && this.connection) return;
if (this.connection) this.leave('move');
log.info(`음성채널 참여: ${channel.name} (${reason})`);
const conn = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
daveEncryption: true,
});
this.connection = conn;
conn.on('error', (e) => log.error('음성 연결 오류', e));
conn.on(VoiceConnectionStatus.Disconnected, async () => {
try {
await Promise.race([
entersState(conn, VoiceConnectionStatus.Signalling, 5000),
entersState(conn, VoiceConnectionStatus.Connecting, 5000),
]);
} catch {
if (this.connection === conn) this.leave('disconnected');
}
});
try {
await entersState(conn, VoiceConnectionStatus.Ready, 20000);
} catch (e) {
log.error('음성채널 연결 실패', e);
conn.destroy();
if (this.connection === conn) this.connection = null;
throw new Error('음성채널 연결 실패');
}
const now = Date.now();
this.sessionId = newId(now);
this.store.startSession(this.sessionId, channel.guild.id, channel.id, channel.name, now);
for (const m of channel.members.values()) if (!m.user.bot) this.touchUser(m);
this.bus.live({ type: 'users.updated', data: [] });
this.state.recording = { active: true, channel: channel.name, channelId: channel.id, since: now, participants: [], reason };
this.recorder.attach(conn, this.sessionId);
this.player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause } });
conn.subscribe(this.player);
this.updateParticipants();
if (this.settings().discord.ttsEnabled) void this.announce();
}
leave(why: string): void {
if (this.emptyTimer) clearTimeout(this.emptyTimer);
this.emptyTimer = null;
this.recorder.detach();
if (this.connection) {
log.info(`음성채널 나감 (${why})`);
try {
this.connection.destroy();
} catch {
/* 이미 끊김 */
}
}
this.connection = null;
this.player?.stop(true);
this.player = null;
if (this.sessionId) this.store.endSession(this.sessionId, Date.now());
this.sessionId = null;
if (this.state.recording.active) {
this.state.recording = { active: false, channel: null, channelId: null, since: null, participants: [], reason: null };
this.emitState();
}
}
async announce(): Promise<void> {
if (!this.player) return;
const s = this.settings().discord;
try {
const file = await this.announcer.ensure(s.ttsText, s.ttsVoice);
if (!this.player) return;
const res = createAudioResource(fs.createReadStream(file), { inputType: StreamType.WebmOpus });
this.player.play(res);
await entersState(this.player, AudioPlayerStatus.Playing, 5000).catch(() => undefined);
} catch (e) {
log.warn('안내 음성 재생 실패', e);
}
}
private emitState(): void {
const r = this.state.recording;
this.bus.live({ type: 'recording.state', data: { active: r.active, channel: r.channel, since: r.since, participants: r.participants } });
}
private async onCommand(i: ChatInputCommandInteraction): Promise<void> {
const reply = (content: string) => i.reply({ content, flags: MessageFlags.Ephemeral });
const member = i.member as GuildMember | null;
switch (i.commandName) {
case '녹음시작': {
const ch = member?.voice?.channel;
if (!ch) return void (await reply('먼저 음성채널에 들어가 주세요.'));
await i.deferReply({ flags: MessageFlags.Ephemeral });
try {
await this.join(ch, 'command');
await i.editReply(`🎙️ ${ch.name} 채널 녹음을 시작했습니다.`);
} catch (e: any) {
await i.editReply(`음성채널에 들어가지 못했습니다: ${e.message}`);
}
return;
}
case '녹음종료':
if (!this.connection) return void (await reply('지금은 녹음 중이 아닙니다.'));
this.leave('command');
return void (await reply('⏹️ 녹음을 끝냈습니다.'));
case '녹음제외':
if (member) this.touchUser(member);
this.store.setExcluded(i.user.id, true);
this.bus.live({ type: 'users.updated', data: [] });
return void (await reply('🔇 이제부터 내 목소리는 녹음하지 않습니다. 다시 참여하려면 /녹음참여 를 입력하세요.'));
case '녹음참여':
if (member) this.touchUser(member);
this.store.setExcluded(i.user.id, false);
this.bus.live({ type: 'users.updated', data: [] });
return void (await reply('🎙️ 다시 녹음에 참여합니다.'));
}
}
}

129
app/src/core/discord/ogg.ts Normal file
View File

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

View File

@@ -0,0 +1,151 @@
import fs from 'node:fs';
import path from 'node:path';
import { EndBehaviorType, type VoiceConnection } from '@discordjs/voice';
import type { Store } from '../db/db.js';
import type { SttPipeline } from '../stt/pipeline.js';
import type { Timeline } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { newId } from '../util/ids.js';
import { logger } from '../util/log.js';
import { OggOpusWriter, SILENCE_FRAME } from './ogg.js';
const log = logger('rec');
export interface RecorderOptions {
audioDir: () => string;
silenceMs: () => number;
maxUtteranceSec: () => number;
/** 이 유저를 녹음하지 않는다 (/녹음제외, 봇) */
skip: (userId: string) => boolean;
/** ts 시점 진행 중인 경기 ID */
matchAt: (ts: number) => string | null;
}
/** 발화 하나 = 파일 하나. 말이 0.8초 끊기면 끝, 최대 30초 (보고서 4장 1~3단계) */
class Utterance {
writer: OggOpusWriter;
id: string;
startedAt: number;
lastArrival: number;
constructor(dir: string, now: number) {
this.id = newId(now);
this.startedAt = now;
this.lastArrival = now;
const day = localDay(now);
const d = path.join(dir, day);
fs.mkdirSync(d, { recursive: true });
this.writer = new OggOpusWriter(path.join(d, `${this.id}.ogg`));
}
}
function localDay(ts: number): string {
const d = new Date(ts);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export class Recorder {
private active = new Map<string, Utterance>();
private connection: VoiceConnection | null = null;
private sessionId: string | null = null;
private onSpeak = (userId: string) => this.subscribe(userId);
constructor(
private store: Store,
private stt: SttPipeline,
private timeline: Timeline,
private bus: Bus,
private opts: RecorderOptions,
) {}
attach(connection: VoiceConnection, sessionId: string): void {
this.detach();
this.connection = connection;
this.sessionId = sessionId;
connection.receiver.speaking.on('start', this.onSpeak);
}
detach(): void {
if (this.connection) {
this.connection.receiver.speaking.off('start', this.onSpeak);
for (const s of this.connection.receiver.subscriptions.values()) s.destroy();
}
for (const userId of [...this.active.keys()]) this.finish(userId);
this.connection = null;
this.sessionId = null;
}
private subscribe(userId: string): void {
const conn = this.connection;
if (!conn || conn.receiver.subscriptions.has(userId)) return;
if (this.opts.skip(userId)) return;
const stream = conn.receiver.subscribe(userId, {
end: { behavior: EndBehaviorType.AfterSilence, duration: this.opts.silenceMs() },
});
stream.on('data', (packet: Buffer) => this.onPacket(userId, packet));
stream.once('end', () => this.finish(userId));
stream.once('close', () => this.finish(userId));
stream.on('error', (e) => log.warn(`수신 오류 (${userId})`, e));
}
private onPacket(userId: string, packet: Buffer): void {
// 녹음 도중 /녹음제외 하면 바로 버린다
if (this.opts.skip(userId)) {
const cur = this.active.get(userId);
if (cur) this.discard(userId, cur);
return;
}
const now = Date.now();
let u = this.active.get(userId);
if (!u) {
u = new Utterance(this.opts.audioDir(), now - 20);
this.active.set(userId, u);
} else {
// 말 사이 짧은 쉼은 디스코드가 패킷을 안 보낸다. 무음 프레임으로 채워 실제 시간과 맞춘다.
const gap = now - u.lastArrival;
const missing = Math.round(gap / 20) - 1;
if (missing > 0 && missing * 20 < this.opts.silenceMs() + 200) for (let i = 0; i < missing; i++) u.writer.write(SILENCE_FRAME);
}
u.lastArrival = now;
u.writer.write(packet);
if (u.writer.samples >= this.opts.maxUtteranceSec() * 48000) {
this.finish(userId);
}
}
private discard(userId: string, u: Utterance): void {
this.active.delete(userId);
u.writer.close();
fs.rmSync(u.writer.path, { force: true });
}
private finish(userId: string): void {
const u = this.active.get(userId);
if (!u) return;
this.active.delete(userId);
u.writer.close();
const dur = u.writer.durationMs;
// 0.25초보다 짧으면 버린다 (키 클릭, 끊긴 패킷)
if (dur < 250) {
fs.rmSync(u.writer.path, { force: true });
return;
}
const endedAt = u.startedAt + dur;
const matchId = this.opts.matchAt(u.startedAt);
const row = this.store.insertUtterance({
id: u.id,
session_id: this.sessionId,
user_id: userId,
started_at: u.startedAt,
ended_at: endedAt,
audio_path: u.writer.path,
match_id: matchId,
});
this.bus.live({ type: 'utterance.created', data: this.timeline.utteranceItem(row) });
this.stt.enqueue(row.id, 'realtime');
log.debug(`발화 저장 ${userId} ${dur}ms ${u.writer.bytes}B`);
}
get speaking(): string[] {
return [...this.active.keys()];
}
}

View File

@@ -0,0 +1,64 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { MsEdgeTTS, OUTPUT_FORMAT } from 'msedge-tts';
import { DEFAULT_TTS_TEXT } from '../settings.js';
import { logger } from '../util/log.js';
const log = logger('tts');
/**
* 녹음 안내 음성. 미리 합성해서 캐시하고, 문구를 바꾸면 다시 합성한다 (보고서 7-3).
* 합성은 Microsoft Edge 온라인 TTS(무료). 인터넷이 안 되면 기본 문구 음성(앱에 포함)을 쓴다.
*/
export class Announcer {
constructor(
private cacheDir: string,
private resourcesDir: string,
) {}
private bundled(): string {
return path.join(this.resourcesDir, 'tts', 'announce-default.webm');
}
cachedPath(text: string, voice: string): string {
const h = crypto.createHash('sha1').update(`${voice}\n${text}`).digest('hex').slice(0, 16);
return path.join(this.cacheDir, `announce-${h}.webm`);
}
/** 안내 음성 파일 경로 (WebM Opus). 없으면 합성. */
async ensure(text: string, voice: string): Promise<string> {
const p = this.cachedPath(text, voice);
if (fs.existsSync(p) && fs.statSync(p).size > 1000) return p;
if (text === DEFAULT_TTS_TEXT && voice === 'ko-KR-SunHiNeural' && fs.existsSync(this.bundled())) return this.bundled();
try {
await synthesize(text, voice, p);
log.info(`안내 음성 합성: ${path.basename(p)}`);
return p;
} catch (e) {
log.warn('안내 음성 합성 실패, 기본 음성 사용', e);
return this.bundled();
}
}
}
export async function synthesize(text: string, voice: string, outFile: string): Promise<void> {
fs.mkdirSync(path.dirname(outFile), { recursive: true });
const tts = new MsEdgeTTS();
const tmpDir = fs.mkdtempSync(path.join(path.dirname(outFile), '.tts-'));
try {
await tts.setMetadata(voice, OUTPUT_FORMAT.WEBM_24KHZ_16BIT_MONO_OPUS);
const r = await Promise.race([
tts.toFile(tmpDir, text),
new Promise<never>((_, rej) => setTimeout(() => rej(new Error('TTS 시간 초과')), 20000)),
]);
fs.renameSync(r.audioFilePath, outFile);
} finally {
try {
tts.close();
} catch {
/* 무시 */
}
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}

View File

@@ -0,0 +1,180 @@
import fs from 'node:fs';
import path from 'node:path';
import { logger } from '../util/log.js';
import { request } from './riot.js';
const log = logger('assets');
/**
* 게임 이미지·이름 목록 (보고서 7-7). 원본 URL 을 사이트 서버의 캐시 경로(/game-assets/...)로 바꿔서 준다.
* - 발로란트: valorant-api.com (ko-KR 이름, 미니맵 좌표 변환값)
* - 롤: Riot Data Dragon (ko_KR), 오브젝트 아이콘은 Community Dragon
*/
export function assetUrl(url: string | null | undefined): string | null {
if (!url) return null;
return url
.replace('https://media.valorant-api.com/', '/game-assets/valmedia/')
.replace('https://ddragon.leagueoflegends.com/', '/game-assets/ddragon/')
.replace('https://raw.communitydragon.org/', '/game-assets/cdragon/');
}
export const LOL_OBJECT_ICON: Record<string, string> = {
baron: 'baron.png',
herald: 'riftherald.png',
grub: 'grub.png',
tower: 'tower.png',
inhibitor: 'inhibitor.png',
atakhan: 'atakhan.png',
dragon: 'dragon.png',
dragon_fire: 'dragon_infernal.png',
dragon_earth: 'dragon_mountain.png',
dragon_water: 'dragon_ocean.png',
dragon_air: 'dragon_cloud.png',
dragon_hextech: 'dragon_hextech.png',
dragon_chemtech: 'dragon_chemtech.png',
dragon_elder: 'dragon_elder.png',
};
export function lolObjectIcon(key: string): string {
return `/game-assets/cdragon/latest/game/assets/ux/minimap/icons/${LOL_OBJECT_ICON[key] || 'dragon.png'}`;
}
interface ValCatalog {
at: number;
agents: Record<string, { name: string; icon: string; abilities: Record<string, { name: string; icon: string | null }> }>;
maps: Record<string, { uuid: string; name: string; image: string | null; xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }>;
weapons: Record<string, { name: string; icon: string | null }>;
tiers: Record<number, string>;
modes: Record<string, string>;
clientVersion: string | null;
}
interface LolCatalog {
at: number;
version: string;
champions: Record<string, { id: string; key: string; name: string; icon: string }>;
items: Record<string, { name: string; icon: string; gold: number }>;
}
const DAY = 24 * 3600 * 1000;
export class GameAssets {
val: ValCatalog | null = null;
lol: LolCatalog | null = null;
constructor(private cacheDir: string) {
fs.mkdirSync(cacheDir, { recursive: true });
this.val = this.readCache('valorant.json');
this.lol = this.readCache('lol.json');
}
private readCache<T>(name: string): T | null {
try {
return JSON.parse(fs.readFileSync(path.join(this.cacheDir, name), 'utf8'));
} catch {
return null;
}
}
private writeCache(name: string, v: unknown): void {
fs.writeFileSync(path.join(this.cacheDir, name), JSON.stringify(v));
}
async refresh(force = false): Promise<void> {
await Promise.all([this.refreshVal(force).catch((e) => log.warn('발로란트 목록 갱신 실패', e)), this.refreshLol(force).catch((e) => log.warn('롤 목록 갱신 실패', e))]);
}
async refreshVal(force = false): Promise<void> {
if (!force && this.val && Date.now() - this.val.at < DAY) return;
const get = async (p: string) => (await request(`https://valorant-api.com/v1/${p}`, { timeoutMs: 20000 })).data?.data;
const [agents, maps, weapons, tiers, modes, version] = await Promise.all([
get('agents?language=ko-KR&isPlayableCharacter=true'),
get('maps?language=ko-KR'),
get('weapons?language=ko-KR'),
get('competitivetiers?language=ko-KR'),
get('gamemodes?language=ko-KR'),
get('version'),
]);
const cat: ValCatalog = { at: Date.now(), agents: {}, maps: {}, weapons: {}, tiers: {}, modes: {}, clientVersion: version?.riotClientVersion ?? null };
for (const a of agents || []) {
const abilities: ValCatalog['agents'][string]['abilities'] = {};
for (const ab of a.abilities || []) abilities[ab.slot] = { name: ab.displayName, icon: assetUrl(ab.displayIcon) };
cat.agents[a.uuid.toLowerCase()] = { name: a.displayName, icon: assetUrl(a.displayIcon)!, abilities };
}
for (const m of maps || [])
cat.maps[m.mapUrl] = {
uuid: m.uuid,
name: m.displayName,
image: assetUrl(m.displayIcon),
xMultiplier: m.xMultiplier,
yMultiplier: m.yMultiplier,
xScalarToAdd: m.xScalarToAdd,
yScalarToAdd: m.yScalarToAdd,
};
for (const w of weapons || []) cat.weapons[w.uuid.toLowerCase()] = { name: w.displayName, icon: assetUrl(w.killStreamIcon || w.displayIcon) };
const lastTiers = (tiers || [])[tiers?.length - 1];
for (const t of lastTiers?.tiers || []) cat.tiers[t.tier] = t.tierName;
for (const gm of modes || []) if (gm.assetPath) cat.modes[gm.assetPath] = gm.displayName;
this.val = cat;
this.writeCache('valorant.json', cat);
log.info(`발로란트 목록 갱신: 요원 ${Object.keys(cat.agents).length}, 맵 ${Object.keys(cat.maps).length}`);
}
async refreshLol(force = false): Promise<void> {
if (!force && this.lol && Date.now() - this.lol.at < DAY) return;
const versions = (await request('https://ddragon.leagueoflegends.com/api/versions.json', { timeoutMs: 20000 })).data;
const v = versions[0];
const base = `https://ddragon.leagueoflegends.com/cdn/${v}`;
const champs = (await request(`${base}/data/ko_KR/champion.json`, { timeoutMs: 30000 })).data.data;
const items = (await request(`${base}/data/ko_KR/item.json`, { timeoutMs: 30000 })).data.data;
const cat: LolCatalog = { at: Date.now(), version: v, champions: {}, items: {} };
for (const c of Object.values<any>(champs)) {
const entry = { id: c.id, key: c.key, name: c.name, icon: assetUrl(`${base}/img/champion/${c.image.full}`)! };
cat.champions[c.id.toLowerCase()] = entry;
cat.champions[`key:${c.key}`] = entry;
cat.champions[`name:${c.name}`] = entry;
}
for (const [id, it] of Object.entries<any>(items)) cat.items[id] = { name: it.name, icon: assetUrl(`${base}/img/item/${id}.png`)!, gold: it.gold?.total ?? 0 };
this.lol = cat;
this.writeCache('lol.json', cat);
log.info(`롤 목록 갱신: ${v}, 챔피언 ${Object.keys(champs).length}`);
}
// ---- 발로란트 조회
agent(id: string | null | undefined) {
const a = id ? this.val?.agents[id.toLowerCase()] : undefined;
return { id: id || '', name: a?.name ?? '?', icon: a?.icon ?? null };
}
valMap(mapUrl: string | null | undefined) {
return mapUrl ? this.val?.maps[mapUrl] : undefined;
}
/** 킬 무기·스킬 이름 */
damageItem(agentId: string | null, type: string, item: string): { id: string; name: string; icon: string | null } | null {
if (type === 'Weapon' && item) {
const w = this.val?.weapons[item.toLowerCase()];
return { id: item.toLowerCase(), name: w?.name ?? '무기', icon: w?.icon ?? null };
}
if (type === 'Ability' && agentId) {
const ab = this.val?.agents[agentId.toLowerCase()]?.abilities[item];
return { id: item, name: ab?.name ?? '스킬', icon: ab?.icon ?? null };
}
if (type === 'Bomb') return { id: 'spike', name: '스파이크', icon: null };
if (type === 'Melee') return { id: 'melee', name: '근접 무기', icon: null };
return item || type ? { id: item || type, name: type === 'Fall' ? '낙사' : item || type, icon: null } : null;
}
// ---- 롤 조회
champion(raw: string | null | undefined, localized?: string) {
const cat = this.lol;
let c: LolCatalog['champions'][string] | undefined;
if (raw && cat) {
const m = /game_character_displayname_(\w+)/.exec(raw);
c = cat.champions[(m ? m[1] : raw).toLowerCase()] || cat.champions[`key:${raw}`];
}
if (!c && localized && cat) c = cat.champions[`name:${localized}`];
return { id: c?.id ?? raw ?? '', name: c?.name ?? localized ?? raw ?? '?', icon: c?.icon ?? null };
}
item(id: number) {
const it = this.lol?.items[String(id)];
return { id, name: it?.name ?? String(id), icon: it?.icon ?? null, gold: it?.gold ?? 0 };
}
lolMapImage(): string {
return assetUrl(`https://ddragon.leagueoflegends.com/cdn/${this.lol?.version ?? '16.20.1'}/img/map/map11.png`)!;
}
}

616
app/src/core/games/lol.ts Normal file
View File

@@ -0,0 +1,616 @@
import type { ChatData, KillData, MatchPlayer, ObjectData, PlayerRef } from '@gvr/shared';
import type { EventRow } from '../db/db.js';
import { logger } from '../util/log.js';
import { lolObjectIcon } from './assets.js';
import { basicAuth, findLcu, request } from './riot.js';
import type { AdapterHost, GameAdapter } from './types.js';
const log = logger('lol');
const LIVE = () => process.env.GVR_LOL_LIVE_URL || 'https://127.0.0.1:2999';
interface LiveMatch {
id: string;
gameId: number | null;
startedAt: number;
selfName: string | null;
selfTeam: string | null;
players: any[];
seenEvents: Set<number>;
failures: number;
goldDiff: { t: number; diff: number }[];
lastGoldAt: number;
lastSnapshotAt: number;
ended: boolean;
}
const DRAGON: Record<string, string> = {
Fire: 'dragon_fire',
Earth: 'dragon_earth',
Water: 'dragon_water',
Air: 'dragon_air',
Hextech: 'dragon_hextech',
Chemtech: 'dragon_chemtech',
Elder: 'dragon_elder',
};
const DRAGON_KO: Record<string, string> = {
Fire: '화염의 용',
Earth: '대지의 용',
Water: '바다의 용',
Air: '바람의 용',
Hextech: '마법공학 용',
Chemtech: '화학공학 용',
Elder: '장로 드래곤',
};
/**
* 리그 오브 레전드 어댑터 (보고서 6-5).
* - 게임 클라이언트 API(127.0.0.1:2999): 게임 시간, 10명 KDA·CS·아이템, 킬·오브젝트 이벤트
* - 롤 클라이언트(LCU): 경기 ID·결과·경기 기록(타임라인), 챔피언 선택·게임 후 채팅
* - 게임 중 채팅: 화면 OCR (STT 워커) 또는 로그 파일(남아 있을 때)
*/
export class LolAdapter implements GameAdapter {
readonly game = 'lol' as const;
private timer: NodeJS.Timeout | null = null;
private lcuTimer: NodeJS.Timeout | null = null;
private live: LiveMatch | null = null;
private lcu: { port: number; password: string; installDir: string | null } | null = null;
private lcuCheckedAt = 0;
private polling = false;
private seenChat = new Set<string>();
private pendingChat: EventRow[] = [];
private detailQueue = new Map<string, { gameId: number; tries: number; endedAt: number; startedAt: number }>();
private summonerNames = new Map<string, string>();
private ocrSeen = new Set<string>();
private lastMatchId: string | null = null;
private lastErr = '';
constructor(private host: AdapterHost) {
host.worker.on('event', (ev: any) => {
if (ev.event === 'ocr_line') this.onOcrLine(ev);
});
}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.tick(), Number(process.env.GVR_POLL_MS) || 2000);
this.lcuTimer = setInterval(() => void this.lcuTick(), (Number(process.env.GVR_POLL_MS) || 2000) * 2.5);
}
stop(): void {
if (this.timer) clearInterval(this.timer);
if (this.lcuTimer) clearInterval(this.lcuTimer);
this.timer = this.lcuTimer = null;
if (this.live) void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
}
status() {
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
}
private async lcuGet<T = any>(path: string): Promise<T | null> {
if (!this.lcu) return null;
try {
const r = await request<T>(`https://127.0.0.1:${this.lcu.port}${path}`, { headers: { authorization: basicAuth(this.lcu.password) }, local: true });
return r.status === 200 ? r.data : null;
} catch {
this.lcu = null;
return null;
}
}
// ------------------------------------------------------------------ 게임 클라이언트 API
private async tick(): Promise<void> {
if (this.polling || !this.host.settings().games.lol) return;
this.polling = true;
try {
let data: any = null;
try {
const r = await request(`${LIVE()}/liveclientdata/allgamedata`, { local: true, timeoutMs: 1500 });
if (r.status === 200 && r.data?.gameData) data = r.data;
} catch {
/* 게임 중이 아님 */
}
if (data) await this.onLive(data);
else if (this.live && !this.live.ended && ++this.live.failures >= 3) this.endMatch(null);
await this.pollDetails();
this.lastErr = '';
} catch (e: any) {
this.lastErr = e.message;
log.debug('롤 폴링 오류', e);
} finally {
this.polling = false;
}
}
private async onLive(d: any): Promise<void> {
const gameTime = Number(d.gameData.gameTime) || 0;
if (gameTime <= 0) return; // 로딩 화면
const now = Date.now();
if (!this.live || this.live.ended) {
if (this.live?.ended) return; // 결과 화면에서도 API 가 잠깐 살아 있다
let gameId: number | null = null;
const sess = await this.lcuGet<any>('/lol-gameflow/v1/session');
gameId = sess?.gameData?.gameId ?? null;
const id = `lol-${gameId ?? now}`;
const selfName = d.activePlayer?.riotId || d.activePlayer?.summonerName || null;
const me = (d.allPlayers || []).find((p: any) => p.riotId === selfName || p.summonerName === selfName);
this.live = {
id,
gameId,
startedAt: now - gameTime * 1000,
selfName,
selfTeam: me?.team ?? null,
players: d.allPlayers || [],
seenEvents: new Set(),
failures: 0,
goldDiff: [],
lastGoldAt: 0,
lastSnapshotAt: 0,
ended: false,
};
this.lastMatchId = id;
this.ocrSeen.clear();
this.host.matchStarted({
id,
game: 'lol',
startedAt: this.live.startedAt,
map: d.gameData.mapName || 'Map11',
mode: d.gameData.gameMode || null,
queue: sess?.gameData?.queue?.description ?? null,
detail: { live: true, players: this.snapshotPlayers(d.allPlayers || []) },
});
// 버퍼해 둔 챔피언 선택 채팅을 이 경기에 붙인다
for (const e of this.pendingChat) this.host.event({ ...e, match_id: id, id: `${id}:${e.id}` });
this.pendingChat = [];
void this.startOcr();
log.info(`롤 경기 시작 감지 ${id}`);
}
const m = this.live;
m.failures = 0;
m.players = d.allPlayers || m.players;
// 게임 시간과 PC 시계로 시작 시각을 계속 다듬는다 (가장 이른 값 = 지연이 가장 적은 값)
m.startedAt = Math.min(m.startedAt, now - gameTime * 1000);
for (const ev of d.events?.Events || []) {
if (m.seenEvents.has(ev.EventID)) continue;
m.seenEvents.add(ev.EventID);
const row = this.liveEvent(m, ev);
if (row) this.host.event(row);
if (ev.EventName === 'GameEnd') this.endMatch(ev.Result === 'Win');
}
if (now - m.lastGoldAt >= 30000) {
m.lastGoldAt = now;
m.goldDiff.push({ t: Math.round(gameTime * 1000), diff: this.itemGoldDiff(m) });
}
if (now - m.lastSnapshotAt >= 10000) {
m.lastSnapshotAt = now;
this.host.matchUpdated(m.id, {
detail: JSON.stringify({ live: true, players: this.snapshotPlayers(m.players), goldDiff: m.goldDiff, goldEstimated: true }),
});
}
}
private findPlayer(m: LiveMatch, name: string | undefined): any {
if (!name) return null;
return m.players.find((p) => p.riotIdGameName === name || p.riotId === name || p.summonerName === name || p.riotId?.split('#')[0] === name) ?? null;
}
private ref(m: LiveMatch, name: string | undefined): PlayerRef | null {
if (!name) return null;
const p = this.findPlayer(m, name);
if (!p) return { name: prettyUnit(name) };
return { name: p.riotIdGameName || p.summonerName || name, team: p.team, character: this.host.assets.champion(p.rawChampionName, p.championName) };
}
private liveEvent(m: LiveMatch, ev: any): EventRow | null {
const t = Math.round((ev.EventTime || 0) * 1000);
const base = { match_id: m.id, game: 'lol' as const, ts: m.startedAt + t, game_time_ms: t, round: null, actor_puuid: null, target_puuid: null };
const id = `${m.id}:live:${ev.EventID}`;
const allyOf = (team: string | undefined) => (team && m.selfTeam ? team === m.selfTeam : undefined);
switch (ev.EventName) {
case 'ChampionKill': {
const killer = this.ref(m, ev.KillerName);
const data: KillData = {
killer,
victim: this.ref(m, ev.VictimName)!,
assists: (ev.Assisters || []).map((a: string) => this.ref(m, a)!).filter(Boolean),
weapon: null,
ally: allyOf(killer?.team),
};
return { ...base, id, type: 'kill', data: JSON.stringify(data) };
}
case 'DragonKill':
case 'BaronKill':
case 'HeraldKill':
case 'HordeKill':
case 'AtakhanKill': {
const killer = this.ref(m, ev.KillerName);
const object: ObjectData['object'] =
ev.EventName === 'DragonKill' ? 'dragon' : ev.EventName === 'BaronKill' ? 'baron' : ev.EventName === 'HeraldKill' ? 'herald' : ev.EventName === 'HordeKill' ? 'grub' : 'atakhan';
const key = object === 'dragon' ? DRAGON[ev.DragonType] || 'dragon' : object;
const data: ObjectData & { icon: string; label: string; stolen?: boolean } = {
object,
subtype: ev.DragonType,
team: killer?.team,
killer,
ally: allyOf(killer?.team),
icon: lolObjectIcon(key),
label: object === 'dragon' ? DRAGON_KO[ev.DragonType] || '드래곤' : { baron: '내셔 남작', herald: '협곡의 전령', grub: '공허 유충', atakhan: '아타칸' }[object as string] || object,
stolen: ev.Stolen === 'True' || ev.Stolen === true,
};
return { ...base, id, type: 'object', data: JSON.stringify(data) };
}
case 'TurretKilled':
case 'InhibKilled': {
const name: string = ev.TurretKilled || ev.InhibKilled || '';
// T1 = 블루(ORDER) 건물 → 레드가 부숨
const destroyedBy = /_T1_/.test(name) ? 'CHAOS' : /_T2_/.test(name) ? 'ORDER' : undefined;
const object = ev.EventName === 'TurretKilled' ? 'tower' : 'inhibitor';
const data = {
object,
team: destroyedBy,
killer: this.ref(m, ev.KillerName),
ally: allyOf(destroyedBy),
icon: lolObjectIcon(object),
label: object === 'tower' ? '포탑 파괴' : '억제기 파괴',
};
return { ...base, id, type: 'object', data: JSON.stringify(data) };
}
case 'Multikill': {
const p = this.ref(m, ev.KillerName);
return { ...base, id, type: 'multikill', data: JSON.stringify({ player: p, count: ev.KillStreak, ally: allyOf(p?.team) }) };
}
case 'Ace': {
const p = this.ref(m, ev.Acer);
return { ...base, id, type: 'ace', data: JSON.stringify({ player: p, team: ev.AcingTeam, ally: allyOf(ev.AcingTeam) }) };
}
case 'GameEnd':
return { ...base, id, type: 'match_end', data: JSON.stringify({ win: ev.Result === 'Win' }) };
default:
return null;
}
}
/** 경기 중 골드 차이 추정: 아이템 가격 합 (경기 후 타임라인 값으로 교체) */
private itemGoldDiff(m: LiveMatch): number {
let ally = 0;
let enemy = 0;
for (const p of m.players) {
const g = (p.items || []).reduce((s: number, it: any) => s + this.host.assets.item(it.itemID).gold * (it.count || 1), 0);
if (p.team === m.selfTeam) ally += g;
else enemy += g;
}
return ally - enemy;
}
private snapshotPlayers(players: any[]): MatchPlayer[] {
const selfTeam = this.live?.selfTeam;
return players.map((p) => ({
puuid: p.puuid || p.riotId || p.summonerName,
name: p.riotIdGameName || p.summonerName,
tag: p.riotIdTagLine,
team: p.team,
ally: p.team === selfTeam,
character: this.host.assets.champion(p.rawChampionName, p.championName),
kills: p.scores?.kills ?? 0,
deaths: p.scores?.deaths ?? 0,
assists: p.scores?.assists ?? 0,
cs: p.scores?.creepScore ?? 0,
level: p.level,
items: (p.items || []).map((it: any) => {
const x = this.host.assets.item(it.itemID);
return { id: it.itemID, name: it.displayName || x.name, icon: x.icon };
}),
}));
}
private endMatch(win: boolean | null): void {
const m = this.live;
if (!m || m.ended) return;
m.ended = true;
const now = Date.now();
void this.host.worker.request('ocr_stop', {}, 5000).catch(() => undefined);
this.host.matchEnded(m.id, now);
this.host.matchUpdated(m.id, {
result: JSON.stringify({ win, score: null }),
detail: JSON.stringify({ live: false, players: this.snapshotPlayers(m.players), goldDiff: m.goldDiff, goldEstimated: true }),
});
if (m.gameId) this.detailQueue.set(m.id, { gameId: m.gameId, tries: 0, endedAt: now, startedAt: m.startedAt });
else this.host.matchUpdated(m.id, { status: 'complete' }, { complete: true });
void this.readLogChat(m);
log.info(`롤 경기 종료 ${m.id}`);
// 결과 화면에서 API 가 살아 있는 동안 다시 시작으로 잡지 않도록 잠시 유지
setTimeout(() => {
if (this.live === m) this.live = null;
}, 60000).unref();
}
// ------------------------------------------------------------------ 채팅 OCR · 로그
private async startOcr(): Promise<void> {
const s = this.host.settings().games;
if (!s.lolChatOcr || process.platform !== 'win32') return;
try {
await this.host.worker.request('ocr_start', { window_title: 'League of Legends (TM) Client', region: s.lolOcrRegion, fps: 3, lang: 'ko' }, 15000);
log.info('롤 채팅 OCR 시작');
} catch (e: any) {
this.lastErr = `채팅 OCR: ${e.message}`;
log.warn('채팅 OCR 시작 실패', e);
}
}
private chatRow(m: LiveMatch, key: string, gameTimeS: number | null, ts: number, p: any, source: ChatData['source']): EventRow {
const sender = this.findPlayer(m, p.sender);
const ts2 = gameTimeS !== null ? m.startedAt + gameTimeS * 1000 : ts;
const data: ChatData = {
sender: {
name: p.sender || '?',
team: sender?.team,
character: sender ? this.host.assets.champion(sender.rawChampionName, sender.championName) : p.champion ? this.host.assets.champion(null, p.champion) : undefined,
},
channel: p.channel || 'all',
text: p.message || '',
source,
};
return {
id: `${m.id}:chat:${source}:${key}`,
match_id: m.id,
game: 'lol',
type: 'chat',
ts: ts2,
game_time_ms: ts2 - m.startedAt,
round: null,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(data),
};
}
private onOcrLine(ev: any): void {
const m = this.live;
if (!m || m.ended || !ev.parsed?.message) return;
const p = ev.parsed;
const key = `${p.game_time ?? ''}|${p.sender ?? ''}|${p.message}`;
if (this.ocrSeen.has(key)) return;
this.ocrSeen.add(key);
const gts = typeof p.game_time_s === 'number' ? p.game_time_s : null;
this.host.event(this.chatRow(m, hash(key), gts, ev.ts || Date.now(), p, 'ocr'));
}
/** 로그 파일에 채팅이 남아 있으면 OCR 보다 정확하므로 그걸로 바꾼다 */
private async readLogChat(m: LiveMatch): Promise<void> {
const dir = this.host.settings().games.lolLogsDir || (this.lcu?.installDir ? `${this.lcu.installDir}\\Logs\\GameLogs` : null);
if (!dir) return;
try {
const r = await this.host.worker.request('r3dlog_read', { logs_dir: dir, since_ms: m.startedAt - 600000 }, 30000);
const lines = r?.lines || [];
if (!lines.length) return;
const rows = lines.map((p: any, i: number) =>
this.chatRow(m, `${i}-${hash(`${p.game_time_s}|${p.sender}|${p.message}`)}`, typeof p.game_time_s === 'number' ? p.game_time_s : null, m.startedAt, p, 'log'),
);
this.host.replaceEvents(m.id, ['chat'], rows);
log.info(`로그 파일 채팅 ${rows.length}줄로 교체`);
} catch (e) {
log.debug('로그 파일 채팅 없음', e);
}
}
// ------------------------------------------------------------------ LCU
private async lcuTick(): Promise<void> {
if (!this.host.settings().games.lol) return;
if (!this.lcu && Date.now() - this.lcuCheckedAt > (Number(process.env.GVR_POLL_MS) ? 0 : 15000)) {
this.lcuCheckedAt = Date.now();
this.lcu = await findLcu().catch(() => null);
if (this.lcu) {
log.info('롤 클라이언트(LCU) 연결');
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`);
}
}
if (!this.lcu) return;
const phase = await this.lcuGet<string>('/lol-gameflow/v1/gameflow-phase');
if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase);
}
private async pollLcuChat(phase: string): Promise<void> {
const convs = (await this.lcuGet<any[]>('/lol-chat/v1/conversations')) || [];
for (const c of convs) {
if (c.type !== 'championSelect' && c.type !== 'postGame') continue;
const msgs = (await this.lcuGet<any[]>(`/lol-chat/v1/conversations/${encodeURIComponent(c.id)}/messages`)) || [];
for (const msg of msgs) {
const key = `${c.id}:${msg.id}`;
if (this.seenChat.has(key) || msg.type === 'system') continue;
this.seenChat.add(key);
const ts = Date.parse(msg.timestamp) || Date.now();
const name = await this.summonerName(msg.fromSummonerId, msg.fromId);
const data: ChatData = { sender: { name }, channel: c.type === 'postGame' ? 'all' : 'team', text: msg.body || '', source: 'lcu' };
const row: EventRow = {
id: `lcu:${hash(key)}`,
match_id: '',
game: 'lol',
type: 'chat',
ts,
game_time_ms: null,
round: null,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(data),
};
const target = c.type === 'postGame' ? this.lastMatchId : this.live && !this.live.ended ? this.live.id : null;
if (target) this.host.event({ ...row, match_id: target, id: `${target}:${row.id}` });
else if (c.type === 'championSelect') this.pendingChat.push(row);
}
}
if (phase !== 'ChampSelect' && phase !== 'InProgress' && this.pendingChat.length && !this.live) this.pendingChat = [];
}
private async summonerName(summonerId: number | undefined, pid: string | undefined): Promise<string> {
const k = String(summonerId ?? pid ?? '');
if (this.summonerNames.has(k)) return this.summonerNames.get(k)!;
let name = '?';
if (summonerId) {
const s = await this.lcuGet<any>(`/lol-summoner/v1/summoners/${summonerId}`);
name = s?.gameName || s?.displayName || name;
}
this.summonerNames.set(k, name);
return name;
}
private async pollDetails(): Promise<void> {
if (!this.detailQueue.size || !this.lcu) return;
for (const [id, q] of this.detailQueue) {
if (Date.now() - q.endedAt < q.tries * (Number(process.env.GVR_DETAIL_RETRY_MS) || 20000)) continue;
q.tries++;
const game = await this.lcuGet<any>(`/lol-match-history/v1/games/${q.gameId}`);
if (!game?.participants) {
if (q.tries >= 15) {
this.detailQueue.delete(id);
this.host.matchUpdated(id, { status: 'complete' }, { complete: true });
}
continue;
}
const timeline = await this.lcuGet<any>(`/lol-match-history/v1/game-timelines/${q.gameId}`);
this.detailQueue.delete(id);
this.applyHistory(id, game, timeline, q.startedAt);
}
}
applyHistory(id: string, game: any, timeline: any, startedAt: number): void {
const res = processLolHistory(game, timeline, this.host, id, startedAt);
if (res.events.length) this.host.replaceEvents(id, ['kill', 'object'], res.events);
this.host.resolvePlayers(res.players.filter((p) => p.puuid && p.tag).map((p) => ({ puuid: p.puuid, riotId: `${p.name}#${p.tag}` })));
this.host.matchUpdated(
id,
{
ended_at: startedAt + (game.gameDuration ?? 0) * 1000,
result: JSON.stringify(res.result),
detail: JSON.stringify({ live: false, players: res.players, goldDiff: res.goldDiff, goldEstimated: !res.goldDiff.length, self: res.self }),
queue: game.queueId ? String(game.queueId) : null,
status: 'complete',
},
{ complete: true },
);
log.info(`롤 경기 기록 적용 ${id}: 타임라인 ${timeline?.frames ? '있음' : '없음'}`);
}
}
/** LCU 경기 기록 + 타임라인 → 선수·이벤트(킬 위치 포함)·골드 그래프. 순수 함수 */
export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHost, 'assets' | 'store'>, id: string, startedAt: number) {
const ident: Record<number, any> = {};
for (const pi of game.participantIdentities || []) ident[pi.participantId] = pi.player || {};
const selfPuuid = host.store.meta('riot_self_puuid');
const selfPart = (game.participants || []).find((p: any) => ident[p.participantId]?.puuid === selfPuuid);
const selfTeam = selfPart?.teamId ?? 100;
const teamName = (t: number) => (t === 100 ? 'ORDER' : 'CHAOS');
const champ = (cid: number) => host.assets.champion(String(cid));
const byPid: Record<number, any> = {};
for (const p of game.participants || []) byPid[p.participantId] = p;
const ref = (pid: number | undefined): PlayerRef | null => {
if (!pid || !byPid[pid]) return pid === 0 ? { name: '미니언·포탑' } : null;
const p = byPid[pid];
const who = ident[pid] || {};
return { puuid: who.puuid, name: who.gameName || who.summonerName || '?', team: teamName(p.teamId), character: champ(p.championId) };
};
const players: MatchPlayer[] = (game.participants || []).map((p: any) => {
const who = ident[p.participantId] || {};
const st = p.stats || {};
return {
puuid: who.puuid || '',
name: who.gameName || who.summonerName || '?',
tag: who.tagLine,
team: teamName(p.teamId),
ally: p.teamId === selfTeam,
character: champ(p.championId),
kills: st.kills ?? 0,
deaths: st.deaths ?? 0,
assists: st.assists ?? 0,
cs: (st.totalMinionsKilled ?? 0) + (st.neutralMinionsKilled ?? 0),
gold: st.goldEarned ?? 0,
level: st.champLevel,
items: [st.item0, st.item1, st.item2, st.item3, st.item4, st.item5, st.item6]
.filter((x: number) => x)
.map((x: number) => {
const it = host.assets.item(x);
return { id: x, name: it.name, icon: it.icon };
}),
};
});
const events: EventRow[] = [];
const goldDiff: { t: number; diff: number }[] = [];
for (const f of timeline?.frames || []) {
let ally = 0;
let enemy = 0;
for (const [pid, pf] of Object.entries<any>(f.participantFrames || {})) {
const team = byPid[Number(pid)]?.teamId;
if (team === selfTeam) ally += pf.totalGold ?? 0;
else enemy += pf.totalGold ?? 0;
}
goldDiff.push({ t: f.timestamp, diff: ally - enemy });
for (const e of f.events || []) {
const t = e.timestamp ?? 0;
const base = { match_id: id, game: 'lol' as const, ts: startedAt + t, game_time_ms: t, round: null, target_puuid: null };
if (e.type === 'CHAMPION_KILL') {
const killer = ref(e.killerId);
const data: KillData = {
killer,
victim: ref(e.victimId)!,
assists: (e.assistingParticipantIds || []).map((x: number) => ref(x)!).filter(Boolean),
weapon: null,
location: e.position ?? null,
ally: byPid[e.killerId]?.teamId === selfTeam,
};
events.push({ ...base, id: `${id}:kill:${t}:${e.victimId}`, type: 'kill', actor_puuid: killer?.puuid ?? null, target_puuid: data.victim?.puuid ?? null, data: JSON.stringify(data) });
} else if (e.type === 'ELITE_MONSTER_KILL') {
const mt = String(e.monsterType || '');
const object = mt === 'DRAGON' ? 'dragon' : mt === 'BARON_NASHOR' ? 'baron' : mt === 'RIFTHERALD' ? 'herald' : mt === 'HORDE' ? 'grub' : mt === 'ATAKHAN' ? 'atakhan' : 'dragon';
const sub = String(e.monsterSubType || '');
const dk = sub.includes('FIRE') ? 'Fire' : sub.includes('EARTH') ? 'Earth' : sub.includes('WATER') ? 'Water' : sub.includes('AIR') ? 'Air' : sub.includes('HEXTECH') ? 'Hextech' : sub.includes('CHEMTECH') ? 'Chemtech' : sub.includes('ELDER') ? 'Elder' : '';
const killer = ref(e.killerId);
const data = {
object,
subtype: dk || undefined,
team: killer?.team,
killer,
ally: byPid[e.killerId]?.teamId === selfTeam,
location: e.position ?? null,
icon: lolObjectIcon(object === 'dragon' ? DRAGON[dk] || 'dragon' : object),
label: object === 'dragon' ? DRAGON_KO[dk] || '드래곤' : { baron: '내셔 남작', herald: '협곡의 전령', grub: '공허 유충', atakhan: '아타칸' }[object] || object,
};
events.push({ ...base, id: `${id}:obj:${t}:${object}`, type: 'object', actor_puuid: killer?.puuid ?? null, data: JSON.stringify(data) });
} else if (e.type === 'BUILDING_KILL') {
const object = e.buildingType === 'INHIBITOR_BUILDING' ? 'inhibitor' : 'tower';
const destroyedBy = e.teamId === 100 ? 'CHAOS' : 'ORDER';
const data = {
object,
team: destroyedBy,
killer: ref(e.killerId),
ally: (e.teamId === 100 ? 200 : 100) === selfTeam,
location: e.position ?? null,
icon: lolObjectIcon(object),
label: object === 'tower' ? '포탑 파괴' : '억제기 파괴',
};
events.push({ ...base, id: `${id}:bld:${t}:${e.position?.x}:${e.position?.y}`, type: 'object', actor_puuid: null, data: JSON.stringify(data) });
}
}
}
const myTeam = (game.teams || []).find((t: any) => t.teamId === selfTeam);
const allyKills = players.filter((p) => p.ally).reduce((s, p) => s + p.kills, 0);
const enemyKills = players.filter((p) => !p.ally).reduce((s, p) => s + p.kills, 0);
return {
players,
events,
goldDiff,
self: selfPuuid,
result: { win: myTeam ? myTeam.win === 'Win' : (selfPart?.stats?.win ?? null), score: { ally: allyKills, enemy: enemyKills } },
};
}
function prettyUnit(name: string): string {
if (/^Turret_/.test(name)) return '포탑';
if (/Minion/.test(name)) return '미니언';
if (/^SRU_/.test(name)) return '몬스터';
return name;
}
function hash(s: string): string {
let h = 2166136261;
for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;
return h.toString(36);
}

View File

@@ -0,0 +1,179 @@
import type { MatchSummary } from '@gvr/shared';
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { SttPipeline } from '../stt/pipeline.js';
import type { WorkerClient } from '../stt/worker.js';
import type { Timeline } from '../timeline.js';
import { safeJson } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
import type { GameAssets } from './assets.js';
import { LolAdapter } from './lol.js';
import type { AdapterHost, GameAdapter, MatchStart } from './types.js';
import { ValorantAdapter } from './valorant.js';
const log = logger('games');
/** 게임 어댑터들을 묶고, 경기 시작·종료를 녹음/STT/타임라인에 반영한다 */
export class GameManager implements AdapterHost {
adapters: GameAdapter[];
constructor(
readonly store: Store,
readonly assets: GameAssets,
readonly worker: WorkerClient,
private stt: SttPipeline,
private timeline: Timeline,
private bus: Bus,
private getSettings: () => Settings,
private ownerUserId: () => string | null,
) {
this.adapters = [new ValorantAdapter(this), new LolAdapter(this)];
}
settings(): Settings {
return this.getSettings();
}
start(): void {
void this.assets.refresh();
for (const a of this.adapters) a.start();
// 앱이 꺼졌다 켜졌을 때 'live' 로 남은 경기는 끝난 것으로 정리
for (const m of this.store.listMatches({ limit: 20 }))
if (m.status === 'live') this.store.upsertMatch({ id: m.id, game: m.game, started_at: m.started_at, status: 'complete', ended_at: m.ended_at ?? Date.now() });
}
stop(): void {
for (const a of this.adapters) a.stop();
}
status() {
const out: Record<string, { connected: boolean; inMatch: boolean; detail?: string }> = {};
for (const a of this.adapters) out[a.game] = a.status();
return out as { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
}
/** 지금 진행 중인 경기 (녹음 시 발화에 붙인다) */
liveMatchAt(ts: number): string | null {
const m = this.store.matchAt(ts);
return m && (m.status === 'live' || !m.ended_at || ts <= m.ended_at) ? m.id : null;
}
matchStarted(m: MatchStart): void {
this.store.upsertMatch({
id: m.id,
game: m.game,
started_at: m.startedAt,
map: m.map ?? null,
mode: m.mode ?? null,
queue: m.queue ?? null,
detail: m.detail ? JSON.stringify(m.detail) : null,
status: 'live',
});
this.timeline.invalidate(m.id);
void this.stt.onMatchStart();
this.emitMatch(m.id);
}
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void {
const cur = this.store.getMatch(id);
if (!cur) return;
this.store.upsertMatch({ ...patch, id, game: cur.game, started_at: patch.started_at ?? cur.started_at });
this.timeline.invalidate(id);
if (opts?.complete) {
const m = this.store.getMatch(id)!;
// 정확한 경기 시간으로 발화를 다시 붙인다
const n = this.store.assignMatch(id, m.started_at + m.clock_offset - 2000, (m.ended_at ?? Date.now()) + 1000);
log.info(`경기 ${id}: 발화 ${n}개 연결`);
this.bus.live({ type: 'users.updated', data: [] });
}
this.emitMatch(id);
}
matchEnded(id: string, endedAt: number): void {
const cur = this.store.getMatch(id);
if (!cur) return;
this.store.upsertMatch({ id, game: cur.game, started_at: cur.started_at, ended_at: endedAt, status: 'pending_detail' });
this.store.assignMatch(id, cur.started_at, endedAt);
this.timeline.invalidate(id);
void this.stt.onMatchEnd(cur.started_at, endedAt);
this.emitMatch(id);
}
event(e: EventRow): void {
if (this.store.insertEvent(e)) this.bus.live({ type: 'event.created', data: this.timeline.eventItem(e) });
}
replaceEvents(matchId: string, types: string[], events: EventRow[]): void {
this.store.replaceEvents(matchId, types, events);
this.timeline.invalidate(matchId);
}
selfAccount(puuid: string, riotId: string): void {
const owner = this.ownerUserId();
this.store.setMeta('riot_self_puuid', puuid);
if (!owner || !this.store.getUser(owner)) return;
const have = this.store.listAccounts().some((a) => a.user_id === owner && a.puuid === puuid);
if (have) return;
this.store.db.prepare('INSERT OR REPLACE INTO game_accounts(user_id,puuid,riot_id) VALUES(?,?,?)').run(owner, puuid, riotId);
this.store.db.prepare(`DELETE FROM game_accounts WHERE user_id=? AND puuid=''`).run(owner);
log.info(`주인 계정 자동 연결: ${riotId}`);
}
/** 설정에서 Riot ID 로만 연결해 둔 유저(puuid '' 자리표시)를 실제 puuid 로 바꾼다 */
resolvePlayers(players: { puuid: string; riotId: string }[]): void {
const pending = this.store.listAccounts().filter((a) => !a.puuid || a.puuid.startsWith('riotid:'));
for (const a of pending) {
const p = players.find((x) => x.riotId.toLowerCase() === a.riot_id.toLowerCase());
if (!p) continue;
this.store.db.prepare('UPDATE game_accounts SET puuid=? WHERE user_id=? AND puuid=?').run(p.puuid, a.user_id, a.puuid);
log.info(`Riot ID 연결: ${a.riot_id}`);
}
}
summary(m: MatchRow): MatchSummary {
const result = safeJson<{ win: boolean | null; score: { ally: number; enemy: number } | null }>(m.result, { win: null, score: null });
const map = m.game === 'valorant' ? this.assets.valMap(m.map) : null;
const participants = (
this.store.db.prepare('SELECT DISTINCT user_id FROM utterances WHERE match_id=?').all(m.id) as { user_id: string }[]
).map((r) => r.user_id);
return {
id: m.id,
game: m.game,
startedAt: m.started_at + m.clock_offset,
endedAt: m.ended_at,
map:
m.game === 'valorant'
? { id: m.map ?? '', name: map?.name ?? m.map ?? '?', image: map?.image ?? null }
: { id: m.map ?? 'Map11', name: '소환사의 협곡', image: this.assets.lolMapImage() },
mode: modeKo(m),
win: result.win,
score: result.score,
status: m.status as MatchSummary['status'],
participants,
};
}
emitMatch(id: string): void {
const m = this.store.getMatch(id);
if (m) this.bus.live({ type: 'match.updated', data: this.summary(m) });
}
}
function modeKo(m: MatchRow): string {
const q = (m.queue || m.mode || '').toLowerCase();
if (m.game === 'valorant') {
const map: Record<string, string> = {
competitive: '경쟁전',
unrated: '일반전',
swiftplay: '신속플레이',
spikerush: '스파이크 돌격',
deathmatch: '데스매치',
hurm: '팀 데스매치',
premier: '프리미어',
custom: '사용자 지정',
ggteam: '에스컬레이션',
};
return map[q] || m.mode || '발로란트';
}
const lq: Record<string, string> = { '420': '솔로 랭크', '440': '자유 랭크', '400': '일반', '430': '일반', '450': '칼바람 나락', '490': '빠른 대전', '1700': '아레나', classic: '소환사의 협곡', aram: '칼바람 나락' };
return lq[q] || m.mode || '리그 오브 레전드';
}

114
app/src/core/games/riot.ts Normal file
View File

@@ -0,0 +1,114 @@
import { execFile } from 'node:child_process';
import fs from 'node:fs';
import http from 'node:http';
import https from 'node:https';
import os from 'node:os';
import path from 'node:path';
/** Riot 로컬 API 는 자체 서명 인증서라 검증을 끈 에이전트로만 부른다 (127.0.0.1 전용) */
const localAgent = new https.Agent({ rejectUnauthorized: false, keepAlive: true });
export interface HttpResult<T = any> {
status: number;
data: T;
}
export function request<T = any>(
url: string,
opts: { method?: string; headers?: Record<string, string>; body?: unknown; timeoutMs?: number; local?: boolean } = {},
): Promise<HttpResult<T>> {
return new Promise((resolve, reject) => {
const u = new URL(url);
const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
const lib: any = u.protocol === 'http:' ? http : https;
const req = lib.request(
u,
{
method: opts.method || 'GET',
headers: { accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}), ...opts.headers },
agent: u.protocol === 'https:' && (opts.local ?? isLocal(u)) ? localAgent : undefined,
timeout: opts.timeoutMs ?? 5000,
},
(res: any) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => {
const txt = Buffer.concat(chunks).toString('utf8');
let data: any = txt;
try {
data = txt ? JSON.parse(txt) : null;
} catch {
/* 텍스트 그대로 */
}
resolve({ status: res.statusCode || 0, data });
});
},
);
req.on('timeout', () => req.destroy(new Error('timeout')));
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
function isLocal(u: URL): boolean {
return u.hostname === '127.0.0.1' || u.hostname === 'localhost';
}
export interface Lockfile {
name: string;
pid: number;
port: number;
password: string;
protocol: string;
}
export function parseLockfile(txt: string): Lockfile | null {
const p = txt.trim().split(':');
if (p.length < 5) return null;
return { name: p[0], pid: Number(p[1]), port: Number(p[2]), password: p[3], protocol: p[4] };
}
export function readLockfile(file: string): Lockfile | null {
try {
return parseLockfile(fs.readFileSync(file, 'utf8'));
} catch {
return null;
}
}
export function basicAuth(password: string): string {
return 'Basic ' + Buffer.from(`riot:${password}`).toString('base64');
}
/** Riot Client lockfile (발로란트 로컬 API) */
export function riotClientLockfilePath(): string {
if (process.env.GVR_RIOT_LOCKFILE) return process.env.GVR_RIOT_LOCKFILE;
const base = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
return path.join(base, 'Riot Games', 'Riot Client', 'Config', 'lockfile');
}
/** 롤 클라이언트(LCU) 접속 정보. lockfile 기본 위치 → 실행 중인 LeagueClientUx 명령줄 순서로 찾는다. */
export async function findLcu(): Promise<{ port: number; password: string; installDir: string | null } | null> {
if (process.env.GVR_LCU_LOCKFILE) {
const lf = readLockfile(process.env.GVR_LCU_LOCKFILE);
return lf ? { port: lf.port, password: lf.password, installDir: path.dirname(process.env.GVR_LCU_LOCKFILE) } : null;
}
if (process.platform !== 'win32') return null;
for (const dir of ['C:\\Riot Games\\League of Legends', 'D:\\Riot Games\\League of Legends']) {
const lf = readLockfile(path.join(dir, 'lockfile'));
if (lf) return { port: lf.port, password: lf.password, installDir: dir };
}
const cmd = await new Promise<string>((resolve) => {
execFile(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-Command', "(Get-CimInstance Win32_Process -Filter \"name='LeagueClientUx.exe'\").CommandLine"],
{ windowsHide: true, timeout: 8000 },
(err, stdout) => resolve(err ? '' : String(stdout)),
);
});
const port = /--app-port=(\d+)/.exec(cmd)?.[1];
const pw = /--remoting-auth-token=([\w-]+)/.exec(cmd)?.[1];
const dir = /--install-directory=([^"]+?)"?\s--/.exec(cmd)?.[1] ?? null;
return port && pw ? { port: Number(port), password: pw, installDir: dir } : null;
}

View File

@@ -0,0 +1,41 @@
import type { EventRow, MatchRow, Store } from '../db/db.js';
import type { Settings } from '../settings.js';
import type { WorkerClient } from '../stt/worker.js';
import type { GameAssets } from './assets.js';
export interface MatchStart {
id: string;
game: 'valorant' | 'lol';
startedAt: number;
map?: string | null;
mode?: string | null;
queue?: string | null;
detail?: unknown;
}
/** 게임 어댑터가 코어에 알리는 통로. 다른 게임도 같은 규격으로 붙인다 (F-15). */
export interface AdapterHost {
store: Store;
assets: GameAssets;
worker: WorkerClient;
settings(): Settings;
matchStarted(m: MatchStart): void;
/** 경기 정보 갱신 (상세가 채워졌을 때 등) */
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void;
matchEnded(id: string, endedAt: number): void;
/** 실시간 이벤트 1건 (중복 ID 는 무시) */
event(e: EventRow): void;
/** 경기 후 상세로 이벤트를 통째로 교체 */
replaceEvents(matchId: string, types: string[], events: EventRow[]): void;
/** 이 PC 의 Riot 계정 (주인 디스코드 유저와 자동 연결) */
selfAccount(puuid: string, riotId: string): void;
/** 경기 참가자 Riot ID 로 디스코드 유저 연결 갱신 */
resolvePlayers(players: { puuid: string; riotId: string }[]): void;
}
export interface GameAdapter {
readonly game: 'valorant' | 'lol';
start(): void;
stop(): void;
status(): { connected: boolean; inMatch: boolean; detail?: string };
}

View File

@@ -0,0 +1,553 @@
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound } from '@gvr/shared';
import type { EventRow, RoundRow } from '../db/db.js';
import { logger } from '../util/log.js';
import type { GameAssets } from './assets.js';
import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js';
import type { AdapterHost, GameAdapter } from './types.js';
const log = logger('valorant');
const CLIENT_PLATFORM = Buffer.from(
JSON.stringify({ platformType: 'PC', platformOS: 'Windows', platformOSVersion: '10.0.19042.1.256.64bit', platformChipset: 'Unknown' }),
).toString('base64');
/** 구매 단계 길이 (경쟁·일반 30초). 라운드 시작 = 전투 시작 - 구매 단계 */
const BUY_MS = 30000;
interface Presence {
state: 'MENUS' | 'PREGAME' | 'INGAME' | string;
map: string | null;
queue: string | null;
ally: number | null;
enemy: number | null;
provisioning: string | null;
}
export function decodePresence(b64: string): Presence | null {
try {
const p = JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));
const mp = p.matchPresenceData || {};
const pp = p.partyPresenceData || {};
return {
state: mp.sessionLoopState || p.sessionLoopState || 'MENUS',
map: mp.matchMap || p.matchMap || null,
queue: mp.queueId || p.queueId || null,
ally: num(pp.partyOwnerMatchScoreAllyTeam ?? p.partyOwnerMatchScoreAllyTeam),
enemy: num(pp.partyOwnerMatchScoreEnemyTeam ?? p.partyOwnerMatchScoreEnemyTeam),
provisioning: mp.provisioningFlow || p.provisioningFlow || null,
};
} catch {
return null;
}
}
const num = (v: any) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
interface Auth {
lock: Lockfile;
accessToken: string;
entitlement: string;
puuid: string;
region: string;
shard: string;
clientVersion: string | null;
}
/**
* 발로란트 어댑터: Riot 클라이언트 로컬 API (Q1 B).
* - 상태(presence)로 경기 시작·종료와 실시간 점수 감지
* - 경기 중 채팅(팀/전체/파티)은 로컬 채팅 API
* - 경기가 끝나면 경기 상세(킬·라운드·경제)를 받아 시간축에 맞춘다
* 읽기 전용, 게임 메모리 접근 없음.
*/
export class ValorantAdapter implements GameAdapter {
readonly game = 'valorant' as const;
private timer: NodeJS.Timeout | null = null;
private auth: Auth | null = null;
private authAt = 0;
private presence: Presence | null = null;
private match: { id: string; matchId: string; startedAt: number; ally: number; enemy: number } | null = null;
private seenChat = new Set<string>();
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
private polling = false;
private lastErr = '';
constructor(private host: AdapterHost) {}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => void this.tick(), Number(process.env.GVR_POLL_MS) || 3000);
void this.tick();
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
status() {
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
}
private async local<T = any>(path: string): Promise<T | null> {
const lock = this.auth?.lock ?? readLockfile(riotClientLockfilePath());
if (!lock) return null;
const r = await request<T>(`https://127.0.0.1:${lock.port}${path}`, { headers: { authorization: basicAuth(lock.password) }, local: true });
return r.status === 200 ? r.data : null;
}
private async ensureAuth(): Promise<Auth | null> {
const lock = readLockfile(riotClientLockfilePath());
if (!lock) {
this.auth = null;
return null;
}
if (this.auth && this.auth.lock.port === lock.port && Date.now() - this.authAt < 10 * 60000) return this.auth;
const base = `https://127.0.0.1:${lock.port}`;
const h = { authorization: basicAuth(lock.password) };
const ent = await request(`${base}/entitlements/v1/token`, { headers: h, local: true });
if (ent.status !== 200 || !ent.data?.accessToken) {
this.auth = null;
return null;
}
let region = process.env.GVR_VAL_REGION || 'kr';
let shard = process.env.GVR_VAL_SHARD || 'kr';
let clientVersion: string | null = null;
const sess = await request(`${base}/product-session/v1/external-sessions`, { headers: h, local: true }).catch(() => null);
for (const s of Object.values<any>(sess?.data || {})) {
if (s?.productId !== 'valorant') continue;
clientVersion = s.version || null;
for (const a of s.launchConfiguration?.arguments || []) {
const d = /^-ares-deployment=(\w+)/.exec(a);
if (d) region = d[1];
const c = /^-config-endpoint=https:\/\/shared\.(\w+)\.a\.pvp\.net/.exec(a);
if (c) shard = c[1];
}
}
this.auth = { lock, accessToken: ent.data.accessToken, entitlement: ent.data.token, puuid: ent.data.subject, region, shard, clientVersion };
this.authAt = Date.now();
log.info(`Riot 클라이언트 연결 (region=${region}, shard=${shard})`);
return this.auth;
}
private pvpHeaders(a: Auth): Record<string, string> {
return {
authorization: `Bearer ${a.accessToken}`,
'x-riot-entitlements-jwt': a.entitlement,
'x-riot-clientplatform': CLIENT_PLATFORM,
'x-riot-clientversion': a.clientVersion || this.host.assets.val?.clientVersion || '',
};
}
private glz(a: Auth): string {
return process.env.GVR_VAL_GLZ || `https://glz-${a.region}-1.${a.shard}.a.pvp.net`;
}
private pd(a: Auth): string {
return process.env.GVR_VAL_PD || `https://pd.${a.shard}.a.pvp.net`;
}
private async tick(): Promise<void> {
if (this.polling || !this.host.settings().games.valorant) return;
this.polling = true;
try {
const a = await this.ensureAuth();
if (a) {
await this.pollPresence(a);
if (this.match) await this.pollChat(a);
} else if (this.match) {
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
this.endMatch();
}
await this.pollDetails();
this.lastErr = '';
} catch (e: any) {
this.lastErr = e.message;
log.debug('발로란트 폴링 오류', e);
} finally {
this.polling = false;
}
}
private async pollPresence(a: Auth): Promise<void> {
const pres = await this.local<any>('/chat/v4/presences');
const mine = (pres?.presences || []).find((p: any) => p.puuid === a.puuid && p.product === 'valorant');
const p = mine?.private ? decodePresence(mine.private) : null;
const prev = this.presence;
this.presence = p;
if (!p) return;
if (p.state === 'INGAME' && !this.match) await this.beginMatch(a, p);
else if (p.state !== 'INGAME' && this.match && prev?.state === 'INGAME') this.endMatch();
else if (this.match && p.ally !== null && p.enemy !== null) {
const m = this.match;
const total = p.ally + p.enemy;
if (total > m.ally + m.enemy) {
// 실시간 라운드 결과 (경기 후 상세로 교체됨)
const win = p.ally > m.ally;
m.ally = p.ally;
m.enemy = p.enemy;
const data: RoundEndData = { round: total, win, result: win ? '승리' : '패배', score: { ally: p.ally, enemy: p.enemy } };
this.host.event({
id: `${m.id}:live-round:${total}`,
match_id: m.id,
game: 'valorant',
type: 'round_end',
ts: Date.now(),
game_time_ms: Date.now() - m.startedAt,
round: total,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(data),
});
this.host.matchUpdated(m.id, { result: JSON.stringify({ win: null, score: { ally: p.ally, enemy: p.enemy } }) });
}
}
}
private async beginMatch(a: Auth, p: Presence): Promise<void> {
let matchId: string | null = null;
let detail: any = null;
try {
const r = await request(`${this.glz(a)}/core-game/v1/players/${a.puuid}`, { headers: this.pvpHeaders(a), timeoutMs: 8000 });
matchId = r.data?.MatchID ?? null;
if (matchId) {
const m = await request(`${this.glz(a)}/core-game/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 8000 });
if (m.status === 200) detail = m.data;
}
} catch (e) {
log.warn('core-game 조회 실패', e);
}
const now = Date.now();
const id = `val-${matchId ?? now}`;
const mapUrl = detail?.MapID || p.map;
const players = (detail?.Players || []).map((pl: any) => ({
puuid: pl.Subject,
team: pl.TeamID,
character: this.host.assets.agent(pl.CharacterID),
}));
this.match = { id, matchId: matchId ?? '', startedAt: now, ally: p.ally ?? 0, enemy: p.enemy ?? 0 };
this.seenChat.clear();
this.host.matchStarted({
id,
game: 'valorant',
startedAt: now,
map: mapUrl,
mode: p.provisioning === 'CustomGame' ? 'custom' : p.queue,
queue: p.queue,
detail: { live: true, self: a.puuid, players },
});
log.info(`경기 시작 감지 ${id} (${this.host.assets.valMap(mapUrl)?.name ?? mapUrl})`);
}
private endMatch(): void {
const m = this.match;
if (!m) return;
this.match = null;
const now = Date.now();
this.host.matchEnded(m.id, now);
if (m.matchId) this.detailQueue.set(m.id, { tries: 0, endedAt: now, startedLocal: m.startedAt });
log.info(`경기 종료 감지 ${m.id}`);
}
private async pollChat(a: Auth): Promise<void> {
const m = this.match!;
const r = await this.local<any>('/chat/v6/messages');
for (const msg of r?.messages || []) {
const key = msg.mid || msg.id;
if (!key || this.seenChat.has(key)) continue;
const ts = Number(msg.time) || Date.now();
if (ts < m.startedAt - 120000) {
this.seenChat.add(key);
continue;
}
const cid: string = msg.cid || '';
const channel: ChatData['channel'] | null = cid.includes('-all@')
? 'all'
: cid.includes('ares-coregame') || cid.includes('ares-pregame')
? 'team'
: cid.includes('ares-parties')
? 'party'
: null;
this.seenChat.add(key);
if (!channel) continue;
const data: ChatData = {
sender: { puuid: msg.puuid, name: msg.game_name ? `${msg.game_name}` : msg.name || '?' },
channel,
text: String(msg.body ?? ''),
source: 'api',
};
this.host.event({
id: `${m.id}:chat:${key}`,
match_id: m.id,
game: 'valorant',
type: 'chat',
ts,
game_time_ms: ts - m.startedAt,
round: null,
actor_puuid: msg.puuid || null,
target_puuid: null,
data: JSON.stringify(data),
});
}
}
/** 경기 상세는 끝나고 수 분 안에 조회된다. 30초마다 최대 20번 시도 */
private async pollDetails(): Promise<void> {
if (!this.detailQueue.size) return;
const a = this.auth;
if (!a) return;
for (const [id, q] of this.detailQueue) {
if (Date.now() - q.endedAt < q.tries * (Number(process.env.GVR_DETAIL_RETRY_MS) || 30000)) continue;
q.tries++;
const matchId = id.replace(/^val-/, '');
try {
const r = await request(`${this.pd(a)}/match-details/v1/matches/${matchId}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
if (r.status === 200 && r.data?.matchInfo) {
this.detailQueue.delete(id);
this.applyDetails(id, r.data, a.puuid, q.startedLocal);
continue;
}
log.debug(`경기 상세 아직 없음 ${id} (${r.status})`);
} catch (e) {
log.debug('경기 상세 조회 실패', e);
}
if (q.tries >= 20) {
this.detailQueue.delete(id);
this.host.matchUpdated(id, { status: 'complete' }, { complete: true });
}
}
}
applyDetails(id: string, md: any, selfPuuid: string, startedLocal: number): void {
const res = processMatchDetails(md, selfPuuid, this.host.assets, id, startedLocal);
this.host.store.replaceRounds(id, res.rounds);
this.host.replaceEvents(id, ['kill', 'round_end', 'spike', 'multikill', 'ace'], res.events);
this.host.resolvePlayers(res.players.map((p) => ({ puuid: p.puuid, riotId: `${p.name}#${p.tag}` })));
const self = res.players.find((p) => p.puuid === selfPuuid);
if (self) this.host.selfAccount(self.puuid, `${self.name}#${self.tag}`);
this.host.matchUpdated(
id,
{
started_at: res.startedAt,
ended_at: res.endedAt + res.clockOffset,
clock_offset: res.clockOffset,
map: md.matchInfo.mapId,
mode: res.mode,
queue: md.matchInfo.queueID ?? null,
result: JSON.stringify(res.result),
detail: JSON.stringify({ self: selfPuuid, players: res.players, roundsDetail: res.roundsDetail }),
status: 'complete',
},
{ complete: true },
);
log.info(`경기 상세 적용 ${id}: 라운드 ${res.rounds.length}, 킬 ${res.events.filter((e) => e.type === 'kill').length}`);
}
}
/** match-details → 라운드·이벤트·선수. 순수 함수 (테스트 대상) */
export function processMatchDetails(md: any, selfPuuid: string, assets: GameAssets, id: string, startedLocal: number) {
const info = md.matchInfo;
const S: number = info.gameStartMillis;
const length: number = info.gameLengthMillis ?? 0;
// PC 시계와 서버 시계 차이: 10초 넘게 차이 나면 보정 (경기 로딩 시간 때문에 작은 차이는 무시)
const diff = startedLocal - S;
const clockOffset = Math.abs(diff) > 10000 && Math.abs(diff) < 6 * 3600000 ? diff - 5000 : 0;
const players: Record<string, any> = {};
for (const p of md.players || []) players[p.subject] = p;
const selfTeam = players[selfPuuid]?.teamId ?? 'Blue';
const ref = (puuid: string | null | undefined): PlayerRef | null => {
if (!puuid) return null;
const p = players[puuid];
if (!p) return { puuid, name: '?' };
return { puuid, name: p.gameName, team: p.teamId, character: assets.agent(p.characterId) };
};
const rr: any[] = md.roundResults || [];
const n = rr.length;
// 라운드 전투 시작 시각(게임 시간) = 킬 gameTime - roundTime
const combat: (number | null)[] = rr.map((r) => {
let best: number | null = null;
for (const ps of r.playerStats || [])
for (const k of ps.kills || []) {
const c = k.gameTime - k.roundTime;
if (best === null || c < best) best = c;
}
return best;
});
const avg = n ? length / n : 100000;
for (let i = 0; i < n; i++) {
if (combat[i] !== null) continue;
const prev = i > 0 ? combat[i - 1] : null;
let next: number | null = null;
for (let j = i + 1; j < n; j++) if (combat[j] !== null) {
next = combat[j]! - (j - i) * avg;
break;
}
combat[i] = prev !== null ? prev + avg : next !== null ? next : BUY_MS + i * avg;
}
const rounds: RoundRow[] = [];
const roundsDetail: MatchRound[] = [];
const events: EventRow[] = [];
let ally = 0;
let enemy = 0;
for (let i = 0; i < n; i++) {
const r = rr[i];
const num = (r.roundNum ?? i) + 1;
const c = combat[i]!;
const start = Math.max(0, c - BUY_MS);
const end = i + 1 < n ? Math.max(c, combat[i + 1]! - BUY_MS) : Math.max(c, length);
const win = r.winningTeam === selfTeam;
if (win) ally++;
else enemy++;
const economy: Record<string, { spent: number; remaining: number; weapon?: string }> = {};
for (const ps of r.playerStats || []) {
if (ps.economy)
economy[ps.subject] = {
spent: ps.economy.spent ?? 0,
remaining: ps.economy.remaining ?? 0,
weapon: ps.economy.weapon ? assets.damageItem(null, 'Weapon', ps.economy.weapon)?.name : undefined,
};
}
rounds.push({
match_id: id,
num,
started_at: S + start,
combat_at: S + c,
ended_at: S + end,
win: win ? 1 : 0,
result: r.roundResult ?? null,
ally_score: ally,
enemy_score: enemy,
economy: JSON.stringify(economy),
});
roundsDetail.push({ num, startedAt: S + start + clockOffset, endedAt: S + end + clockOffset, win, result: roundResultKo(r.roundResult), score: { ally, enemy }, economy });
// 킬
const killsBy: Record<string, number> = {};
const kills = (r.playerStats || []).flatMap((ps: any) => ps.kills || []).sort((x: any, y: any) => x.gameTime - y.gameTime);
for (const k of kills) {
const killer = ref(k.killer);
const victim = ref(k.victim)!;
killsBy[k.killer] = (killsBy[k.killer] || 0) + 1;
const fd = k.finishingDamage || {};
const data: KillData = {
killer,
victim,
assists: (k.assistants || []).map((x: string) => ref(x)!).filter(Boolean),
weapon: assets.damageItem(players[k.killer]?.characterId ?? null, fd.damageType, fd.damageItem),
location: k.victimLocation ? { x: k.victimLocation.x, y: k.victimLocation.y } : null,
ally: players[k.killer]?.teamId === selfTeam,
};
events.push({
id: `${id}:kill:${num}:${k.gameTime}:${k.victim}`,
match_id: id,
game: 'valorant',
type: 'kill',
ts: S + k.gameTime + clockOffset,
game_time_ms: k.gameTime,
round: num,
actor_puuid: k.killer ?? null,
target_puuid: k.victim ?? null,
data: JSON.stringify(data),
});
}
for (const [puuid, cnt] of Object.entries(killsBy)) {
if (cnt >= 4) {
const last = kills.filter((k: any) => k.killer === puuid).pop();
events.push({
id: `${id}:${cnt >= 5 ? 'ace' : 'multikill'}:${num}:${puuid}`,
match_id: id,
game: 'valorant',
type: cnt >= 5 ? 'ace' : 'multikill',
ts: S + last.gameTime + clockOffset + 1,
game_time_ms: last.gameTime,
round: num,
actor_puuid: puuid,
target_puuid: null,
data: JSON.stringify({ player: ref(puuid), count: cnt, ally: players[puuid]?.teamId === selfTeam }),
});
}
}
if (r.plantRoundTime) {
events.push({
id: `${id}:spike:plant:${num}`,
match_id: id,
game: 'valorant',
type: 'spike',
ts: S + c + r.plantRoundTime + clockOffset,
game_time_ms: c + r.plantRoundTime,
round: num,
actor_puuid: r.bombPlanter ?? null,
target_puuid: null,
data: JSON.stringify({ action: 'plant', site: r.plantSite ?? null, player: ref(r.bombPlanter), location: r.plantLocation ?? null }),
});
}
if (r.defuseRoundTime) {
events.push({
id: `${id}:spike:defuse:${num}`,
match_id: id,
game: 'valorant',
type: 'spike',
ts: S + c + r.defuseRoundTime + clockOffset,
game_time_ms: c + r.defuseRoundTime,
round: num,
actor_puuid: r.bombDefuser ?? null,
target_puuid: null,
data: JSON.stringify({ action: 'defuse', player: ref(r.bombDefuser), location: r.defuseLocation ?? null }),
});
}
const rd: RoundEndData = { round: num, win, result: roundResultKo(r.roundResult), score: { ally, enemy } };
events.push({
id: `${id}:round_end:${num}`,
match_id: id,
game: 'valorant',
type: 'round_end',
ts: S + end + clockOffset - 1,
game_time_ms: end,
round: num,
actor_puuid: null,
target_puuid: null,
data: JSON.stringify(rd),
});
}
const mp: MatchPlayer[] = (md.players || []).map((p: any) => ({
puuid: p.subject,
name: p.gameName,
tag: p.tagLine,
team: p.teamId,
ally: p.teamId === selfTeam,
character: assets.agent(p.characterId),
kills: p.stats?.kills ?? 0,
deaths: p.stats?.deaths ?? 0,
assists: p.stats?.assists ?? 0,
score: p.stats?.roundsPlayed ? Math.round((p.stats.score ?? 0) / p.stats.roundsPlayed) : (p.stats?.score ?? 0),
rank: assets.val?.tiers[p.competitiveTier] ?? null,
}));
const selfTeamInfo = (md.teams || []).find((t: any) => t.teamId === selfTeam);
const enemyTeamInfo = (md.teams || []).find((t: any) => t.teamId !== selfTeam);
return {
startedAt: S,
endedAt: S + length,
clockOffset,
rounds,
roundsDetail,
events,
players: mp,
mode: assets.val?.modes[info.gameMode] ?? info.queueID ?? null,
result: {
win: selfTeamInfo ? !!selfTeamInfo.won : null,
score: { ally: selfTeamInfo?.roundsWon ?? ally, enemy: enemyTeamInfo?.roundsWon ?? enemy },
},
};
}
export function roundResultKo(r: string | undefined): string {
switch (r) {
case 'Eliminated':
return '전멸';
case 'Bomb detonated':
return '스파이크 폭발';
case 'Bomb defused':
return '스파이크 해체';
case 'Round timer expired':
return '시간 초과';
case 'Surrendered':
return '항복';
default:
return r || '';
}
}

136
app/src/core/index.ts Normal file
View File

@@ -0,0 +1,136 @@
import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance } from 'fastify';
import { buildApi } from './api/server.js';
import { Store } from './db/db.js';
import { Dictionary } from './dict/dictionary.js';
import { Bot } from './discord/bot.js';
import { Recorder } from './discord/recorder.js';
import { Announcer } from './discord/tts.js';
import { GameAssets } from './games/assets.js';
import { GameManager } from './games/manager.js';
import { RelayClient } from './relay/client.js';
import { Retention } from './retention.js';
import { SettingsStore, resolvePaths, type SecretCodec } from './settings.js';
import { SttPipeline } from './stt/pipeline.js';
import { WorkerClient, type WorkerCommand } from './stt/worker.js';
import { Timeline } from './timeline.js';
import { Bus } from './util/events.js';
import { initLogFile, logger } from './util/log.js';
const log = logger('core');
export interface CoreOptions {
dataDir: string;
resourcesDir: string;
worker: WorkerCommand;
version: string;
codec?: SecretCodec;
/** 로컬 API 를 127.0.0.1 포트로도 연다 (설정 창·디버그용). 0 이면 열지 않음 */
apiPort?: number;
}
export type Core = Awaited<ReturnType<typeof startCore>>;
/** 코어 조립 (Electron 메인 프로세스와 헤드리스 CLI 가 같이 쓴다) */
export async function startCore(opts: CoreOptions) {
fs.mkdirSync(opts.dataDir, { recursive: true });
const settings = new SettingsStore(opts.dataDir, opts.codec);
const S = () => settings.get();
const paths = () => resolvePaths(opts.dataDir, S());
initLogFile(paths().logs);
log.info(`겜녹이 ${opts.version} 시작, 데이터 폴더 ${opts.dataDir}`);
const store = new Store(paths().db);
const bus = new Bus();
bus.setMaxListeners(50);
const timeline = new Timeline(store);
const dict = new Dictionary(store, opts.resourcesDir, () => S().dictionary.packs);
dict.seed();
const worker = new WorkerClient({
...opts.worker,
env: { ...(opts.worker.env || {}), GVR_DATA_DIR: opts.dataDir, GVR_MODELS_DIR: paths().models },
});
const stt = new SttPipeline(worker, store, dict, timeline, bus, S);
const assets = new GameAssets(path.join(opts.dataDir, 'cache'));
const games = new GameManager(store, assets, worker, stt, timeline, bus, S, () => S().discord.followUserId);
const recorder: Recorder = new Recorder(store, stt, timeline, bus, {
audioDir: () => paths().audio,
silenceMs: () => S().audio.silenceMs,
maxUtteranceSec: () => S().audio.maxUtteranceSec,
skip: (uid): boolean => {
const u = store.getUser(uid);
if (u?.excluded) return true;
return !!bot.client?.users.cache.get(uid)?.bot;
},
matchAt: (ts) => games.liveMatchAt(ts),
});
const announcer = new Announcer(paths().tts, opts.resourcesDir);
const bot: Bot = new Bot(store, recorder, announcer, bus, S, (gid) => {
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
});
const api: FastifyInstance = await buildApi({
store,
timeline,
games,
dict,
bus,
settings: S,
trainingDir: () => paths().training,
version: opts.version,
overviewExtra: () => ({
guild: bot.state.guild,
recording: {
active: bot.state.recording.active,
channel: bot.state.recording.channel,
since: bot.state.recording.since,
participants: bot.state.recording.participants,
},
}),
});
const relay = new RelayClient(api, bus, () => ({
serverUrl: S().site.serverUrl,
deviceId: S().site.deviceId,
deviceKey: settings.getSecret('deviceKey') ?? null,
name: S().site.deviceName,
version: opts.version,
}));
const retention = new Retention(store, () => S().storage.retentionDays, () => paths().audio);
worker.start();
stt.resumePending();
games.start();
retention.start();
relay.start();
if (opts.apiPort) await api.listen({ host: '127.0.0.1', port: opts.apiPort });
const startBot = async () => {
const token = settings.getSecret('botToken');
if (!token) {
log.warn('봇 토큰이 없습니다. 설정에서 입력해 주세요.');
return;
}
try {
await bot.start(token);
} catch (e: any) {
log.error(`봇 로그인 실패: ${e.message}`);
}
};
await startBot();
const stop = async () => {
log.info('종료 중');
relay.stop();
retention.stop();
games.stop();
await bot.stop();
await worker.stop();
await api.close();
store.close();
};
return { settings, store, bus, timeline, dict, worker, stt, assets, games, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version };
}

View File

@@ -0,0 +1,160 @@
import type { FastifyInstance } from 'fastify';
import WebSocket from 'ws';
import type { LiveEvent, RelayFromDevice, RelayToDevice } from '@gvr/shared';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
const log = logger('relay');
export interface RelayStatus {
state: 'off' | 'connecting' | 'online' | 'error';
error: string | null;
since: number | null;
serverUrl: string | null;
}
/**
* 사이트 서버로 나가는 WebSocket 하나를 유지한다 (포트 개방 불필요, 보고서 3장).
* 서버가 넘겨 준 /api 요청을 로컬 API(Fastify inject)로 처리해 돌려주고, 실시간 이벤트를 올린다.
*/
export class RelayClient {
private ws: WebSocket | null = null;
private pingTimer: NodeJS.Timeout | null = null;
private retryTimer: NodeJS.Timeout | null = null;
private retries = 0;
private stopped = true;
private lastPong = 0;
status: RelayStatus = { state: 'off', error: null, since: null, serverUrl: null };
constructor(
private api: FastifyInstance,
private bus: Bus,
private cfg: () => { serverUrl: string; deviceId: string | null; deviceKey: string | null; name: string; version: string },
) {
bus.on('live', (ev: LiveEvent) => this.send({ t: 'event', event: ev }));
}
start(): void {
this.stopped = false;
this.connect();
}
stop(): void {
this.stopped = true;
if (this.retryTimer) clearTimeout(this.retryTimer);
this.retryTimer = null;
this.cleanup();
this.ws?.close();
this.ws = null;
this.status = { state: 'off', error: null, since: null, serverUrl: null };
}
restart(): void {
this.stop();
this.start();
}
private connect(): void {
const c = this.cfg();
if (!c.deviceId || !c.deviceKey) {
this.status = { state: 'off', error: '사이트 서버에 등록되지 않았습니다', since: null, serverUrl: c.serverUrl };
return;
}
const url = c.serverUrl.replace(/^http/, 'ws').replace(/\/$/, '') + '/device/ws';
this.status = { ...this.status, state: 'connecting', serverUrl: c.serverUrl };
const ws = new WebSocket(url, { headers: { authorization: `Device ${c.deviceId}.${c.deviceKey}` }, handshakeTimeout: 10000, maxPayload: 8 * 1024 * 1024 });
this.ws = ws;
ws.on('open', () => {
this.retries = 0;
this.lastPong = Date.now();
this.status = { state: 'online', error: null, since: Date.now(), serverUrl: c.serverUrl };
log.info(`사이트 서버 연결됨: ${c.serverUrl}`);
this.send({ t: 'hello', name: c.name, version: c.version });
this.pingTimer = setInterval(() => {
if (Date.now() - this.lastPong > 20000) {
log.warn('사이트 서버 응답 없음, 다시 연결');
ws.terminate();
return;
}
this.send({ t: 'ping', ts: Date.now() });
}, 5000);
});
ws.on('message', (data, isBinary) => {
if (isBinary) return;
let msg: RelayToDevice;
try {
msg = JSON.parse(String(data));
} catch {
return;
}
if (msg.t === 'pong') this.lastPong = Date.now();
else if (msg.t === 'req') void this.handle(msg);
});
ws.on('unexpected-response', (_req, res) => {
this.status.error = res.statusCode === 401 ? '기기 인증 실패 (다시 등록해 주세요)' : `서버 응답 ${res.statusCode}`;
});
ws.on('error', (e) => {
this.status.error = this.status.error || e.message;
});
ws.on('close', () => {
this.cleanup();
if (this.ws === ws) this.ws = null;
if (this.stopped) return;
this.status = { ...this.status, state: 'error', since: null };
const delay = Math.min(30000, 1000 * 2 ** Math.min(this.retries++, 5));
this.retryTimer = setTimeout(() => this.connect(), delay);
});
}
private cleanup(): void {
if (this.pingTimer) clearInterval(this.pingTimer);
this.pingTimer = null;
}
private send(m: RelayFromDevice): void {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(m));
}
private async handle(req: Extract<RelayToDevice, { t: 'req' }>): Promise<void> {
if (!req.path.startsWith('/api/')) {
this.send({ t: 'res', id: req.id, status: 403, headers: { 'content-type': 'application/json' }, body: '{"error":"forbidden"}' });
return;
}
try {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = req.headers[k];
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: req.body ?? undefined });
const outHeaders: Record<string, string> = {};
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length']) {
const v = res.headers[k];
if (v !== undefined) outHeaders[k] = String(v);
}
const ct = outHeaders['content-type'] || '';
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream')) {
this.send({ t: 'res_head', id: req.id, status: res.statusCode, headers: outHeaders });
const idBuf = Buffer.from(req.id, 'utf8');
const head = Buffer.alloc(4);
head.writeUInt32BE(idBuf.length, 0);
this.ws?.send(Buffer.concat([head, idBuf, res.rawPayload]), { binary: true });
this.send({ t: 'res_end', id: req.id });
} else {
this.send({ t: 'res', id: req.id, status: res.statusCode, headers: outHeaders, body: res.payload });
}
} catch (e: any) {
this.send({ t: 'res', id: req.id, status: 500, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error: 'internal', message: e.message }) });
}
}
}
/** 1회용 등록 코드로 이 PC 를 사이트 서버에 등록한다 */
export async function registerDevice(serverUrl: string, code: string, name: string): Promise<{ deviceId: string; deviceKey: string }> {
const r = await fetch(serverUrl.replace(/\/$/, '') + '/device/register', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ code: code.trim(), name }),
});
const data: any = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(data.message || (r.status === 400 || r.status === 404 ? '등록 코드가 올바르지 않거나 만료되었습니다' : `서버 오류 ${r.status}`));
return { deviceId: data.deviceId, deviceKey: data.deviceKey };
}

89
app/src/core/retention.ts Normal file
View File

@@ -0,0 +1,89 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Store } from './db/db.js';
import { logger } from './util/log.js';
const log = logger('retention');
/**
* 음성 7일 자동 삭제 (Q9, A2): 음성 파일만 지우고 텍스트·경기 기록은 남긴다.
* 학습 데이터(training/)는 대상이 아니다 (A3). 시작할 때와 매일 새벽 4시에 돈다.
*/
export class Retention {
private timer: NodeJS.Timeout | null = null;
constructor(
private store: Store,
private days: () => number,
private audioDir: () => string,
) {}
start(): void {
this.run();
this.schedule();
}
stop(): void {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
}
private schedule(): void {
const now = new Date();
const next = new Date(now);
next.setHours(4, 0, 0, 0);
if (next <= now) next.setDate(next.getDate() + 1);
this.timer = setTimeout(() => {
this.run();
this.schedule();
}, next.getTime() - now.getTime());
}
run(now = Date.now()): { deleted: number; freedBytes: number } {
const before = now - this.days() * 24 * 3600 * 1000;
let deleted = 0;
let freed = 0;
for (const r of this.store.expiredAudio(before)) {
try {
freed += fs.statSync(r.audio_path).size;
fs.rmSync(r.audio_path, { force: true });
} catch {
/* 이미 없음 */
}
this.store.markAudioDeleted(r.id);
deleted++;
}
// 빈 날짜 폴더 정리
try {
for (const d of fs.readdirSync(this.audioDir())) {
const p = path.join(this.audioDir(), d);
if (fs.statSync(p).isDirectory() && fs.readdirSync(p).length === 0) fs.rmdirSync(p);
}
} catch {
/* 폴더 없음 */
}
if (deleted) log.info(`보관 기간 지난 음성 ${deleted}개 삭제 (${(freed / 1048576).toFixed(1)}MB)`);
return { deleted, freedBytes: freed };
}
}
export function dirSize(dir: string): number {
let total = 0;
const walk = (d: string) => {
let ents: fs.Dirent[] = [];
try {
ents = fs.readdirSync(d, { withFileTypes: true });
} catch {
return;
}
for (const e of ents) {
const p = path.join(d, e.name);
if (e.isDirectory()) walk(p);
else
try {
total += fs.statSync(p).size;
} catch {
/* 무시 */
}
}
};
walk(dir);
return total;
}

217
app/src/core/settings.ts Normal file
View File

@@ -0,0 +1,217 @@
import fs from 'node:fs';
import path from 'node:path';
export interface Settings {
version: 1;
firstRunDone: boolean;
discord: {
guildId: string | null;
/** 따라갈 유저 (보통 게임 PC 주인) */
followUserId: string | null;
followEnabled: boolean;
commandsEnabled: boolean;
ttsEnabled: boolean;
ttsText: string;
ttsOnNewMember: boolean;
ttsVoice: string;
};
games: {
valorant: boolean;
lol: boolean;
lolChatOcr: boolean;
lolOcrRegion: { x: number; y: number; w: number; h: number };
lolLogsDir: string | null;
};
stt: {
realtimeModel: string;
preciseModel: string;
device: 'cuda' | 'cpu';
computeType: string;
modelsDir: string | null;
reprocessAfterMatch: boolean;
gameVramReserveMb: number;
};
audio: {
targetLufs: number;
denoise: boolean;
noiseSensitivity: number;
silenceMs: number;
maxUtteranceSec: number;
};
dictionary: {
packs: Record<string, boolean>;
applySiteCorrections: boolean;
};
storage: {
audioDir: string | null;
retentionDays: number;
};
site: {
serverUrl: string;
deviceId: string | null;
deviceName: string;
};
general: {
autoStart: boolean;
sfx: boolean;
};
finetune: {
schedule: 'off' | 'nightly';
activeModel: string | null;
previousModel: string | null;
};
}
export interface Secrets {
botToken?: string;
deviceKey?: string;
riotApiKey?: string;
}
export const DEFAULT_TTS_TEXT =
'겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
export function defaultSettings(): Settings {
return {
version: 1,
firstRunDone: false,
discord: {
guildId: null,
followUserId: null,
followEnabled: true,
commandsEnabled: true,
ttsEnabled: true,
ttsText: DEFAULT_TTS_TEXT,
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
},
games: {
valorant: true,
lol: true,
lolChatOcr: true,
lolOcrRegion: { x: 0.0, y: 0.6, w: 0.3, h: 0.27 },
lolLogsDir: null,
},
stt: {
realtimeModel: 'large-v3-turbo',
preciseModel: 'large-v3',
device: 'cuda',
computeType: 'float16',
modelsDir: null,
reprocessAfterMatch: true,
gameVramReserveMb: 3072,
},
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
dictionary: {
packs: { valorant: true, valorant_callouts: true, lol: true, lol_skills: true, game: true, daily: true, university: true, slang20s: true },
applySiteCorrections: true,
},
storage: { audioDir: null, retentionDays: 7 },
site: { serverUrl: 'https://gvr.tkrmagid.kr', deviceId: null, deviceName: 'GAME-PC' },
general: { autoStart: false, sfx: true },
finetune: { schedule: 'off', activeModel: null, previousModel: null },
};
}
function deepMerge<T>(base: T, over: any): T {
if (over === undefined || over === null || typeof base !== 'object' || base === null || Array.isArray(base)) {
return (over ?? base) as T;
}
const out: any = { ...base };
for (const k of Object.keys(over)) {
const b = (base as any)[k];
out[k] = b && typeof b === 'object' && !Array.isArray(b) ? deepMerge(b, over[k]) : over[k];
}
return out;
}
/** 비밀값 암호화 방식. Electron 에서는 safeStorage(DPAPI), 헤드리스는 평문(0600). */
export interface SecretCodec {
name: string;
encrypt(plain: string): Buffer;
decrypt(data: Buffer): string;
}
export const plainCodec: SecretCodec = {
name: 'plain',
encrypt: (s) => Buffer.from(s, 'utf8'),
decrypt: (b) => b.toString('utf8'),
};
export class SettingsStore {
private file: string;
private secretFile: string;
private cur: Settings;
private secrets: Secrets;
private listeners = new Set<(s: Settings) => void>();
constructor(
private dataDir: string,
private codec: SecretCodec = plainCodec,
) {
this.file = path.join(dataDir, 'settings.json');
this.secretFile = path.join(dataDir, 'secrets.bin');
this.cur = defaultSettings();
try {
this.cur = deepMerge(defaultSettings(), JSON.parse(fs.readFileSync(this.file, 'utf8')));
} catch {
/* 첫 실행 */
}
this.secrets = {};
try {
this.secrets = JSON.parse(this.codec.decrypt(fs.readFileSync(this.secretFile)));
} catch {
/* 없음 */
}
// 개발/헤드리스: 환경변수로 비밀값 주입
if (process.env.GVR_BOT_TOKEN) this.secrets.botToken = process.env.GVR_BOT_TOKEN;
}
get(): Settings {
return this.cur;
}
update(patch: any): Settings {
this.cur = deepMerge(this.cur, patch);
this.save();
for (const l of this.listeners) l(this.cur);
return this.cur;
}
onChange(fn: (s: Settings) => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
save(): void {
fs.mkdirSync(this.dataDir, { recursive: true });
const tmp = this.file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(this.cur, null, 2));
fs.renameSync(tmp, this.file);
}
getSecret<K extends keyof Secrets>(k: K): Secrets[K] {
return this.secrets[k];
}
hasSecret(k: keyof Secrets): boolean {
return !!this.secrets[k];
}
setSecret<K extends keyof Secrets>(k: K, v: Secrets[K] | null): void {
if (v === null || v === undefined || v === '') delete this.secrets[k];
else this.secrets[k] = v;
fs.mkdirSync(this.dataDir, { recursive: true });
fs.writeFileSync(this.secretFile, this.codec.encrypt(JSON.stringify(this.secrets)), { mode: 0o600 });
for (const l of this.listeners) l(this.cur);
}
get codecName(): string {
return this.codec.name;
}
}
export function resolvePaths(dataDir: string, s: Settings) {
return {
dataDir,
db: path.join(dataDir, 'gvr.sqlite'),
audio: s.storage.audioDir || path.join(dataDir, 'audio'),
training: path.join(dataDir, 'training'),
models: s.stt.modelsDir || path.join(dataDir, 'models'),
tts: path.join(dataDir, 'tts'),
logs: path.join(dataDir, 'logs'),
};
}
export type Paths = ReturnType<typeof resolvePaths>;

View File

@@ -0,0 +1,282 @@
import fs from 'node:fs';
import type { Store, UtteranceRow } from '../db/db.js';
import type { Dictionary, DictContext } from '../dict/dictionary.js';
import type { Settings } from '../settings.js';
import type { Timeline } from '../timeline.js';
import type { Bus } from '../util/events.js';
import { logger } from '../util/log.js';
import { WorkerClient, WorkerError, type TranscribeResult } from './worker.js';
const log = logger('stt');
type Slot = 'realtime' | 'precise';
interface Job {
id: string;
slot: Slot;
/** 낮을수록 먼저 */
prio: number;
}
export interface SttStatus {
worker: 'starting' | 'ready' | 'down';
slots: Record<Slot, { model: string | null; state: 'empty' | 'loading' | 'loaded' | 'missing' | 'error'; error?: string }>;
queue: number;
processing: string | null;
device: string | null;
lastError: string | null;
}
/**
* 녹음과 STT 를 분리하는 대기열 (N-05). 발화는 DB 에 'pending' 으로 먼저 저장되고, 여기서 하나씩 변환한다.
* 프로그램을 다시 켜면 pending 을 다시 넣는다.
* 경기 중에는 실시간 모델, 경기가 끝나면 같은 구간을 정밀 모델로 다시 변환한다 (Q4).
*/
export class SttPipeline {
private queue: Job[] = [];
private queued = new Set<string>();
private busy = false;
private processing: string | null = null;
private inMatch = false;
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
private bothFit = true;
status: SttStatus = {
worker: 'starting',
slots: { realtime: { model: null, state: 'empty' }, precise: { model: null, state: 'empty' } },
queue: 0,
processing: null,
device: null,
lastError: null,
};
constructor(
private worker: WorkerClient,
private store: Store,
private dict: Dictionary,
private timeline: Timeline,
private bus: Bus,
private settings: () => Settings,
) {
worker.on('ready', (r) => {
this.status.worker = 'ready';
this.status.device = r?.device ?? null;
void this.prepareModels();
});
worker.on('exit', () => {
this.status.worker = 'down';
this.status.slots.realtime.state = 'empty';
this.status.slots.precise.state = 'empty';
});
}
/** 설치된 모델을 슬롯에 올린다. 없으면 'missing' 으로 두고 발화는 pending 으로 쌓인다. */
async prepareModels(): Promise<void> {
const s = this.settings().stt;
try {
const gi = await this.worker.request('gpu_info', {}, 30000);
const g = gi?.gpus?.[0];
if (g) this.bothFit = g.vram_total_mb - s.gameVramReserveMb >= 9000;
else this.bothFit = false;
} catch {
this.bothFit = false;
}
await this.load('realtime', s.realtimeModel);
if (this.bothFit && !this.inMatch) await this.load('precise', s.preciseModel);
this.pump();
}
private async installed(): Promise<Set<string>> {
try {
const r = await this.worker.request('models', {}, 30000);
return new Set((r.models || []).filter((m: any) => m.installed).map((m: any) => m.name));
} catch {
return new Set();
}
}
async load(slot: Slot, model: string): Promise<boolean> {
const s = this.settings().stt;
const st = this.status.slots[slot];
if (st.model === model && st.state === 'loaded') return true;
const inst = await this.installed();
// 파인튜닝한 모델 이름이나 경로도 그대로 넘긴다 (워커가 해석)
if (!inst.has(model) && !model.includes('/') && !model.includes('\\') && !model.includes('-ft-')) {
st.model = model;
st.state = 'missing';
return false;
}
st.model = model;
st.state = 'loading';
try {
await this.worker.request('load', { slot, model, device: s.device, compute_type: s.computeType }, 15 * 60000);
st.state = 'loaded';
st.error = undefined;
log.info(`${slot} 모델 적재: ${model}`);
return true;
} catch (e: any) {
st.state = 'error';
st.error = e.message;
this.status.lastError = e.message;
log.error(`${slot} 모델 적재 실패: ${model}`, e);
return false;
}
}
async unload(slot: Slot): Promise<void> {
try {
await this.worker.request('unload', { slot }, 60000);
} catch {
/* 무시 */
}
this.status.slots[slot].state = 'empty';
}
/** 시작 시 미처리분 복구 */
resumePending(): void {
const rows = this.store.pendingUtterances();
if (rows.length) log.info(`미처리 발화 ${rows.length}개 다시 대기열에 넣음`);
for (const r of rows) this.enqueue(r.id, 'realtime', 5);
}
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10): void {
const key = `${slot}:${id}`;
if (this.queued.has(key)) return;
this.queued.add(key);
this.queue.push({ id, slot, prio });
this.queue.sort((a, b) => a.prio - b.prio);
this.status.queue = this.queue.length;
this.pump();
}
async onMatchStart(): Promise<void> {
this.inMatch = true;
// VRAM 이 빠듯하면 경기 중에는 정밀 모델을 내린다 (게임 프레임 보호)
if (!this.bothFit && this.status.slots.precise.state === 'loaded') await this.unload('precise');
}
async onMatchEnd(from: number, to: number): Promise<void> {
this.inMatch = false;
const s = this.settings().stt;
if (!s.reprocessAfterMatch || s.preciseModel === s.realtimeModel) return;
if (this.status.slots.precise.state !== 'loaded') await this.load('precise', s.preciseModel);
if (this.status.slots.precise.state !== 'loaded') return;
const rows = this.store.realtimeUtterancesInRange(from, to);
log.info(`경기 종료: ${rows.length}개 발화를 정밀 모델로 다시 변환`);
for (const r of rows) this.enqueue(r.id, 'precise', 10);
}
private pickSlot(job: Job): Slot | null {
const { realtime, precise } = this.status.slots;
if (job.slot === 'precise') return precise.state === 'loaded' ? 'precise' : null;
// 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로
if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise';
if (realtime.state === 'loaded') return 'realtime';
if (precise.state === 'loaded') return 'precise';
return null;
}
private pump(): void {
if (this.busy || !this.worker.ready) return;
const idx = this.queue.findIndex((j) => this.pickSlot(j) !== null);
if (idx < 0) return;
const job = this.queue.splice(idx, 1)[0];
this.queued.delete(`${job.slot}:${job.id}`);
this.status.queue = this.queue.length;
this.busy = true;
this.processing = job.id;
this.status.processing = job.id;
this.run(job, this.pickSlot(job)!)
.catch((e) => log.error('STT 작업 오류', e))
.finally(() => {
this.busy = false;
this.processing = null;
this.status.processing = null;
setImmediate(() => this.pump());
});
}
/** 이 경기에 나온 요원·챔피언·선수 이름 → 핫워드 맨 앞 */
private matchWords(u: UtteranceRow): string[] {
if (!u.match_id) return [];
const m = this.store.getMatch(u.match_id);
if (!m?.detail) return [];
try {
const det = JSON.parse(m.detail);
const out: string[] = [];
for (const p of det.players || []) {
if (p.character?.name && p.character.name !== '?') out.push(p.character.name);
}
for (const p of det.players || []) if (p.name && p.name !== '?') out.push(p.name);
return out;
} catch {
return [];
}
}
private dictContext(u: UtteranceRow): DictContext {
if (!u.match_id) return 'none';
return (this.store.getMatch(u.match_id)?.game as DictContext) || 'none';
}
private async run(job: Job, slot: Slot): Promise<void> {
const u = this.store.getUtterance(job.id);
if (!u || !u.audio_path || u.audio_deleted) return;
if (!fs.existsSync(u.audio_path)) {
this.store.markUtteranceFailed(u.id);
return;
}
if (job.slot === 'precise' && (u.corrected || u.status === 'precise')) return;
const s = this.settings();
const ctx = this.dictContext(u);
const user = this.store.getUser(u.user_id);
let r: TranscribeResult;
try {
r = await this.worker.request<TranscribeResult>(
'transcribe',
{
slot,
path: u.audio_path,
hotwords: this.dict.hotwords(ctx, this.matchWords(u)),
initial_prompt: null,
corrections: this.dict.corrections(),
dictionary: this.dict.candidates(ctx),
profile_lufs: user?.gain_lufs ?? null,
target_lufs: s.audio.targetLufs,
noise_sensitivity: s.audio.noiseSensitivity,
denoise: s.audio.denoise,
},
5 * 60000,
);
} catch (e: any) {
const attempts = this.store.bumpAttempt(u.id);
this.status.lastError = e.message;
log.warn(`STT 실패 (${u.id}, ${attempts}회): ${e.message}`);
if (e instanceof WorkerError && (e.code === 'worker_exit' || e.code === 'worker_down') && attempts < 3) {
this.enqueue(u.id, job.slot, job.prio + 1);
} else if (attempts >= 3) {
this.store.markUtteranceFailed(u.id);
this.emit(u.id);
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
this.store.updateUtteranceResult(u.id, {
text: r.text,
raw_text: r.raw_text,
words: r.words,
noise: r.noise,
noise_reason: r.noise_reason,
confidence: r.confidence,
lufs: r.lufs,
gain_db: r.gain_db,
model: r.model,
status: slot,
});
if (!r.noise && r.lufs !== null && r.duration_s >= 1) this.store.updateGainProfile(u.user_id, r.lufs);
if (r.text) this.store.hitDict(r.words.map((w) => w.w));
this.emit(u.id);
}
private emit(id: string): void {
const row = this.store.getUtterance(id);
if (row) this.bus.live({ type: 'utterance.updated', data: this.timeline.utteranceItem(row) });
}
}

169
app/src/core/stt/worker.ts Normal file
View File

@@ -0,0 +1,169 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { EventEmitter } from 'node:events';
import readline from 'node:readline';
import os from 'node:os';
import { logger } from '../util/log.js';
const log = logger('worker');
export interface WorkerCommand {
/** 실행 파일 (gvr-worker.exe 또는 python) */
cmd: string;
args: string[];
cwd?: string;
env?: Record<string, string>;
}
export interface TranscribeResult {
text: string | null;
raw_text: string | null;
words: { w: string; s: number; e: number; p?: number }[];
noise: boolean;
noise_reason: string | null;
confidence: number | null;
lufs: number | null;
gain_db: number;
speech_ratio: number;
duration_s: number;
model: string;
elapsed_ms: number;
}
type Pending = { resolve: (v: any) => void; reject: (e: Error) => void; op: string; onEvent?: (ev: any) => void };
export class WorkerError extends Error {
constructor(
public code: string,
message: string,
) {
super(message);
}
}
/**
* STT 워커 프로세스 (JSON Lines). 죽으면 자동으로 다시 띄우고, 진행 중이던 요청은 실패로 돌려준다.
* docs/dev/ARCHITECTURE.md 1장.
*/
export class WorkerClient extends EventEmitter {
private proc: ChildProcess | null = null;
private seq = 0;
private pending = new Map<string, Pending>();
private stopping = false;
private restarts = 0;
ready = false;
lastError: string | null = null;
constructor(private command: WorkerCommand) {
super();
}
start(): void {
this.stopping = false;
this.spawn();
}
private spawn(): void {
const { cmd, args, cwd, env } = this.command;
log.info(`워커 시작: ${cmd} ${args.join(' ')}`);
const p = spawn(cmd, args, {
cwd,
env: { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', ...env },
stdio: ['pipe', 'pipe', 'pipe'],
windowsHide: true,
});
this.proc = p;
// 게임 프레임을 덜 건드리도록 낮은 우선순위
try {
if (p.pid) os.setPriority(p.pid, 10);
} catch {
/* 권한 없음 무시 */
}
readline.createInterface({ input: p.stdout! }).on('line', (line) => this.onLine(line));
readline.createInterface({ input: p.stderr! }).on('line', (line) => {
if (line.trim()) log.debug(line);
if (/Traceback|Error/.test(line)) this.lastError = line.slice(0, 500);
});
p.on('error', (e) => {
this.lastError = e.message;
log.error('워커 실행 실패', e);
});
p.on('exit', (code, sig) => {
this.ready = false;
this.proc = null;
for (const [, pend] of this.pending) pend.reject(new WorkerError('worker_exit', `워커 종료 (code=${code} sig=${sig})`));
this.pending.clear();
this.emit('exit', code);
if (this.stopping) return;
this.restarts++;
const delay = Math.min(30000, 1000 * 2 ** Math.min(this.restarts, 5));
log.warn(`워커가 종료됨 (code=${code}). ${delay / 1000}초 뒤 다시 시작`);
setTimeout(() => !this.stopping && this.spawn(), delay);
});
this.request('hello', {}, 30000)
.then((r) => {
this.ready = true;
this.restarts = 0;
log.info(`워커 준비됨 ${JSON.stringify(r)}`);
this.emit('ready', r);
})
.catch((e) => log.error('워커 hello 실패', e));
}
private onLine(line: string): void {
let msg: any;
try {
msg = JSON.parse(line);
} catch {
log.debug(`워커 stdout(비프로토콜): ${line}`);
return;
}
if (msg.event) {
if (msg.id && this.pending.has(msg.id)) this.pending.get(msg.id)!.onEvent?.(msg);
this.emit('event', msg);
return;
}
const pend = this.pending.get(msg.id);
if (!pend) return;
this.pending.delete(msg.id);
if (msg.ok) pend.resolve(msg.result);
else pend.reject(new WorkerError(msg.error?.code || 'error', msg.error?.message || '워커 오류'));
}
request<T = any>(op: string, params: Record<string, unknown>, timeoutMs = 600000, onEvent?: (ev: any) => void): Promise<T> {
if (!this.proc || !this.proc.stdin) return Promise.reject(new WorkerError('worker_down', 'STT 워커가 실행 중이 아닙니다'));
const id = String(++this.seq);
return new Promise<T>((resolve, reject) => {
const timer =
timeoutMs > 0
? setTimeout(() => {
if (this.pending.delete(id)) reject(new WorkerError('timeout', `${op} 시간 초과`));
}, timeoutMs)
: null;
this.pending.set(id, {
op,
onEvent,
resolve: (v) => {
if (timer) clearTimeout(timer);
resolve(v);
},
reject: (e) => {
if (timer) clearTimeout(timer);
reject(e);
},
});
this.proc!.stdin!.write(JSON.stringify({ id, op, ...params }) + '\n');
});
}
async stop(): Promise<void> {
this.stopping = true;
if (!this.proc) return;
const p = this.proc;
try {
await Promise.race([this.request('shutdown', {}, 5000), new Promise((r) => setTimeout(r, 5000))]);
} catch {
/* 무시 */
}
if (p.exitCode === null) p.kill();
}
}

243
app/src/core/timeline.ts Normal file
View File

@@ -0,0 +1,243 @@
import type { EventItem, TimeLabel, TimelineItem, TimelinePage, UtteranceItem, GameType } from '@gvr/shared';
import { fmtClock, fmtReal } from '@gvr/shared';
import type { EventRow, MatchRow, RoundRow, Store, UtteranceRow } from './db/db.js';
export interface MatchCtx {
match: MatchRow;
rounds: RoundRow[];
}
/** 시간 표시 규칙 (보고서 6-3, Q5): 발로란트 "R7 · 0:42" + 경기 경과, 롤 게임 시간, 경기 밖 현실 시각 */
export function timeLabel(ts: number, ctx: MatchCtx | null): TimeLabel {
if (!ctx) return { primary: fmtReal(ts), real: ts };
const { match, rounds } = ctx;
const gameTs = ts - match.clock_offset;
const elapsed = gameTs - match.started_at;
// 경기 전(챔피언 선택 채팅 등)·경기 후는 현실 시각
if (elapsed < -1000 || (match.ended_at && ts > match.ended_at + 1000)) return { primary: fmtReal(ts), real: ts };
if (match.game === 'lol') return { primary: fmtClock(Math.max(0, elapsed)), real: ts };
// 발로란트
const r = rounds.find((x) => gameTs >= x.started_at && gameTs <= x.ended_at) ?? rounds.find((x) => gameTs < x.started_at && x.num === 1);
if (r) {
if (gameTs < r.combat_at) return { primary: `R${r.num} · 구매`, secondary: fmtClock(Math.max(0, elapsed)), real: ts };
return { primary: `R${r.num} · ${fmtClock(gameTs - r.combat_at)}`, secondary: fmtClock(Math.max(0, elapsed)), real: ts };
}
return { primary: fmtClock(Math.max(0, elapsed)), secondary: '경기 중', real: ts };
}
export function roundAt(ts: number, ctx: MatchCtx | null): number | undefined {
if (!ctx || ctx.match.game !== 'valorant') return undefined;
const gameTs = ts - ctx.match.clock_offset;
return ctx.rounds.find((x) => gameTs >= x.started_at && gameTs <= x.ended_at)?.num;
}
export class Timeline {
constructor(private store: Store) {}
private ctxCache = new Map<string, { at: number; ctx: MatchCtx }>();
ctx(matchId: string | null | undefined): MatchCtx | null {
if (!matchId) return null;
const c = this.ctxCache.get(matchId);
if (c && Date.now() - c.at < 5000) return c.ctx;
const match = this.store.getMatch(matchId);
if (!match) return null;
const ctx = { match, rounds: this.store.rounds(matchId) };
this.ctxCache.set(matchId, { at: Date.now(), ctx });
return ctx;
}
invalidate(matchId?: string): void {
if (matchId) this.ctxCache.delete(matchId);
else this.ctxCache.clear();
}
utteranceItem(u: UtteranceRow): UtteranceItem {
const ctx = this.ctx(u.match_id);
return {
kind: 'utterance',
id: u.id,
ts: u.started_at,
endTs: u.ended_at,
userId: u.user_id,
text: u.noise && !u.corrected ? null : u.text,
words: u.noise && !u.corrected ? [] : safeJson(u.words, []),
noise: !!u.noise && !u.corrected,
status: u.status as UtteranceItem['status'],
corrected: !!u.corrected,
confidence: u.confidence,
model: u.model,
audio:
u.audio_path && !u.audio_deleted
? { url: `/api/audio/${u.id}`, durationMs: u.ended_at - u.started_at, gainDb: u.gain_db ?? 0 }
: null,
game: ctx ? { type: ctx.match.game as GameType, matchId: ctx.match.id, round: roundAt(u.started_at, ctx) } : null,
time: timeLabel(u.started_at, ctx),
};
}
eventItem(e: EventRow): EventItem {
const ctx = this.ctx(e.match_id);
const data = safeJson(e.data, {});
const userId = e.actor_puuid ? this.store.userIdForPuuid(e.actor_puuid) : undefined;
return {
kind: 'event',
id: e.id,
ts: e.ts,
game: e.game,
matchId: e.match_id,
type: e.type as EventItem['type'],
data,
time: timeLabel(e.ts, ctx),
...(userId ? { userId } : {}),
};
}
query(q: TimelineQuery): TimelinePage {
const limit = Math.min(Math.max(q.limit ?? 100, 1), 500);
const desc = q.order !== 'asc';
const cur = q.cursor ? parseCursor(q.cursor) : null;
const types = q.types && q.types.length ? new Set(q.types) : null;
const wantUtt = !types || types.has('utterance');
const eventTypes = types
? [...types].flatMap((t) => (t === 'round' ? ['round_end'] : t === 'match' ? ['match_start', 'match_end'] : t === 'utterance' ? [] : [t]))
: null;
const wantEvents = (!types || (eventTypes && eventTypes.length > 0)) && q.game !== 'none';
const cmp = desc ? '<' : '>';
const ord = desc ? 'DESC' : 'ASC';
let utts: UtteranceRow[] = [];
if (wantUtt) {
const where: string[] = [];
const args: any[] = [];
if (cur) {
where.push(`(u.started_at ${cmp} ? OR (u.started_at = ? AND u.id ${cmp} ?))`);
args.push(cur.ts, cur.ts, cur.id);
}
if (q.users?.length) {
where.push(`u.user_id IN (${q.users.map(() => '?').join(',')})`);
args.push(...q.users);
}
if (q.match) {
where.push('u.match_id = ?');
args.push(q.match);
} else if (q.game === 'none') where.push('u.match_id IS NULL');
else if (q.game) {
where.push('u.match_id IN (SELECT id FROM matches WHERE game = ?)');
args.push(q.game);
}
if (q.from) {
where.push('u.started_at >= ?');
args.push(q.from);
}
if (q.to) {
where.push('u.started_at <= ?');
args.push(q.to);
}
if (q.hideNoise) where.push('(u.noise = 0 OR u.corrected = 1)');
if (q.q) {
const kw = q.q.trim();
if ([...kw].length >= 3) {
where.push('u.rowid IN (SELECT rowid FROM utterances_fts WHERE utterances_fts MATCH ?)');
args.push(`"${kw.replace(/"/g, '""')}"`);
} else {
where.push('u.text LIKE ?');
args.push(`%${kw.replace(/[%_]/g, '')}%`);
}
}
utts = this.store.db
.prepare(
`SELECT u.rowid, u.* FROM utterances u ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
ORDER BY u.started_at ${ord}, u.id ${ord} LIMIT ?`,
)
.all(...args, limit + 1) as UtteranceRow[];
}
let evs: EventRow[] = [];
if (wantEvents) {
const where: string[] = [];
const args: any[] = [];
if (cur) {
where.push(`(e.ts ${cmp} ? OR (e.ts = ? AND e.id ${cmp} ?))`);
args.push(cur.ts, cur.ts, cur.id);
}
if (eventTypes) {
where.push(`e.type IN (${eventTypes.map(() => '?').join(',')})`);
args.push(...eventTypes);
}
if (q.match) {
where.push('e.match_id = ?');
args.push(q.match);
} else if (q.game) {
where.push('e.game = ?');
args.push(q.game);
}
if (q.users?.length) {
const puuids = this.store
.listAccounts()
.filter((a) => q.users!.includes(a.user_id))
.map((a) => a.puuid);
if (!puuids.length) where.push('0');
else {
const ph = puuids.map(() => '?').join(',');
where.push(`(e.actor_puuid IN (${ph}) OR e.target_puuid IN (${ph}))`);
args.push(...puuids, ...puuids);
}
}
if (q.from) {
where.push('e.ts >= ?');
args.push(q.from);
}
if (q.to) {
where.push('e.ts <= ?');
args.push(q.to);
}
if (q.q) {
where.push(`e.type = 'chat' AND e.data LIKE ?`);
args.push(`%${q.q.trim().replace(/[%_]/g, '')}%`);
}
evs = this.store.db
.prepare(`SELECT e.* FROM game_events e ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY e.ts ${ord}, e.id ${ord} LIMIT ?`)
.all(...args, limit + 1) as EventRow[];
}
const merged: { ts: number; id: string; item: () => TimelineItem }[] = [
...utts.map((u) => ({ ts: u.started_at, id: u.id, item: () => this.utteranceItem(u) })),
...evs.map((e) => ({ ts: e.ts, id: e.id, item: () => this.eventItem(e) })),
];
merged.sort((a, b) => (desc ? b.ts - a.ts || (b.id < a.id ? -1 : 1) : a.ts - b.ts || (a.id < b.id ? -1 : 1)));
const page = merged.slice(0, limit);
const hasMore = merged.length > limit;
const last = page[page.length - 1];
return { items: page.map((p) => p.item()), next: hasMore && last ? `${last.ts}:${last.id}` : null };
}
}
export interface TimelineQuery {
users?: string[];
game?: 'valorant' | 'lol' | 'none';
match?: string;
from?: number;
to?: number;
q?: string;
types?: string[];
hideNoise?: boolean;
cursor?: string;
limit?: number;
order?: 'asc' | 'desc';
}
function parseCursor(c: string): { ts: number; id: string } | null {
const i = c.indexOf(':');
if (i < 0) return null;
const ts = Number(c.slice(0, i));
return Number.isFinite(ts) ? { ts, id: c.slice(i + 1) } : null;
}
export function safeJson<T>(s: string | null | undefined, d: T): T {
if (!s) return d;
try {
return JSON.parse(s) as T;
} catch {
return d;
}
}

View File

@@ -0,0 +1,9 @@
import { EventEmitter } from 'node:events';
import type { LiveEvent } from '@gvr/shared';
/** 코어 내부 이벤트 버스. 'live' 는 사이트로 그대로 나가는 이벤트. */
export class Bus extends EventEmitter {
live(ev: LiveEvent): void {
this.emit('live', ev);
}
}

13
app/src/core/util/ids.ts Normal file
View File

@@ -0,0 +1,13 @@
import crypto from 'node:crypto';
/** 시간순 정렬되는 짧은 ID (ms 타임스탬프 base36 + 랜덤) */
export function newId(ts = Date.now()): string {
return ts.toString(36).padStart(9, '0') + crypto.randomBytes(5).toString('hex');
}
const PALETTE = ['#ff4655', '#14c1b7', '#c8aa6e', '#7aa2ff', '#f5a623', '#b48cff', '#5fd068', '#ff7ab6', '#4fd1ff', '#ffd45c'];
export function colorFor(id: string): string {
let h = 0;
for (const c of id) h = (h * 31 + c.charCodeAt(0)) >>> 0;
return PALETTE[h % PALETTE.length];
}

49
app/src/core/util/log.ts Normal file
View File

@@ -0,0 +1,49 @@
import fs from 'node:fs';
import path from 'node:path';
type Level = 'debug' | 'info' | 'warn' | 'error';
const order: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };
let minLevel: Level = (process.env.GVR_LOG_LEVEL as Level) || 'info';
let stream: fs.WriteStream | null = null;
const listeners = new Set<(line: string) => void>();
export function initLogFile(dir: string): void {
fs.mkdirSync(dir, { recursive: true });
const day = new Date().toISOString().slice(0, 10);
stream = fs.createWriteStream(path.join(dir, `gvr-${day}.log`), { flags: 'a' });
}
export function setLogLevel(l: Level): void {
minLevel = l;
}
export function onLog(fn: (line: string) => void): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
function write(level: Level, scope: string, msg: string, extra?: unknown): void {
if (order[level] < order[minLevel]) return;
let line = `${new Date().toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}`;
if (extra !== undefined) {
if (extra instanceof Error) line += ` ${extra.stack || extra.message}`;
else {
try {
line += ' ' + JSON.stringify(extra);
} catch {
line += ' ' + String(extra);
}
}
}
(level === 'error' || level === 'warn' ? process.stderr : process.stdout).write(line + '\n');
stream?.write(line + '\n');
for (const l of listeners) l(line);
}
export function logger(scope: string) {
return {
debug: (m: string, e?: unknown) => write('debug', scope, m, e),
info: (m: string, e?: unknown) => write('info', scope, m, e),
warn: (m: string, e?: unknown) => write('warn', scope, m, e),
error: (m: string, e?: unknown) => write('error', scope, m, e),
};
}
export type Logger = ReturnType<typeof logger>;

185
app/test/core.test.ts Normal file
View File

@@ -0,0 +1,185 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { Store } from '../src/core/db/db.ts';
import { Timeline, timeLabel } from '../src/core/timeline.ts';
import { diffWords, Dictionary } from '../src/core/dict/dictionary.ts';
import { realignWords } from '../src/core/api/server.ts';
import { processMatchDetails } from '../src/core/games/valorant.ts';
import { GameAssets } from '../src/core/games/assets.ts';
import { OggOpusWriter, opusSamples, SILENCE_FRAME } from '../src/core/discord/ogg.ts';
import { Retention } from '../src/core/retention.ts';
import { makeValDetails, SELF } from './fixtures/make-val-details.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-test-'));
test('Ogg Opus writer: ffmpeg 가 읽을 수 있고 길이가 맞다', () => {
const dir = tmp();
const src = path.join(dir, 'src.ogg');
// 2초 톤을 Opus 로 만든 뒤 패킷을 꺼내 다시 쓴다
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', '-ac', '2', '-ar', '48000', '-c:a', 'libopus', '-frame_duration', '20', src]);
const packets = readOggPackets(fs.readFileSync(src)).slice(2); // OpusHead, OpusTags 제외
const out = path.join(dir, 'out.ogg');
const w = new OggOpusWriter(out);
for (const p of packets) w.write(p);
for (let i = 0; i < 25; i++) w.write(SILENCE_FRAME); // 0.5초 무음 채우기
w.close();
assert.equal(opusSamples(SILENCE_FRAME), 960);
const dur = Number(execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', out]).toString());
assert.ok(Math.abs(dur - 2.5) < 0.05, `duration ${dur}`);
// 끝까지 디코드되는지
execFileSync('ffmpeg', ['-v', 'error', '-i', out, '-f', 'null', '-']);
});
function readOggPackets(buf: Buffer): Buffer[] {
const out: Buffer[] = [];
let pos = 0;
let cur: Buffer[] = [];
while (pos < buf.length) {
const nseg = buf[pos + 26];
const lacing = buf.subarray(pos + 27, pos + 27 + nseg);
let p = pos + 27 + nseg;
for (const l of lacing) {
cur.push(buf.subarray(p, p + l));
p += l;
if (l < 255) {
out.push(Buffer.concat(cur));
cur = [];
}
}
pos = p;
}
return out;
}
test('단어 diff: 고친 단어 쌍 추출', () => {
assert.deepEqual(diffWords('레이저 궁 빠졌어 비 싸이트 로태 하자', '레이즈 궁 빠졌어 B 사이트 로테 하자'), [
['레이저', '레이즈'],
['비 싸이트', 'B 사이트'],
['로태', '로테'],
]);
assert.deepEqual(diffWords('같은 문장', '같은 문장'), []);
});
test('단어 시각 재배치', () => {
const old = [
{ w: '레이저', s: 0.1, e: 0.5 },
{ w: '궁', s: 0.6, e: 0.8 },
];
assert.deepEqual(realignWords(old, '레이즈 궁', 1).map((w) => [w.w, w.s]), [
['레이즈', 0.1],
['궁', 0.6],
]);
const re = realignWords(old, '레이즈 궁 빠졌어', 1);
assert.equal(re.length, 3);
assert.equal(re[0].s, 0.1);
assert.ok(Math.abs(re[2].e - 0.8) < 0.02);
});
test('사전: 기본 사전 적재, 상황별 핫워드, 사이트 교정 학습', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const dict = new Dictionary(store, path.join(import.meta.dirname, '..', 'resources'), () => ({ valorant: true, lol: true, daily: true }));
dict.seed();
const hv = dict.hotwords('valorant').split(' ');
assert.ok(hv.length > 20 && hv.length <= 60);
assert.ok(hv.includes('레이즈') || hv.includes('제트'), hv.slice(0, 10).join(','));
assert.ok(dict.corrections().some((c) => c.from === '레이저' && c.to === '레이즈'));
assert.equal(dict.learn('나 오퍼래잇 삼', '나 오퍼레이터 삼'), 1);
assert.ok(dict.corrections().some((c) => c.from === '오퍼래잇' && c.to === '오퍼레이터'));
assert.ok(dict.hotwords('valorant').split(' ')[0] === '오퍼레이터', '사이트 교정 단어가 가장 먼저');
// 다시 seed 해도 사이트 교정은 남는다
dict.seed();
assert.ok(dict.corrections().some((c) => c.from === '오퍼래잇'));
store.close();
});
test('발로란트 경기 상세 → 라운드·킬·시간 표시', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const assets = new GameAssets(path.join(dir, 'cache'));
const S = Date.UTC(2026, 9, 15, 12, 0, 0);
const res = processMatchDetails(makeValDetails(S), SELF, assets, 'val-m-0001', S + 3000);
assert.equal(res.clockOffset, 0);
assert.equal(res.rounds.length, 3);
// R1 전투 시작 = 60000-25000 = 35000
assert.equal(res.rounds[0].combat_at, S + 35000);
assert.equal(res.rounds[0].started_at, S + 5000);
// R3 전투 시작 = 330000-20000 = 310000, R2 는 보간
assert.equal(res.rounds[2].combat_at, S + 310000);
assert.ok(res.rounds[1].combat_at > res.rounds[0].combat_at && res.rounds[1].combat_at < res.rounds[2].combat_at);
assert.deepEqual(res.result, { win: true, score: { ally: 2, enemy: 1 } });
const kills = res.events.filter((e) => e.type === 'kill');
assert.equal(kills.length, 4);
assert.ok(res.events.some((e) => e.type === 'spike' && JSON.parse(e.data).action === 'defuse'));
store.upsertMatch({ id: 'val-m-0001', game: 'valorant', started_at: S, ended_at: S + 420000, status: 'complete' });
store.replaceRounds('val-m-0001', res.rounds);
const ctx = { match: store.getMatch('val-m-0001')!, rounds: store.rounds('val-m-0001') };
// R1 전투 42초 후
assert.deepEqual(timeLabel(S + 35000 + 42000, ctx).primary, 'R1 · 0:42');
assert.equal(timeLabel(S + 35000 + 42000, ctx).secondary, '1:17');
// 구매 단계
assert.equal(timeLabel(S + 10000, ctx).primary, 'R1 · 구매');
// 경기 밖: 현실 시각
assert.match(timeLabel(S + 3600000, ctx).primary, /^\d\d:\d\d:\d\d$/);
store.close();
});
test('타임라인 조회: 필터·검색·커서', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const tl = new Timeline(store);
store.upsertUser({ id: 'u1', name: '승한', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
const t0 = Date.UTC(2026, 9, 15, 12, 0, 0);
const texts = ['스모크 깔게 미드로 와', '레이즈 궁 빠졌어', '오퍼 사줘', '배고프다 치킨 먹자', 'B 사이트 로테 하자'];
texts.forEach((t, i) => {
store.insertUtterance({ id: `x${i}`, session_id: null, user_id: i % 2 ? 'u2' : 'u1', started_at: t0 + i * 1000, ended_at: t0 + i * 1000 + 800, audio_path: null, match_id: null });
store.updateUtteranceResult(`x${i}`, { text: t, raw_text: t, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 2, model: 'tiny', status: 'realtime' });
});
store.insertUtterance({ id: 'n1', session_id: null, user_id: 'u1', started_at: t0 + 9000, ended_at: t0 + 9500, audio_path: null, match_id: null });
store.updateUtteranceResult('n1', { text: null, raw_text: '시청해 주셔서 감사합니다', words: [], noise: true, noise_reason: 'hallucination', confidence: 0.2, lufs: -40, gain_db: 20, model: 'tiny', status: 'realtime' });
let page = tl.query({ limit: 3 });
assert.equal(page.items.length, 3);
assert.equal(page.items[0].id, 'n1');
const page2 = tl.query({ limit: 3, cursor: page.next! });
assert.deepEqual(page2.items.map((i) => i.id), ['x2', 'x1', 'x0']);
assert.equal(tl.query({ hideNoise: true }).items.length, 5);
assert.deepEqual(tl.query({ q: '레이즈 궁' }).items.map((i) => i.id), ['x1']);
assert.deepEqual(tl.query({ q: '오퍼' }).items.map((i) => i.id), ['x2']);
assert.equal(tl.query({ users: ['u2'] }).items.length, 2);
page = tl.query({ order: 'asc', limit: 2 });
assert.deepEqual(page.items.map((i) => i.id), ['x0', 'x1']);
// 교정하면 검색 색인도 바뀐다
store.correctUtterance('x3', '배고프다 피자 먹자', []);
assert.deepEqual(tl.query({ q: '피자' }).items.map((i) => i.id), ['x3']);
assert.equal(tl.query({ q: '치킨' }).items.length, 0);
store.close();
});
test('7일 지난 음성만 삭제, 텍스트는 남음', () => {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const audio = path.join(dir, 'audio', '2026-10-01');
fs.mkdirSync(audio, { recursive: true });
const now = Date.now();
for (const [id, age] of [
['old', 8],
['new', 2],
] as const) {
const f = path.join(audio, `${id}.ogg`);
fs.writeFileSync(f, 'x'.repeat(100));
store.insertUtterance({ id, session_id: null, user_id: 'u', started_at: now - age * 86400000, ended_at: now - age * 86400000 + 500, audio_path: f, match_id: null });
store.updateUtteranceResult(id, { text: id, raw_text: id, words: [], noise: false, noise_reason: null, confidence: 1, lufs: -18, gain_db: 0, model: 'm', status: 'precise' });
}
const r = new Retention(store, () => 7, () => path.join(dir, 'audio')).run(now);
assert.equal(r.deleted, 1);
assert.ok(!fs.existsSync(path.join(audio, 'old.ogg')));
assert.ok(fs.existsSync(path.join(audio, 'new.ogg')));
assert.equal(store.getUtterance('old')!.text, 'old');
assert.equal(store.getUtterance('old')!.audio_deleted, 1);
store.close();
});

84
app/test/e2e-stt.test.ts Normal file
View File

@@ -0,0 +1,84 @@
// 실제 STT 워커(CPU, tiny)와 코어를 붙여 "발화 저장 → 대기열 → STT → DB → 실시간 이벤트 → API" 를 확인한다.
// 워커 venv(worker/.venv)와 HF 캐시의 tiny 모델이 있어야 한다. 없으면 건너뛴다.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const root = path.resolve(import.meta.dirname, '..', '..');
const py = path.join(root, 'worker', '.venv', 'bin', 'python');
const hfTiny = path.join(os.homedir(), '.cache/huggingface/hub/models--Systran--faster-whisper-tiny/snapshots');
const skip = !fs.existsSync(py) || !fs.existsSync(hfTiny);
test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API', { skip, timeout: 180000 }, async () => {
const { startCore } = await import('../src/core/index.ts');
const dataDir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-e2e-'));
const models = path.join(dataDir, 'models');
fs.mkdirSync(models, { recursive: true });
fs.symlinkSync(path.join(hfTiny, fs.readdirSync(hfTiny)[0]), path.join(models, 'tiny'));
fs.writeFileSync(
path.join(dataDir, 'settings.json'),
JSON.stringify({ stt: { realtimeModel: 'tiny', preciseModel: 'tiny', device: 'cpu', computeType: 'int8' }, games: { valorant: false, lol: false } }),
);
const core = await startCore({
dataDir,
resourcesDir: path.join(root, 'app', 'resources'),
worker: { cmd: py, args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') },
version: 'test',
});
const live: any[] = [];
core.bus.on('live', (e) => live.push(e));
try {
const wait = async (fn: () => boolean, ms: number, label: string) => {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error(`timeout ${label}: ${JSON.stringify(core.stt.status)}`);
await new Promise((r) => setTimeout(r, 100));
}
};
await wait(() => core.stt.status.slots.realtime.state === 'loaded', 60000, 'model load');
core.store.upsertUser({ id: 'u1', name: '승한', avatar: null });
const fx = path.join(root, 'worker', 'tests', 'fixtures');
const items: [string, string][] = [
['speech', 'speech_ko.ogg'],
['quiet', 'speech_ko_quiet.ogg'],
['keys', 'keyboard_clicks.ogg'],
];
const t0 = Date.now();
for (const [id, f] of items) {
const dst = path.join(core.paths().audio, 'test', `${id}.ogg`);
fs.mkdirSync(path.dirname(dst), { recursive: true });
fs.copyFileSync(path.join(fx, f), dst);
core.store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: t0, ended_at: t0 + 3000, audio_path: dst, match_id: null });
core.stt.enqueue(id, 'realtime');
}
await wait(() => items.every(([id]) => core.store.getUtterance(id)!.status !== 'pending'), 120000, 'transcribe');
const sp = core.store.getUtterance('speech')!;
console.log('speech →', sp.text, '| raw:', sp.raw_text, '| gain', sp.gain_db);
assert.ok(['realtime', 'precise'].includes(sp.status), sp.status);
assert.ok(sp.text && sp.text.includes('레이즈'), sp.text ?? '');
assert.ok(JSON.parse(sp.words).length >= 3);
const q = core.store.getUtterance('quiet')!;
assert.ok(q.gain_db > 15, `quiet gain ${q.gain_db}`);
const k = core.store.getUtterance('keys')!;
assert.equal(k.noise, 1);
assert.ok(live.filter((e) => e.type === 'utterance.updated').length >= 3);
// 기록 API (사이트가 중계로 부르는 것과 같은 경로)
const res = await core.api.inject({ method: 'GET', url: '/api/timeline?limit=10' });
const page = res.json();
assert.equal(page.items.length, 3);
const audio = await core.api.inject({ method: 'GET', url: '/api/audio/speech', headers: { range: 'bytes=0-99' } });
assert.equal(audio.statusCode, 206);
assert.equal(audio.rawPayload.length, 100);
// 사이트 교정 → 사전·학습 데이터
const patched = await core.api.inject({ method: 'PATCH', url: '/api/utterances/speech', payload: { text: '레이즈 궁 빠졌어 B 사이트 로테 하자' } });
assert.equal(patched.json().corrected, true);
assert.equal(core.store.trainingSamples().length, 1);
assert.ok(fs.existsSync(core.store.trainingSamples()[0].audio_path));
const search = (await core.api.inject({ method: 'GET', url: '/api/timeline?q=' + encodeURIComponent('B 사이트') })).json();
assert.deepEqual(search.items.map((i: any) => i.id), ['speech']);
} finally {
await core.stop();
}
});

58
app/test/fixtures/make-val-details.ts vendored Normal file
View File

@@ -0,0 +1,58 @@
// 발로란트 match-details 형태의 합성 데이터 (pd.<shard>.a.pvp.net/match-details/v1/matches/{id} 응답 구조)
export const SELF = 'self-puuid-0001';
export const ASCENT = '/Game/Maps/Ascent/Ascent';
const JETT = 'add6443a-41bd-e414-f6ad-e58d267f4e95';
const SAGE = '569fdd95-4d10-43ab-ca70-79becc718b46';
const REYNA = 'a3bfb853-43b2-7238-a4f1-ad90e9e46bcc';
const VANDAL = '9c82e19d-4575-0200-1a81-3eacf00cf872';
export function makeValDetails(gameStart: number) {
const players = [
{ subject: SELF, gameName: '승한', tagLine: 'KR1', teamId: 'Blue', characterId: JETT, competitiveTier: 15, stats: { score: 4200, roundsPlayed: 3, kills: 3, deaths: 1, assists: 1 } },
{ subject: 'ally-2', gameName: '민수', tagLine: 'KR1', teamId: 'Blue', characterId: SAGE, competitiveTier: 14, stats: { score: 1800, roundsPlayed: 3, kills: 1, deaths: 2, assists: 3 } },
{ subject: 'enemy-1', gameName: '상대1', tagLine: '0000', teamId: 'Red', characterId: REYNA, competitiveTier: 15, stats: { score: 3000, roundsPlayed: 3, kills: 2, deaths: 3, assists: 0 } },
];
const kill = (gameTime: number, roundTime: number, killer: string, victim: string) => ({
gameTime,
roundTime,
killer,
victim,
victimLocation: { x: 6500, y: -7000 },
assistants: [],
playerLocations: [],
finishingDamage: { damageType: 'Weapon', damageItem: VANDAL.toUpperCase(), isSecondaryFireMode: false },
});
const roundResults = [
{
roundNum: 0,
roundResult: 'Eliminated',
winningTeam: 'Blue',
playerStats: [
{ subject: SELF, kills: [kill(60000, 25000, SELF, 'enemy-1')], economy: { spent: 800, remaining: 0, weapon: '', loadoutValue: 800 } },
{ subject: 'enemy-1', kills: [kill(70000, 35000, 'enemy-1', 'ally-2')] },
],
},
// 킬 없는 라운드 (시간 초과) → 보간
{ roundNum: 1, roundResult: 'Round timer expired', winningTeam: 'Red', playerStats: [] },
{
roundNum: 2,
roundResult: 'Bomb defused',
winningTeam: 'Blue',
plantRoundTime: 40000,
defuseRoundTime: 80000,
bombPlanter: 'enemy-1',
bombDefuser: SELF,
plantSite: 'B',
playerStats: [{ subject: SELF, kills: [kill(330000, 20000, SELF, 'enemy-1'), kill(331000, 21000, SELF, 'enemy-1')] }],
},
];
return {
matchInfo: { matchId: 'm-0001', mapId: ASCENT, gameStartMillis: gameStart, gameLengthMillis: 420000, queueID: 'competitive', gameMode: '/Game/GameModes/Bomb/BombGameMode.BombGameMode_C', isCompleted: true },
players,
teams: [
{ teamId: 'Blue', won: true, roundsWon: 2 },
{ teamId: 'Red', won: false, roundsWon: 1 },
],
roundResults,
};
}

123
app/test/games.test.ts Normal file
View File

@@ -0,0 +1,123 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { startMockRiot, lolLiveData } from './mock/riot.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-games-'));
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function until(fn: () => boolean, ms = 8000, label = 'condition') {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error(`timeout: ${label}`);
await sleep(50);
}
}
test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅→라운드→종료→상세', async () => {
const dir = tmp();
const mock = await startMockRiot(path.join(dir, 'mock'));
process.env.GVR_RIOT_LOCKFILE = mock.lockfile;
process.env.GVR_LCU_LOCKFILE = mock.lockfile;
process.env.GVR_VAL_GLZ = mock.base;
process.env.GVR_VAL_PD = mock.base;
process.env.GVR_LOL_LIVE_URL = mock.base;
process.env.GVR_POLL_MS = '150';
process.env.GVR_DETAIL_RETRY_MS = '100';
const { Store } = await import('../src/core/db/db.ts');
const { Timeline } = await import('../src/core/timeline.ts');
const { GameAssets } = await import('../src/core/games/assets.ts');
const { GameManager } = await import('../src/core/games/manager.ts');
const { Bus } = await import('../src/core/util/events.ts');
const { defaultSettings } = await import('../src/core/settings.ts');
const store = new Store(path.join(dir, 'db.sqlite'));
const bus = new Bus();
const live: any[] = [];
bus.on('live', (e) => live.push(e));
const tl = new Timeline(store);
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
const sttCalls: string[] = [];
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end') };
const assets = new GameAssets(path.join(dir, 'cache'));
(assets as any).refresh = async () => undefined; // 네트워크 없이
assets.lol = {
at: Date.now(),
version: '16.20.1',
champions: { ahri: { id: 'Ahri', key: '103', name: '아리', icon: '/game-assets/ddragon/cdn/16.20.1/img/champion/Ahri.png' }, 'key:103': { id: 'Ahri', key: '103', name: '아리', icon: '/game-assets/ddragon/cdn/16.20.1/img/champion/Ahri.png' } },
items: {},
};
const s = defaultSettings();
store.upsertUser({ id: 'owner', name: '승한', avatar: null });
const gm = new GameManager(store, assets, worker, stt, tl, bus, () => s, () => 'owner');
gm.start();
try {
// ---- 발로란트
await until(() => gm.status().valorant.connected, 5000, 'val connected');
mock.st.valStart = Date.now() - 2000;
mock.st.valState = 'INGAME';
await until(() => !!store.getMatch('val-m-0001'), 5000, 'val match start');
assert.equal(store.getMatch('val-m-0001')!.status, 'live');
mock.st.valMessages.push({ mid: 'c1', cid: 'm-0001-blue@ares-coregame.kr1.pvp.net', body: '스모크 깔게', game_name: '민수', puuid: 'ally-2', time: String(Date.now()) });
mock.st.valMessages.push({ mid: 'c2', cid: 'm-0001-all@ares-coregame.kr1.pvp.net', body: 'gg', game_name: '상대1', puuid: 'enemy-1', time: String(Date.now()) });
await until(() => store.events('val-m-0001').filter((e) => e.type === 'chat').length === 2, 5000, 'chat');
mock.st.ally = 1;
await until(() => store.events('val-m-0001').some((e) => e.type === 'round_end'), 5000, 'live round');
// 발화 하나 (경기 중)
store.insertUtterance({ id: 'u-val', session_id: null, user_id: 'owner', started_at: Date.now(), ended_at: Date.now() + 500, audio_path: null, match_id: gm.liveMatchAt(Date.now()) });
assert.equal(store.getUtterance('u-val')!.match_id, 'val-m-0001');
mock.st.valState = 'MENUS';
await until(() => store.getMatch('val-m-0001')!.status === 'complete', 8000, 'val details');
const ev = store.events('val-m-0001');
assert.equal(ev.filter((e) => e.type === 'kill').length, 4);
assert.equal(ev.filter((e) => e.type === 'chat').length, 2, '채팅은 상세 적용 뒤에도 남는다');
assert.ok(!ev.some((e) => e.id.includes('live-round')), '실시간 라운드는 상세로 교체');
assert.equal(store.rounds('val-m-0001').length, 3);
assert.ok(sttCalls.includes('start') && sttCalls.includes('end'));
assert.ok(store.listAccounts().some((a) => a.user_id === 'owner' && a.puuid === 'self-puuid-0001'), '주인 계정 자동 연결');
const sum = gm.summary(store.getMatch('val-m-0001')!);
assert.deepEqual(sum.score, { ally: 2, enemy: 1 });
assert.equal(sum.win, true);
// ---- 롤
mock.st.lolPhase = 'ChampSelect';
await until(() => (gm as any).adapters[1].pendingChat.length === 1, 5000, 'champ select chat');
mock.st.lolPhase = 'InProgress';
mock.st.lolLive = lolLiveData(120, [
{ EventID: 0, EventName: 'GameStart', EventTime: 0.05 },
{ EventID: 1, EventName: 'ChampionKill', EventTime: 75.2, KillerName: '승한', VictimName: '적1', Assisters: ['민수'] },
{ EventID: 2, EventName: 'DragonKill', EventTime: 90.0, KillerName: '민수', DragonType: 'Fire', Stolen: 'False' },
{ EventID: 3, EventName: 'TurretKilled', EventTime: 95.0, KillerName: '승한', TurretKilled: 'Turret_T2_R_03_A' },
]);
await until(() => !!store.getMatch('lol-7001'), 5000, 'lol start');
await until(() => store.events('lol-7001').length >= 4, 5000, 'lol events');
const lev = store.events('lol-7001');
const chat = lev.find((e) => e.type === 'chat')!;
assert.equal(JSON.parse(chat.data).text, '정글 갱 갈게요');
assert.equal(JSON.parse(chat.data).source, 'lcu');
const drag = JSON.parse(lev.find((e) => e.type === 'object' && e.data.includes('dragon'))!.data);
assert.equal(drag.label, '화염의 용');
assert.equal(drag.ally, true);
const tower = JSON.parse(lev.find((e) => e.data.includes('"tower"'))!.data);
assert.equal(tower.team, 'ORDER');
// 게임 시간 표시
const k = lev.find((e) => e.type === 'kill')!;
assert.equal(tl.eventItem(k).time.primary, '1:15');
mock.st.lolLive = null;
mock.st.lolPhase = 'EndOfGame';
mock.st.lolHistoryReady = true;
await until(() => store.getMatch('lol-7001')!.status === 'complete', 8000, 'lol history');
const det = JSON.parse(store.getMatch('lol-7001')!.detail!);
assert.equal(det.goldDiff.length, 2);
assert.equal(det.goldDiff[1].diff, 1700);
assert.equal(det.players[0].character.id, 'Ahri');
const kill = store.events('lol-7001').find((e) => e.type === 'kill')!;
assert.deepEqual(JSON.parse(kill.data).location, { x: 7000, y: 7200 });
} finally {
gm.stop();
await mock.close();
store.close();
}
});

162
app/test/mock/riot.ts Normal file
View File

@@ -0,0 +1,162 @@
// 가짜 Riot 서버 (발로란트 로컬 API · glz · pd, 롤 게임 클라이언트 API · LCU). 응답 구조는 실제 API 와 같게 맞췄다.
// 테스트와 M0 시연용. 실제 게임 PC 검증은 진단 화면(M0)으로 한다.
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import https from 'node:https';
import path from 'node:path';
import { makeValDetails, SELF, ASCENT } from '../fixtures/make-val-details.ts';
export interface MockState {
valState: 'MENUS' | 'PREGAME' | 'INGAME';
ally: number;
enemy: number;
valMessages: any[];
valMatchId: string;
valStart: number;
lolLive: any | null;
lolPhase: string;
lolGameId: number;
lolHistoryReady: boolean;
lolStart: number;
}
export async function startMockRiot(dir: string) {
fs.mkdirSync(dir, { recursive: true });
const key = path.join(dir, 'key.pem');
const cert = path.join(dir, 'cert.pem');
if (!fs.existsSync(cert))
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', key, '-out', cert, '-days', '2', '-subj', '/CN=127.0.0.1'], { stdio: 'ignore' });
const st: MockState = {
valState: 'MENUS',
ally: 0,
enemy: 0,
valMessages: [],
valMatchId: 'm-0001',
valStart: 0,
lolLive: null,
lolPhase: 'None',
lolGameId: 7001,
lolHistoryReady: false,
lolStart: 0,
};
const password = 'pw-test';
const presence = () => {
const priv = {
isValid: true,
sessionLoopState: st.valState,
matchMap: ASCENT,
partyOwnerMatchScoreAllyTeam: st.ally,
partyOwnerMatchScoreEnemyTeam: st.enemy,
provisioningFlow: 'Matchmaking',
queueId: 'competitive',
};
return Buffer.from(JSON.stringify(priv)).toString('base64');
};
const routes: [RegExp, (m: RegExpMatchArray, auth: string) => [number, any]][] = [
// ---- Riot Client local
[/^\/entitlements\/v1\/token$/, () => [200, { accessToken: 'acc-token', token: 'ent-token', subject: SELF, issuer: 'x' }]],
[
/^\/product-session\/v1\/external-sessions$/,
() => [200, { 'host_app': { productId: 'valorant', version: 'release-11.08-shipping-1-3765', launchConfiguration: { arguments: ['-ares-deployment=kr', '-config-endpoint=https://shared.kr.a.pvp.net'] } } }],
],
[/^\/chat\/v4\/presences$/, () => [200, { presences: [{ puuid: SELF, product: 'valorant', private: presence() }] }]],
[/^\/chat\/v6\/messages$/, () => [200, { messages: st.valMessages }]],
// ---- glz
[/^\/core-game\/v1\/players\/(.+)$/, () => (st.valState === 'INGAME' ? [200, { Subject: SELF, MatchID: st.valMatchId }] : [404, { errorCode: 'RESOURCE_NOT_FOUND' }])],
[
/^\/core-game\/v1\/matches\/(.+)$/,
() => [200, { MatchID: st.valMatchId, MapID: ASCENT, Players: [{ Subject: SELF, TeamID: 'Blue', CharacterID: 'add6443a-41bd-e414-f6ad-e58d267f4e95' }] }],
],
// ---- pd
[/^\/match-details\/v1\/matches\/(.+)$/, (_m, auth) => (auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}])],
// ---- LoL Live Client Data
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
// ---- LCU
[/^\/lol-gameflow\/v1\/gameflow-phase$/, () => [200, st.lolPhase]],
[/^\/lol-gameflow\/v1\/session$/, () => [200, { phase: st.lolPhase, gameData: { gameId: st.lolGameId, queue: { description: '솔로 랭크', id: 420 } } }]],
[/^\/lol-summoner\/v1\/current-summoner$/, () => [200, { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' }]],
[/^\/lol-chat\/v1\/conversations$/, () => [200, st.lolPhase === 'ChampSelect' ? [{ id: 'cs1@champ-select.kr', type: 'championSelect' }] : []]],
[/^\/lol-chat\/v1\/conversations\/(.+)\/messages$/, () => [200, [{ id: 'msg1', body: '정글 갱 갈게요', fromSummonerId: 11, timestamp: new Date(Date.now() - 5000).toISOString(), type: 'groupchat' }]]],
[/^\/lol-summoner\/v1\/summoners\/(\d+)$/, () => [200, { gameName: '민수' }]],
[/^\/lol-match-history\/v1\/games\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolHistory()] : [404, {}])],
[/^\/lol-match-history\/v1\/game-timelines\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolTimeline()] : [404, {}])],
];
const server = https.createServer({ key: fs.readFileSync(key), cert: fs.readFileSync(cert) }, (req, res) => {
const url = new URL(req.url || '/', 'https://x');
for (const [re, fn] of routes) {
const m = url.pathname.match(re);
if (!m) continue;
const [code, body] = fn(m, String(req.headers.authorization || ''));
res.writeHead(code, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
return;
}
res.writeHead(404);
res.end('{}');
});
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const port = (server.address() as any).port as number;
const lockfile = path.join(dir, 'lockfile');
fs.writeFileSync(lockfile, `Riot Client:1234:${port}:${password}:https`);
return { st, port, lockfile, base: `https://127.0.0.1:${port}`, close: () => new Promise<void>((r) => server.close(() => r())) };
}
export function lolLiveData(gameTime: number, events: any[]) {
const player = (name: string, raw: string, ko: string, team: string, k: number) => ({
riotId: `${name}#KR1`,
riotIdGameName: name,
riotIdTagLine: 'KR1',
summonerName: name,
rawChampionName: `game_character_displayname_${raw}`,
championName: ko,
team,
level: 9,
scores: { kills: k, deaths: 1, assists: 2, creepScore: 80 },
items: [{ itemID: 3031, displayName: '무한의 대검', count: 1 }],
});
return {
activePlayer: { riotId: '승한#KR1', summonerName: '승한', currentGold: 500 },
allPlayers: [player('승한', 'Ahri', '아리', 'ORDER', 3), player('민수', 'LeeSin', '리 신', 'ORDER', 1), player('적1', 'Garen', '가렌', 'CHAOS', 2)],
events: { Events: events },
gameData: { gameMode: 'CLASSIC', gameTime, mapName: 'Map11', mapNumber: 11 },
};
}
function lolHistory() {
return {
gameId: 7001,
gameDuration: 1500,
queueId: 420,
participants: [
{ participantId: 1, championId: 103, teamId: 100, stats: { kills: 5, deaths: 2, assists: 7, totalMinionsKilled: 180, neutralMinionsKilled: 10, goldEarned: 11000, item0: 3031, win: true, champLevel: 16 } },
{ participantId: 2, championId: 64, teamId: 100, stats: { kills: 3, deaths: 4, assists: 9, totalMinionsKilled: 30, neutralMinionsKilled: 140, goldEarned: 9000, win: true } },
{ participantId: 6, championId: 86, teamId: 200, stats: { kills: 4, deaths: 6, assists: 2, totalMinionsKilled: 170, neutralMinionsKilled: 0, goldEarned: 8500, win: false } },
],
participantIdentities: [
{ participantId: 1, player: { puuid: 'lol-self', gameName: '승한', tagLine: 'KR1' } },
{ participantId: 2, player: { puuid: 'lol-2', gameName: '민수', tagLine: 'KR1' } },
{ participantId: 6, player: { puuid: 'lol-6', gameName: '적1', tagLine: 'KR9' } },
],
teams: [
{ teamId: 100, win: 'Win' },
{ teamId: 200, win: 'Fail' },
],
};
}
function lolTimeline() {
return {
frames: [
{ timestamp: 0, participantFrames: { '1': { totalGold: 500 }, '2': { totalGold: 500 }, '6': { totalGold: 500 } }, events: [] },
{
timestamp: 60000,
participantFrames: { '1': { totalGold: 1500 }, '2': { totalGold: 1200 }, '6': { totalGold: 1000 } },
events: [
{ type: 'CHAMPION_KILL', timestamp: 75000, killerId: 1, victimId: 6, assistingParticipantIds: [2], position: { x: 7000, y: 7200 } },
{ type: 'ELITE_MONSTER_KILL', timestamp: 90000, killerId: 2, monsterType: 'DRAGON', monsterSubType: 'FIRE_DRAGON', position: { x: 9866, y: 4414 } },
{ type: 'BUILDING_KILL', timestamp: 95000, killerId: 1, teamId: 200, buildingType: 'TOWER_BUILDING', position: { x: 8955, y: 8510 } },
],
},
],
};
}

19
app/tsconfig.json Normal file
View File

@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"lib": ["ES2023", "DOM"],
"types": ["node"],
"baseUrl": ".",
"paths": { "@gvr/shared": ["../packages/shared/src/index.ts"] },
"allowImportingTsExtensions": true
},
"include": ["src/**/*.ts", "test/**/*.ts", "../packages/shared/src/**/*.ts"]
}

211
docs/dev/ARCHITECTURE.md Normal file
View File

@@ -0,0 +1,211 @@
# 겜녹이 (GVR) 개발 구조 · 인터페이스 계약
이 문서는 구현용 계약서다. 컴포넌트 사이의 경계(프로세스, 프로토콜, 데이터 형식)를
고정해 두고, 각 컴포넌트는 이 계약만 지키면 따로 만들 수 있다.
## 저장소 구조
```
app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript)
src/core/ 헤드리스 코어. Electron 없이 `node` 로도 돈다 (리눅스 테스트용)
src/main/ Electron 메인 프로세스 (트레이, 창, 마법사, safeStorage)
src/renderer/ 설정 창 · 첫 실행 마법사 UI
worker/ Python STT 워커 (faster-whisper, VAD, 음량 정규화, OCR, 모델 관리, 파인튜닝)
site/server/ 사이트 서버 (Fastify, Discord OAuth2, 기기 중계, 게임 이미지 캐시)
site/web/ 사이트 프런트엔드 (React + Vite)
packages/shared/ 앱·사이트가 같이 쓰는 TypeScript 타입 (protocol.ts)
deploy/site/ 사이트 서버 Docker 배포
tools/ 사전 생성기, 테스트 도구(목 Riot 서버, 음성 E2E)
```
## 1. 앱 코어 ↔ STT 워커 (stdin/stdout JSON Lines)
코어가 워커를 자식 프로세스로 띄운다. 한 줄 = JSON 하나 (UTF-8, `\n` 구분).
워커 stdout 에는 프로토콜 메시지만 쓴다. 로그는 stderr.
실행: `python -m gvr_worker` (개발) / `gvr-worker.exe` (PyInstaller 빌드)
환경변수: `GVR_DATA_DIR` (모델·CUDA DLL 폴더의 부모), `GVR_MODELS_DIR` (선택)
### 요청 (코어 → 워커)
```jsonc
{"id":"1","op":"hello"}
// → {"id":"1","ok":true,"result":{"version":"1.0.0","python":"3.11.9","device":"cuda"|"cpu"}}
{"id":"2","op":"gpu_info"}
// → {"gpus":[{"index":0,"name":"NVIDIA GeForce RTX 5070 Ti","vram_total_mb":16303,"vram_used_mb":1200,
// "driver":"581.15","cuda_driver":"13.0","compute_capability":"12.0"}],
// "recommend":{"realtime":"large-v3-turbo","precise":"large-v3","compute_type":"float16",
// "budget_mb":13000,"reason":"16GB: 게임 3GB 예약 후 실시간+정밀 동시 적재"}}
{"id":"3","op":"models"} // 다운로드된 모델·CUDA 런타임 상태
// → {"models":[{"name":"large-v3-turbo","repo":"mobiuslabsgmbh/faster-whisper-large-v3-turbo",
// "size_mb":1620,"installed":true,"path":"..."}...],
// "cuda_runtime":{"installed":true,"path":"...","size_mb":1100}}
{"id":"4","op":"download","target":"model","name":"large-v3-turbo"} // target: model | cuda_runtime
// 진행 중 이벤트: {"event":"progress","id":"4","done_mb":120.5,"total_mb":1620,"speed_mbps":11.2,"eta_s":130}
// 완료: {"id":"4","ok":true,"result":{"path":"..."}}
{"id":"5","op":"load","slot":"realtime","model":"large-v3-turbo","device":"cuda","compute_type":"float16"}
{"id":"6","op":"unload","slot":"precise"}
{"id":"7","op":"transcribe",
"slot":"realtime", // realtime | precise
"path":"C:/.../audio/2026-10-15/123.ogg", // Ogg Opus 48kHz mono
"hotwords":"레이즈 오멘 스파이크 ...", // 공백 구분, 상황별로 코어가 고름
"initial_prompt":null,
"corrections":[{"from":"레이저","to":"레이즈"},...], // 교정 사전 (정확 일치 → 자모 유사도)
"dictionary":["레이즈","오멘",...], // 자모 유사도 교정 후보
"profile_lufs":-23.5, // 이 유저 평소 음량 (없으면 null)
"target_lufs":-18,
"noise_sensitivity":0.5, // 0~1, 클수록 잡음 판정이 엄격(쉽게 [잡음])
"denoise":false}
// → {"id":"7","ok":true,"result":{
// "text":"레이즈 궁 빠졌어",
// "raw_text":"레이저 궁 빠졌어", // 교정 전
// "words":[{"w":"레이즈","s":0.12,"e":0.48,"p":0.93},...], // s/e: 파일 시작 기준 초
// "noise":false, "noise_reason":null, // "vad"|"no_speech"|"hallucination"|"repetition"
// "confidence":0.87, // exp(avg_logprob) 평균
// "lufs":-31.2, "gain_db":13.2, // 측정 음량, 재생 시 적용할 게인
// "speech_ratio":0.82, "duration_s":2.4,
// "model":"large-v3-turbo", "elapsed_ms":310}}
{"id":"8","op":"ocr_start","window_title":"League of Legends (TM) Client",
"region":{"x":0,"y":0.62,"w":0.32,"h":0.25}, // 창 크기 대비 비율 (채팅 영역)
"fps":3, "lang":"ko"}
// 이벤트: {"event":"ocr_line","ts":1760000000000,"text":"[12:34] [팀] 민수 (아리): 드래곤 가자",
// "parsed":{"game_time":"12:34","channel":"team","sender":"민수","champion":"아리","message":"드래곤 가자"}}
{"id":"9","op":"ocr_stop"}
{"id":"10","op":"ocr_image","path":"..."} // 테스트용: 이미지 한 장 OCR → {"lines":[...]}
{"id":"11","op":"train", ...} // 파인튜닝 (worker/gvr_worker/finetune 참고, M8)
{"id":"99","op":"shutdown"}
```
오류: `{"id":"7","ok":false,"error":{"code":"model_not_loaded","message":"..."}}`
## 2. 앱 데이터 폴더
포터블: exe 옆 `GVR-Data/` (단일 exe 포터블이면 `PORTABLE_EXECUTABLE_DIR` 옆).
개발/리눅스: `GVR_DATA_DIR` 환경변수.
```
GVR-Data/
settings.json 일반 설정 (평문)
secrets.bin 비밀값 (Windows: Electron safeStorage = DPAPI, 헤드리스: 0600 평문 JSON)
gvr.sqlite 기록 DB
audio/YYYY-MM-DD/<utteranceId>.ogg
training/<sampleId>.ogg 교정한 문장의 음성 조각 (자동 삭제 제외, A3)
models/<name>/ CTranslate2 모델
cuda/ cuBLAS·cuDNN DLL
tts/ 안내 음성 캐시 (Ogg Opus)
logs/
```
## 3. 기록 DB (SQLite, better-sqlite3)
`app/src/core/db/schema.sql` 이 기준. 요약:
- `users(id TEXT PK, name, color, avatar, excluded INT, gain_lufs REAL, gain_n INT, updated_at)`
- `game_accounts(user_id, puuid, riot_id, PRIMARY KEY(user_id, puuid))`
- `sessions(id PK, guild_id, channel_id, channel_name, started_at, ended_at)`
- `utterances(id TEXT PK, session_id, user_id, started_at INT ms, ended_at INT ms, audio_path, audio_deleted INT,
text, raw_text, words JSON, noise INT, noise_reason, confidence, lufs, gain_db, model, status
('pending'|'realtime'|'precise'|'failed'), match_id, corrected INT, created_at)`
- `utterances_fts` (FTS5 trigram, content=utterances)
- `matches(id TEXT PK, game ('valorant'|'lol'), started_at, ended_at, map, mode, queue, result JSON, detail JSON, status)`
- `rounds(match_id, num, started_at, combat_at, ended_at, winner, result_code, PRIMARY KEY(match_id,num))`
- `game_events(id PK, match_id, game, type, ts INT ms(real), game_time_ms, round, actor_puuid, target_puuid, data JSON)`
- `dictionary(id PK, word, pack, kind ('hotword'|'correction'), from_text, source ('builtin'|'user'|'site'), enabled)`
- `training_samples(id PK, utterance_id, text, audio_path, used INT, created_at)`
## 4. 앱 HTTP API (코어 Fastify, 127.0.0.1) — 사이트 서버가 그대로 중계
사이트 브라우저 → `https://gvr.tkrmagid.kr/api/...` → 사이트 서버 → WS → 앱 코어 `/api/...`.
요청에는 사이트 서버가 `x-gvr-user` (JSON: `{id,name,avatar}`) 헤더를 붙인다.
| Method | Path | 설명 |
|---|---|---|
| GET | `/api/overview` | `{guild, recording:{active,channel,since,participants}, users, games:{valorant:{connected},lol:{connected}}, counts}` |
| GET | `/api/users` | `User[]` |
| GET | `/api/users/:id` | `{user, stats:{talkMs,count,topWords:[{w,n}]}, matches:[MatchSummary]}` |
| GET | `/api/timeline` | 쿼리 아래 참고 → `{items:TimelineItem[], next:string|null}` |
| GET | `/api/audio/:utteranceId` | `audio/ogg` (Range 지원). 7일 지나 삭제됐으면 410 |
| GET | `/api/matches` | `?game=&limit=&before=` → `MatchSummary[]` |
| GET | `/api/matches/:id` | `MatchDetail` |
| PATCH | `/api/utterances/:id` | `{text}` → 교정 저장, 교정 사전·학습 데이터 반영. 응답 `TimelineItem` |
| GET | `/api/dictionary` | 사전 목록 |
`/api/timeline` 쿼리: `users=a,b` · `game=valorant|lol|none` · `match=<id>` · `from=<ms>&to=<ms>` ·
`q=<키워드>` · `types=utterance,kill,chat,object,round` · `hideNoise=1` · `cursor=<opaque>` · `limit=100` ·
`order=desc|asc` (기본 desc = 최신 먼저).
### TimelineItem
```ts
type TimeLabel = { primary: string; secondary?: string; real: number }; // "R7 · 0:42" / "12:18"
type TimelineItem =
| { kind:'utterance'; id:string; ts:number; endTs:number; userId:string; text:string|null;
words:{w:string;s:number;e:number;p?:number}[]; noise:boolean; status:'pending'|'realtime'|'precise'|'failed';
corrected:boolean; confidence:number|null; model:string|null;
audio:{url:string; durationMs:number; gainDb:number}|null; // null = 삭제됨
game:{type:'valorant'|'lol'; matchId:string; round?:number}|null; time:TimeLabel }
| { kind:'event'; id:string; ts:number; game:'valorant'|'lol'; matchId:string; type:'kill'|'chat'|'object'|'spike'|'round_end'|'match_start'|'match_end'|'multikill'|'ace';
data:any; time:TimeLabel; userId?:string }
```
`event.data` 예: 킬 `{killer:{puuid,name,agent|champion,team,userId?}, victim:{...}, assists:[...], weapon:{id,name,icon}, headshot?}` ·
채팅 `{sender:{name,puuid?,userId?}, channel:'team'|'all'|'party', text, source:'api'|'ocr'|'lcu'}` ·
오브젝트 `{object:'dragon'|'baron'|'herald'|'grub'|'tower'|'inhibitor', subtype?, team, killer}` ·
라운드 종료 `{round, winner:'ally'|'enemy'|teamId, result:'Elimination'|'Bomb detonated'|..., score:{ally,enemy}}`
### MatchDetail
```ts
{ id, game, startedAt, endedAt, map:{id,name,image}, mode, queue, result:{win:boolean, score:{ally,enemy}},
players:[{puuid, name, tag, team, agent|champion:{id,name,icon}, kills, deaths, assists, score?, cs?, gold?, items?, userId?}],
rounds?:[{num, startedAt, endedAt, winner, result, score, economy:{puuid:{spent,remaining,weapon}} }], // 발로란트
goldDiff?:[{t:ms, diff:number}], // 롤
events: TimelineItem[] (kind=event), utterances: TimelineItem[] (kind=utterance),
mapTransform: {valorant:{xMultiplier,yMultiplier,xScalarToAdd,yScalarToAdd}} | {lol:{minX,minY,maxX,maxY}} }
```
## 5. 실시간 이벤트 (앱 → 사이트 서버 → 브라우저)
`{type:'utterance.created'|'utterance.updated'|'event.created'|'match.updated'|'recording.state'|'users.updated', data}`
## 6. 사이트 서버 ↔ 앱 (WebSocket `wss://gvr.tkrmagid.kr/device/ws`)
인증: 헤더 `authorization: Device <deviceId>.<deviceKey>`. 기기 키는 등록 때 한 번 받는다
(서버는 SHA-256 해시만 저장).
등록: `POST /device/register {code, name}` → `{deviceId, deviceKey}`. 코드는 사이트에서
관리자(`OWNER_DISCORD_IDS`)가 만드는 1회용 코드(10분 유효).
메시지 (JSON 텍스트 프레임, 오디오는 바이너리 프레임):
```jsonc
// 서버 → 앱
{"t":"req","id":"r1","method":"GET","path":"/api/timeline?limit=50","headers":{"range":"bytes=0-"},"user":{...},"body":null}
// 앱 → 서버
{"t":"res","id":"r1","status":200,"headers":{"content-type":"application/json"},"body":"<utf8 text>"} // 작은 응답
{"t":"res_head","id":"r2","status":206,"headers":{...}} + 바이너리 프레임들 [4바이트 id길이][id][데이터] + {"t":"res_end","id":"r2"}
{"t":"event","event":{...5장 형식...}}
{"t":"hello","name":"GAME-PC","version":"1.0.0"}
{"t":"ping","ts":...} ↔ {"t":"pong","ts":...} // 앱이 5초마다. 15초 무응답이면 서버가 오프라인 처리
```
## 7. 사이트 서버 HTTP
| Path | 설명 |
|---|---|
| `GET /auth/discord` | OAuth2 시작 (`identify guilds`) |
| `GET /auth/discord/callback` | 코드 교환 → 봇 토큰으로 `GET /guilds/{GUILD_ID}/members/{uid}` 확인 → 세션 쿠키 |
| `POST /auth/logout` | |
| `GET /auth/me` | `{user:{id,name,avatar}, isOwner}` 또는 401 |
| `GET /api/status` | `{device:{registered, online, name, lastSeen, version}, server:{version}}` (로그인 필요) |
| `/api/*` | 로그인 + 기기 온라인이면 앱으로 중계, 오프라인이면 `503 {error:'device_offline'}` |
| `WS /ws` | 브라우저용. `{type:'status',data}` + 5장 이벤트 |
| `POST /admin/registration-code` | 관리자 전용 → `{code, expiresAt}` |
| `GET /game-assets/<source>/<path>` | valorant-api.com · ddragon · cdragon 이미지 캐시 프록시 |

View File

@@ -0,0 +1,40 @@
# M0 기술 검증 결과 (2026-10-15)
개발 서버(.9, 리눅스, RTX 5050)에서 확인한 것과, 게임 PC(Windows, RTX 5070 Ti)에서 확인해야 하는 것을 나눠 적는다.
게임 PC 쪽은 앱의 **진단** 기능(설정 창 "진단" 탭, 개발용 `npm run core -- --diagnose`)으로 같은 항목을 그대로 돌린다.
## 개발 서버에서 확인함
| 항목 | 결과 | 근거 |
|---|---|---|
| 디스코드 DAVE(E2EE) 음성 연결 | ✅ 겜녹이 봇이 M&L 음성채널에 1.06초 만에 Ready, 암호화 `aead_aes256_gcm_rtpsize`, DAVE 프로토콜 v1 | `app/scripts/voice-smoke.mts` |
| TTS 녹음 안내 재생 | ✅ 연결 직후 안내 음성(Edge TTS, WebM Opus) 재생 시작 | 같은 스크립트 |
| 유저별 음성 수신 | ⏳ 말하는 사람이 있어야 확인 가능. 테스트봇을 M&L 에 초대하면 자동 시험 | `voice-smoke.mts` 가 수신 패킷을 유저별 Ogg 로 저장 |
| Ogg Opus 저장 (재인코딩 없음) | ✅ ffmpeg 로 끝까지 디코드, 길이 오차 < 50ms, 말 사이 쉼은 무음 프레임으로 채워 실제 시간과 일치 | `app/test/core.test.ts` |
| faster-whisper 한국어 STT | ✅ CPU tiny: 3.6초 음성 0.31초, "레이드 공 빠졌어…" → 사전 교정 후 "레이즈 공 빠졌어…" | `app/test/e2e-stt.test.ts`, 진단 |
| 음량 정규화 | ✅ -30dB 작은 목소리: -48.5 LUFS 측정, +24dB 보정 후 같은 문장 인식 | `worker/tests` |
| 잡음 판정 | ✅ 키보드 소리·백색 잡음·무음 모두 VAD 단계에서 `[잡음]` (Whisper 생략, 약 25ms) | `worker/tests` |
| 단어사전 교정 | ✅ 보고서 예시 문장이 정확히 교정됨 (교정 규칙 + 한글 자모 유사도) | `worker/tests/test_dictionary.py` |
| 발로란트·롤 로컬 API 처리 | ✅ 실제 API 와 같은 구조의 가짜 서버로 경기 시작→채팅→라운드→종료→상세 전 과정 통과 | `app/test/games.test.ts` |
| 파인튜닝 파이프라인 | ✅ CPU whisper-tiny 로 합성→학습→CER 비교→CTranslate2 내보내기 전 단계 통과 (≈30초) | `worker/README.md` |
| PyInstaller 패키징 | ✅ 리눅스 onedir 빌드 후 hello/load/transcribe 통과 (Windows 빌드는 M5) | `worker/gvr-worker.spec` |
## 게임 PC 에서 확인할 것 (진단 기능)
| 항목 | 진단 이름 | 확인 내용 |
|---|---|---|
| RTX 5070 Ti STT 속도·VRAM | `STT 속도` | CUDA 12.8 + cuDNN 9 DLL 로 large-v3-turbo / large-v3 float16 적재 시간, 3.6초 음성 변환 시간, VRAM |
| 발로란트 경기 감지 | `발로란트 로컬 API` | lockfile → entitlement → presence (상태·맵) |
| 롤 게임 API | `롤 게임 클라이언트 API` | 게임 중 2999 포트 응답 |
| 롤 타임라인 | `롤 클라이언트 (LCU) · 타임라인` | 최근 경기 타임라인 조회 가능 여부 → 불가면 킬 위치·골드 그래프에 공식 키 필요 |
| 채팅 OCR | `채팅 OCR (한국어)` | Windows 한국어 OCR 설치 여부, 예시 이미지 3줄 인식률 |
| 롤 로그 채팅 | `롤 로그 파일 채팅` | r3dlog 에 채팅이 남는지 → 남으면 OCR 대신 사용 |
결과는 `GVR-Data/logs/diagnostics-*.json` 에 남는다.
## 결정 사항
- 한국어 TTS 엔진: **Microsoft Edge 온라인 TTS** (무료, 한국어 음성 3종). 안내 음성은 기본 문구를 앱에 포함해 인터넷이 없어도 재생되고, 문구를 바꾸면 다시 합성해 캐시한다. 파인튜닝용 합성 음성도 같은 엔진.
- 실시간/정밀 모델: `mobiuslabsgmbh/faster-whisper-large-v3-turbo` / `Systran/faster-whisper-large-v3` (CTranslate2), float16 기본.
- CUDA 런타임: PyPI `nvidia-cublas-cu12` 12.9 + `nvidia-cudnn-cu12` 9.x Windows 휠에서 DLL 만 받아 `GVR-Data/cuda/` 에 둔다 (≈1.2GB, exe 에 넣지 않음).
- 핫워드: 상황별 묶음(발로란트·롤·일상…) 앞에 **그 경기에 나온 요원·챔피언·선수 이름 10명분**을 먼저 넣는다.

View File

@@ -0,0 +1,8 @@
{
"name": "@gvr/shared",
"version": "1.0.0",
"private": true,
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts"
}

View File

@@ -0,0 +1,2 @@
export * from './protocol.js';
export * from './time.js';

View File

@@ -0,0 +1,226 @@
// 앱 코어 · 사이트 서버 · 사이트 프런트엔드가 같이 쓰는 타입. docs/dev/ARCHITECTURE.md 4~6장.
export type GameType = 'valorant' | 'lol';
export interface TimeLabel {
/** 발로란트 "R7 · 0:42" / 롤 "21:14" / 경기 밖 "21:08:44" */
primary: string;
/** 발로란트 경기 경과 시간 "12:18" */
secondary?: string;
/** 현실 시각 (unix ms) */
real: number;
}
export interface Word {
w: string;
/** 발화 시작 기준 초 */
s: number;
e: number;
p?: number;
}
export interface User {
id: string;
name: string;
color: string;
avatar: string | null;
excluded: boolean;
riot: { puuid: string; riotId: string }[];
}
export type UtteranceStatus = 'pending' | 'realtime' | 'precise' | 'failed';
export interface UtteranceItem {
kind: 'utterance';
id: string;
ts: number;
endTs: number;
userId: string;
text: string | null;
words: Word[];
noise: boolean;
status: UtteranceStatus;
corrected: boolean;
confidence: number | null;
model: string | null;
audio: { url: string; durationMs: number; gainDb: number } | null;
game: { type: GameType; matchId: string; round?: number } | null;
time: TimeLabel;
}
export type EventType =
| 'kill'
| 'chat'
| 'object'
| 'spike'
| 'round_end'
| 'match_start'
| 'match_end'
| 'multikill'
| 'ace';
export interface PlayerRef {
puuid?: string;
name: string;
team?: string;
/** 발로란트 요원 / 롤 챔피언 */
character?: { id: string; name: string; icon: string | null };
userId?: string;
}
export interface KillData {
killer: PlayerRef | null;
victim: PlayerRef;
assists: PlayerRef[];
weapon: { id: string; name: string; icon: string | null } | null;
headshot?: boolean;
location?: { x: number; y: number } | null;
ally?: boolean;
}
export interface ChatData {
sender: PlayerRef;
channel: 'team' | 'all' | 'party' | 'system';
text: string;
source: 'api' | 'ocr' | 'lcu' | 'log';
}
export interface ObjectData {
object: 'dragon' | 'baron' | 'herald' | 'grub' | 'tower' | 'inhibitor' | 'atakhan';
subtype?: string;
team?: string;
killer?: PlayerRef | null;
ally?: boolean;
}
export interface RoundEndData {
round: number;
win: boolean;
result: string;
score: { ally: number; enemy: number };
}
export interface EventItem {
kind: 'event';
id: string;
ts: number;
game: GameType;
matchId: string;
type: EventType;
data: any;
time: TimeLabel;
userId?: string;
}
export type TimelineItem = UtteranceItem | EventItem;
export interface TimelinePage {
items: TimelineItem[];
next: string | null;
}
export interface MatchSummary {
id: string;
game: GameType;
startedAt: number;
endedAt: number | null;
map: { id: string; name: string; image: string | null };
mode: string;
win: boolean | null;
score: { ally: number; enemy: number } | null;
status: 'live' | 'pending_detail' | 'complete';
participants: string[];
}
export interface MatchPlayer {
puuid: string;
name: string;
tag?: string;
team: string;
ally: boolean;
character: { id: string; name: string; icon: string | null };
kills: number;
deaths: number;
assists: number;
score?: number;
cs?: number;
gold?: number;
level?: number;
items?: { id: number; name: string; icon: string | null }[];
rank?: string | null;
userId?: string;
}
export interface MatchRound {
num: number;
startedAt: number;
endedAt: number;
win: boolean;
result: string;
score: { ally: number; enemy: number };
economy?: Record<string, { spent: number; remaining: number; weapon?: string }>;
}
export interface MatchDetail extends MatchSummary {
players: MatchPlayer[];
rounds?: MatchRound[];
goldDiff?: { t: number; diff: number }[];
events: EventItem[];
utterances: UtteranceItem[];
mapTransform:
| { valorant: { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number } }
| { lol: { minX: number; minY: number; maxX: number; maxY: number } }
| null;
}
export interface Overview {
guild: { id: string; name: string; icon: string | null } | null;
recording: { active: boolean; channel: string | null; since: number | null; participants: string[] };
users: User[];
games: { valorant: { connected: boolean; inMatch: boolean }; lol: { connected: boolean; inMatch: boolean } };
counts: { utterances: number; matches: number };
version: string;
}
export interface UserProfile {
user: User;
stats: { talkMs: number; count: number; topWords: { w: string; n: number }[] };
matches: MatchSummary[];
}
export type LiveEvent =
| { type: 'utterance.created' | 'utterance.updated'; data: UtteranceItem }
| { type: 'event.created'; data: EventItem }
| { type: 'match.updated'; data: MatchSummary }
| { type: 'recording.state'; data: Overview['recording'] }
| { type: 'users.updated'; data: User[] };
export interface DeviceStatus {
registered: boolean;
online: boolean;
name: string | null;
lastSeen: number | null;
version: string | null;
}
export type BrowserMessage = { type: 'status'; data: { device: DeviceStatus } } | LiveEvent;
// 사이트 서버 ↔ 앱 WebSocket
export type RelayToDevice =
| {
t: 'req';
id: string;
method: string;
path: string;
headers: Record<string, string>;
user: { id: string; name: string; avatar: string | null } | null;
body: string | null;
}
| { t: 'cancel'; id: string }
| { t: 'pong'; ts: number }
| { t: 'welcome'; deviceId: string };
export type RelayFromDevice =
| { t: 'hello'; name: string; version: string }
| { t: 'ping'; ts: number }
| { t: 'res'; id: string; status: number; headers: Record<string, string>; body: string | null }
| { t: 'res_head'; id: string; status: number; headers: Record<string, string> }
| { t: 'res_end'; id: string }
| { t: 'event'; event: LiveEvent };

View File

@@ -0,0 +1,16 @@
/** ms → "m:ss" (1시간 넘으면 "h:mm:ss") */
export function fmtClock(ms: number): string {
const neg = ms < 0;
let s = Math.floor(Math.abs(ms) / 1000);
const h = Math.floor(s / 3600);
s -= h * 3600;
const m = Math.floor(s / 60);
s -= m * 60;
const body = h > 0 ? `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}` : `${m}:${String(s).padStart(2, '0')}`;
return neg ? `-${body}` : body;
}
/** 현실 시각 → "HH:MM:SS" (Asia/Seoul) */
export function fmtReal(ts: number, tz = 'Asia/Seoul'): string {
return new Intl.DateTimeFormat('ko-KR', { timeZone: tz, hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(ts);
}

136
tools/gen-dictionary.mjs Normal file
View File

@@ -0,0 +1,136 @@
#!/usr/bin/env node
// 기본 단어사전 생성기. 공식 게임 데이터(발로란트: valorant-api.com, 롤: Riot Data Dragon)의 한국어 이름과
// 직접 정리한 단어 묶음을 합쳐 app/resources/dictionary/*.json 으로 쓴다.
// node tools/gen-dictionary.mjs
// 게임 패치로 요원·챔피언이 늘면 다시 돌리면 된다. 앱도 실행 중에 같은 소스로 사전을 갱신한다(dict/update.ts).
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const OUT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'app', 'resources', 'dictionary');
fs.mkdirSync(OUT, { recursive: true });
const j = async (url) => {
const r = await fetch(url);
if (!r.ok) throw new Error(`${url} ${r.status}`);
return r.json();
};
const uniq = (a) => [...new Set(a.map((s) => s.trim()).filter(Boolean))];
// ------------------------------------------------------------------ 발로란트
async function valorant() {
const agents = (await j('https://valorant-api.com/v1/agents?language=ko-KR&isPlayableCharacter=true')).data;
const maps = (await j('https://valorant-api.com/v1/maps?language=ko-KR')).data;
const weapons = (await j('https://valorant-api.com/v1/weapons?language=ko-KR')).data;
// 순서가 우선순위다 (핫워드는 앞쪽부터 최대 60개): 요원 → 맵 → 무기 → 용어 → 스킬
const words = [];
const abilities = [];
for (const a of agents) {
words.push(a.displayName.replace('/', ''));
for (const ab of a.abilities || []) if (ab.displayName) abilities.push(ab.displayName);
}
for (const m of maps) if (m.tacticalDescription) words.push(m.displayName);
for (const w of weapons) words.push(w.displayName);
const callouts = [];
for (const m of maps) for (const c of m.callouts || []) callouts.push(c.regionName);
words.push(
...'A사이트 B사이트 C사이트 미드 헤븐 로비 메인 롱 숏 링크 마켓 개구멍 문 계단 창문 철문 쇼트 엘보 탑 백사이트 지붕 하수구 텔레포터 로프 파이프 팔레트 지옥 가든 트리 박스 기둥 도어 나무 정원 체인 다리'.split(' '),
...'스파이크 설치 해체 디퓨즈 해체기 에코 이코 풀바이 세이브 하프바이 포스바이 오퍼 오퍼레이터 밴달 팬텀 셰리프 고스트 클래식 스펙터 저지 마셜 아웃로 원탭 헤드 헤드샷 에이스 클러치 로테 로테이션 리테이크 엔트리 트레이드 플래시 섬광 연막 스모크 몰리 화염 궁 궁극기 오브 크레딧 스파이크 소리 발소리 걸었어 걷는다 러시 패스트 디폴트 스택 백업 프리파이어 원웨이 스킬 장전 리로드 피 체력 실드 방어구 프리 라운드 피스톨 라운드 투킬 쓰리킬 포킬 첫킬 퍼블 매치포인트 연장전 정규 경쟁전 신속플레이 스파이크러시 데스매치 팀데스매치 언레이티드'.split(
' ',
),
);
words.push(...abilities);
return { valorant: uniq(words), valorant_callouts: uniq(callouts) };
}
// ------------------------------------------------------------------ 롤
async function lol() {
const v = (await j('https://ddragon.leagueoflegends.com/api/versions.json'))[0];
const champs = (await j(`https://ddragon.leagueoflegends.com/cdn/${v}/data/ko_KR/championFull.json`)).data;
const items = (await j(`https://ddragon.leagueoflegends.com/cdn/${v}/data/ko_KR/item.json`)).data;
const spells = (await j(`https://ddragon.leagueoflegends.com/cdn/${v}/data/ko_KR/summoner.json`)).data;
// 순서: 오브젝트·용어 → 소환사 주문 → 챔피언 → 아이템 (경기 중에는 그 경기 챔피언 10명이 따로 맨 앞에 들어간다)
const words = [];
const champNames = [];
const skills = [];
for (const c of Object.values(champs)) {
champNames.push(c.name);
for (const sp of c.spells || []) skills.push(sp.name);
if (c.passive?.name) skills.push(c.passive.name);
}
words.push(
...'바론 드래곤 용 장로 장로드래곤 전령 협곡의전령 유충 공허유충 아타칸 억제기 억제기 포탑 타워 넥서스 쌍둥이타워 미니언 슈퍼미니언 대포미니언 정글 탑 미드 바텀 봇 서폿 서포터 원딜 정글러 미드라이너 탑라이너 갱 갱킹 백도어 텔 텔포 점멸 플 강타 점화 탈진 정화 회복 유체화 방어막 와드 제어와드 핑와 시야 딜교 라인전 한타 스플릿 운영 오브젝트 버프 블루 레드 칼날부리 늑대 두꺼비 돌거북 바위게 스카이 다이브 포킹 이니시 이니시에이팅 백 귀환 리콜 킬각 킬캐치 솔킬 퍼블 더블킬 트리플킬 쿼드라킬 펜타킬 에이스 서렌 항복 하이브리드 cs 씨에스 골드 템 아이템 코어템 신화템 전설템 장화 신발 포션 물약 엘릭서 스펠 쿨 궁 궁극기 스킬샷 논타겟 cc 씨씨 스턴 에어본 넉백 속박 침묵'.split(
' ',
),
);
for (const s of Object.values(spells)) words.push(s.name);
const itemNames = [];
for (const it of Object.values(items)) {
if (it.gold?.purchasable && it.gold.total >= 2000 && it.maps?.['11']) itemNames.push(it.name);
}
words.push(...champNames, ...itemNames);
return { lol: uniq(words), lol_skills: uniq(skills).filter((w) => w.length <= 12), _ddragon: v };
}
// ------------------------------------------------------------------ 직접 정리한 묶음
const game = `킬 데스 어시 어시스트 힐 쿨 쿨타임 궁 빽 백 라인 랭겜 랭크 티어 큐 큐돌리자 큐잡혀 트롤 던짐 던졌다 캐리 버스 하드캐리 멘탈 멘붕 탈주 닷지 픽 밴 챔폭 듀오 트리오 파티 솔랭 자랭 일반겜 칼바람 증강 패치 너프 버프 메타 OP 사기 개사기 핵 매크로 핑 렉 프레임 프레임드랍 서버 재접 재시작 로딩 승리 패배 이겼다 졌다 연승 연패 승급 강등 아이언 브론즈 실버 골드 플래티넘 플레 에메랄드 다이아 다이아몬드 마스터 그마 그랜드마스터 챌린저 레디언트 불멸 초월자 디스코드 디코 마이크 음소거 뮤트 보이스 헤드셋 키보드 마우스 모니터 게임 한판 한겜 한판더 마지막판 다음판 이번판 판수 전적 MVP 에이스 하이라이트 리플레이 클립 녹화`;
const daily = `레전드 미쳤다 미쳤네 개웃기네 웃기네 인정 에바 에반데 킹받네 킹받아 갓생 존맛 존맛탱 퇴근각 실화냐 ㄹㅇ 리얼 진짜 대박 헐 와 아니 근데 그니까 맞아 아 잠깐만 잠깐 기다려 빨리 천천히 오케이 오키 굿 나이스 나이스샷 고마워 미안 ㅇㅋ 배고파 졸려 피곤해 밥 저녁 점심 야식 치킨 피자 라면 편의점 배달 배민 쿠팡 카톡 인스타 유튜브 넷플릭스 트위치 치지직 숏츠 알바 출근 퇴근 주말 내일 오늘 어제 방금 아까 이따 나중에 지금 몇시 새벽 아침 커피 아아 술 소주 맥주 노래방 피시방 PC방 집 방 엄마 아빠 동생 형 누나 언니 오빠 친구`;
const university = `과제 팀플 중간고사 기말 기말고사 시험 퀴즈 휴강 보강 학식 에타 에브리타임 종강 개강 학점 학기 수강신청 정정기간 동아리 엠티 MT 오티 OT 과대 과팀 조교 교수님 교수 강의 수업 출석 출첵 레포트 리포트 발표 PPT 피피티 졸업 졸작 졸업작품 전공 교양 복전 부전 휴학 복학 군대 전역 입대 기숙사 긱사 자취 통학 도서관 열람실 공강 시간표 장학금 등록금 성적 재수강 F 에이쁠 A+ 과탑 족보 캡스톤 인턴 취준 취업 자소서 면접 토익 학회 축제 대동제`;
const slang20s = `갑분싸 개꿀 꿀잼 노잼 핵노잼 존잼 꿀팁 ㅈㄴ 졸라 개 핵 쩐다 쩔어 지린다 지렸다 오지네 오진다 미친 레게노 킹 갓 국룰 찐 찐이다 찐텐 텐션 억텐 플렉스 TMI 투머치 별다줄 알잘딱깔센 내돈내산 갓벽 킹정 ㅇㅈ 반박불가 꾸안꾸 혼코노 스불재 오히려좋아 가보자고 가즈아 어쩔티비 저쩔티비 킹받 너무해 무야호 중꺾마 웅앵 손절 읽씹 안읽씹 칼답 퇴사각 월급루팡 탕진잼 홀리몰리 띵작 띵곡 실화 느좋 럭키비키 MBTI 엠비티아이 대문자 극I 극E 파워`;
const v = await valorant();
const l = await lol();
const packs = {
valorant: { label: '발로란트', words: v.valorant },
valorant_callouts: { label: '발로란트 콜아웃', words: v.valorant_callouts },
lol: { label: '리그 오브 레전드', words: l.lol },
lol_skills: { label: '롤 스킬 이름', words: l.lol_skills },
game: { label: '게임 공통', words: uniq(game.split(/\s+/)) },
daily: { label: '일상', words: uniq(daily.split(/\s+/)) },
university: { label: '대학생', words: uniq(university.split(/\s+/)) },
slang20s: { label: '20대 말투', words: uniq(slang20s.split(/\s+/)) },
};
// 교정 규칙: 사전 없이 자주 틀리는 표기 (from → to). 자모 유사도 교정과 별개로 정확히 바꾼다.
const corrections = [
['레이저', '레이즈'],
['비 싸이트', 'B 사이트'],
['비싸이트', 'B사이트'],
['에이 싸이트', 'A 사이트'],
['에이싸이트', 'A사이트'],
['씨 싸이트', 'C 사이트'],
['비 사이트', 'B 사이트'],
['에이 사이트', 'A 사이트'],
['로태', '로테'],
['오퍼래이터', '오퍼레이터'],
['반달', '밴달'],
['펜텀', '팬텀'],
['쉐리프', '셰리프'],
['세리프', '셰리프'],
['스파이크 설치했어', '스파이크 설치했어'],
['디퓨저', '디퓨즈'],
['킬 조이', '킬조이'],
['브림 스톤', '브림스톤'],
['아스트로', '아스트라'],
['클로버', '클로브'],
['바론 둥지', '바론 둥지'],
['드레곤', '드래곤'],
['드라곤', '드래곤'],
['협곡에 전령', '협곡의 전령'],
['억재기', '억제기'],
['점명', '점멸'],
['텔 포', '텔포'],
['와드 박아', '와드 박아'],
['이즈리얼', '이즈리얼'],
['리신', '리 신'],
['쓰레시', '쓰레쉬'],
['르블랑', '르블랑'],
['에타', '에타'],
['팀 플', '팀플'],
].filter(([a, b]) => a !== b);
const meta = { generatedAt: new Date().toISOString(), ddragon: l._ddragon, source: ['valorant-api.com (ko-KR)', 'ddragon ko_KR', 'curated'] };
fs.writeFileSync(path.join(OUT, 'packs.json'), JSON.stringify({ meta, packs }, null, 1));
fs.writeFileSync(path.join(OUT, 'corrections.json'), JSON.stringify(corrections.map(([from, to]) => ({ from, to })), null, 1));
const total = Object.values(packs).reduce((n, p) => n + p.words.length, 0);
console.log(`packs: ${Object.entries(packs).map(([k, p]) => `${k}=${p.words.length}`).join(' ')} total=${total}, corrections=${corrections.length}`);

8
worker/.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
.venv/
.venv-ft/
__pycache__/
*.pyc
.pytest_cache/
.pytest-tmp/
build/
dist/

94
worker/README.md Normal file
View File

@@ -0,0 +1,94 @@
# gvr-worker (겜녹이 STT 워커)
앱 코어(Electron/Node)가 자식 프로세스로 띄우는 Python 워커. 하는 일:
- 발화 Ogg Opus → 음량 정규화(BS.1770 LUFS + 리미터) → Silero VAD → faster-whisper(한국어 고정, 핫워드, 단어별 시각)
- 잡음 판정 4단계(VAD / no_speech / 환각 문구 / 반복) → `noise`, `noise_reason`
- 교정 사전(정확 일치) + 한글 자모 유사도 교정 (단어 시각 유지)
- GPU 감지(NVML → nvidia-smi)와 VRAM 별 모델 추천, 모델·CUDA 런타임 다운로드(이어받기, 해시 검사, 진행률)
- 롤 채팅 화면 OCR(Windows.Media.Ocr), r3dlog 채팅 확인
- 파인튜닝(별도 환경): TTS 합성 → LoRA → CER 비교 → CTranslate2 내보내기
## 프로토콜
`docs/dev/ARCHITECTURE.md` 1장이 계약이다. stdin/stdout JSON Lines, stdout 은 프로토콜 메시지만, 로그는 stderr.
계약 외 추가 사항:
| op | 설명 |
|---|---|
| `r3dlog_check {logs_dir}` | `{found_chat, file, sample:[...]}` |
| `r3dlog_read {logs_dir, since_ms}` | 최신 `*_r3dlog.txt`(since_ms 이후 수정) 전체 채팅 → `{file, lines:[{game_time, game_time_s, channel, sender, champion, message}]}` |
| `train {python?, args:{...}}` | 파인튜닝 환경의 파이썬(`python` 또는 `GVR_FINETUNE_PYTHON`)으로 `finetune/run.py` 실행. `args` 키는 `--kebab-case` 옵션으로 넘어감. 진행은 `progress` 이벤트(`stage`,`step`,`total`)로 중계 |
- `load` 는 `device` 생략 시 GPU 있으면 cuda/float16, 없으면 cpu/int8. cuda 요청인데 GPU 가 없으면 cpu 로 바꾸고 `"fallback":"no_gpu"`. `cpu_threads` 선택.
- `models` 응답에 `loaded`(슬롯별 적재 상태)와 파인튜닝 모델(`<이름>-ft-<날짜>`, `meta`=gvr-model.json) 이 함께 나온다.
- `ocr_start` 중 창 상태가 바뀌면 `{"event":"ocr_status","state":"window_not_found"|"capturing"|"error"}`.
- `ocr_line.parsed` 에 `game_time_s`(초, 없으면 null) 포함. 시각 없는 줄은 dedupe 키에 시각이 없어 같은 내용 반복이 한 번만 잡힌다 → 게임 옵션에서 채팅 타임스탬프를 켜도록 안내.
- 잡음이면 `text=null`, `words=[]`, `raw_text` 는 모델 출력(① VAD 단계에서 걸리면 Whisper 를 돌리지 않으므로 null).
- 동시성: 같은 슬롯의 load/unload/transcribe 는 순서대로, realtime/precise 는 서로 병렬. download·train·ocr_image·r3dlog_read 는 별도 스레드.
- 주요 오류 코드: `bad_json` `bad_request` `unknown_op` `model_not_loaded` `model_not_installed` `unknown_model` `file_not_found` `decode_failed` `transcribe_failed` `load_failed` `cuda_runtime_missing` `disk_full` `network` `verify_failed` `busy` `ocr_unavailable` `ocr_lang_missing` `finetune_env_missing` `train_failed` `internal`.
환경변수: `GVR_DATA_DIR`, `GVR_MODELS_DIR`(선택), `GVR_FINETUNE_PYTHON`(선택), `GVR_LOG_LEVEL`(기본 INFO).
## 개발 환경 (리눅스)
```bash
cd worker
uv venv --python 3.11 .venv
uv pip install --python .venv/bin/python -r requirements-dev.txt
.venv/bin/python -m gvr_worker # stdin 으로 JSON 한 줄씩
```
## 테스트
```bash
cd worker && .venv/bin/python -m pytest -q
```
- 모델은 tiny(CPU, int8). `~/.cache/huggingface` 에 `Systran/faster-whisper-tiny` 가 있으면 링크하고, 없으면 테스트가 `download` op 로 받는다.
- 픽스처(`tests/fixtures/*.ogg`, 48kHz mono Opus)는 `tests/make_fixtures.py` 로 다시 만들 수 있다 (edge-tts + ffmpeg, 인터넷 필요).
## 패키징 (Windows)
```bat
py -3.11 -m venv .venv && .venv\Scripts\pip install -r requirements-dev.txt
.venv\Scripts\pyinstaller gvr-worker.spec REM → dist\gvr-worker\gvr-worker.exe (onedir)
```
콘솔 앱이며 부모가 `windowsHide` 로 띄운다. faster-whisper VAD onnx, ctranslate2/onnxruntime/av DLL, pywinrt 가 포함되고
`gvr_worker/finetune/*.py` 는 데이터 파일로만 들어간다 (torch 등은 exe 에 넣지 않음).
## Windows CUDA 메모
- ctranslate2 4.8.x Windows 휠은 CUDA 12.8 + cuDNN 9 로 빌드되어 RTX 50(Blackwell, sm_120)을 지원한다. 그래픽 드라이버는 CUDA 12.8 이상을 지원해야 한다(R570+).
- cuBLAS/cuDNN DLL 은 exe 에 넣지 않고 첫 실행 때 `download {target:"cuda_runtime"}` 으로 PyPI 의 `nvidia-cublas-cu12`, `nvidia-cudnn-cu12` win_amd64 휠(약 1.2GB)을 받아 `bin/*.dll` 만 `GVR-Data/cuda/` 에 푼다(sha256 검사). 워커는 시작할 때 이 폴더를 `os.add_dll_directory` + PATH 앞에 넣으므로, 받은 뒤에는 워커를 재시작한다(`restart_required:true`).
- 기본 연산 정밀도는 float16. RTX 50 에서 int8 계열이 cuBLAS 오류를 낸 보고가 있어 int8 은 VRAM 이 빠듯할 때만 추천하고 경고를 붙인다.
- 리눅스에서 `cuda_runtime` 다운로드는 `skipped:true` 로 끝난다.
## 파인튜닝 (M8, 별도 환경)
```bash
uv venv --python 3.11 .venv-ft
uv pip install --python .venv-ft/bin/python torch --index-url https://download.pytorch.org/whl/cu128 # CPU: /whl/cpu
uv pip install --python .venv-ft/bin/python -r gvr_worker/finetune/requirements.txt
.venv-ft/bin/python gvr_worker/finetune/run.py --data-dir GVR-Data \
--dictionary words.txt --sentences sentences.txt --user-corrections corrections.jsonl
```
- 단계: `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`).
- `adopt = cer_after < cer_before` 일 때만 내보낸다(`--export-always` 로 강제). 앱은 `models` 의 `meta` 를 보고 교체/되돌리기.
- 중지 파일(기본 `GVR-Data/finetune.stop`)이 있으면 시작하지 않고, 학습 중 생기면 어댑터를 저장하고 `stopped:true` 로 끝난다.
- 사용자 교정 jsonl: `{"audio":"<training/xxx.ogg>","text":"<고친 문장>"}`.
CPU 스모크 테스트(openai/whisper-tiny, 합성 30개, `--max-steps 3`)는 약 30초에 전체 단계와 CT2 내보내기까지 돈다.
## 알려진 한계
- 화면 OCR 과 Windows OCR 경로는 리눅스에서 실행 검증하지 못했다(파싱·중복 제거만 단위 테스트). 실제 게임 PC 에서 확인 필요.
'전체 화면(독점)' 모드는 캡처가 검게 나올 수 있어 '테두리 없음' 창 모드를 권장한다.
- r3dlog 채팅 형식은 2024년 이전 보고 기준 추정이다. `r3dlog_check` 로 실제 로그를 확인해야 한다.
- 잡음 판정 기준값은 추정치다. 실제 녹음으로 `noise_sensitivity` 와 `noise.py` 임계값을 조정해야 한다.
- 정규화 음량은 16kHz 로 디코딩한 신호에서 잰다(48k 원본과 소폭 차이 가능).
- CUDA 경로(GPU 추론, cuDNN/cuBLAS DLL 다운로드·로딩)는 이 개발 머신에서 실행하지 않았다(M0 에서 게임 PC 로 확인).

50
worker/gvr-worker.spec Normal file
View File

@@ -0,0 +1,50 @@
# -*- mode: python ; coding: utf-8 -*-
# PyInstaller onedir 빌드: pyinstaller gvr-worker.spec → dist/gvr-worker/gvr-worker.exe
# 콘솔 앱이지만 부모(Electron)가 windowsHide 로 띄우므로 창은 보이지 않는다.
import sys
from PyInstaller.utils.hooks import collect_data_files, collect_dynamic_libs, collect_submodules
datas = []
binaries = []
hiddenimports = []
# faster-whisper: Silero VAD onnx (assets/)
datas += collect_data_files("faster_whisper")
# CTranslate2 / onnxruntime / PyAV 네이티브 라이브러리
for pkg in ("ctranslate2", "onnxruntime", "av"):
binaries += collect_dynamic_libs(pkg)
hiddenimports += collect_submodules("av")
hiddenimports += ["pyloudnorm", "scipy.signal", "scipy.ndimage", "pynvml", "mss"]
# Windows OCR (pywinrt) — 윈도우에서만
if sys.platform == "win32":
hiddenimports += collect_submodules("winrt")
binaries += collect_dynamic_libs("winrt")
hiddenimports += ["PIL.Image"]
# 파인튜닝 스크립트는 별도 파이썬 환경에서 돌리므로 모듈로 묶지 않고 파일로만 넣는다
datas += [("gvr_worker/finetune/*.py", "gvr_worker/finetune"),
("gvr_worker/finetune/requirements.txt", "gvr_worker/finetune")]
a = Analysis(
["run_worker.py"],
pathex=["."],
binaries=binaries,
datas=datas,
hiddenimports=hiddenimports,
excludes=["gvr_worker.finetune", "torch", "transformers", "peft", "tkinter", "matplotlib", "IPython",
"pytest"],
noarchive=False,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name="gvr-worker",
console=True,
upx=False,
)
coll = COLLECT(exe, a.binaries, a.datas, strip=False, upx=False, name="gvr-worker")

View File

@@ -0,0 +1,3 @@
"""겜녹이(GVR) STT 워커. 앱 코어와 stdin/stdout JSON Lines 로 통신한다 (docs/dev/ARCHITECTURE.md 1장)."""
__version__ = "1.0.0"

View File

@@ -0,0 +1,4 @@
from gvr_worker.main import main
if __name__ == "__main__":
main()

111
worker/gvr_worker/audio.py Normal file
View File

@@ -0,0 +1,111 @@
"""오디오 디코딩, 라우드니스 정규화(ITU-R BS.1770), 피크 리미터, 선택적 잡음 억제."""
from __future__ import annotations
import logging
from dataclasses import dataclass
import numpy as np
log = logging.getLogger(__name__)
SR = 16000
MIN_GAIN_DB = -12.0
MAX_GAIN_DB = 24.0
CEILING_DBFS = -1.0
SHORT_S = 0.5
SILENCE_LUFS = -70.0
@dataclass
class Prepared:
audio: np.ndarray # STT 입력 (정규화·리미터·선택적 잡음 억제 후), 16k mono float32
duration_s: float
lufs: float | None # 게인 계산에 쓴 음량 (측정값, 짧으면 유저 프로필 값)
gain_db: float # 재생 시 원본에 적용할 게인
def decode(path: str) -> np.ndarray:
from faster_whisper import decode_audio
return decode_audio(path, sampling_rate=SR).astype(np.float32, copy=False)
def measure_lufs(audio: np.ndarray, sr: int = SR) -> float | None:
"""BS.1770 게이팅 적분 음량. 0.4초 미만이거나 무음이면 None."""
if audio.size < int(0.4 * sr) + 1:
return None
import pyloudnorm
try:
lufs = float(pyloudnorm.Meter(sr).integrated_loudness(audio.astype(np.float64)))
except ValueError:
return None
if not np.isfinite(lufs) or lufs < SILENCE_LUFS:
return None
return lufs
def limit(audio: np.ndarray, ceiling_dbfs: float = CEILING_DBFS, sr: int = SR) -> np.ndarray:
"""룩어헤드 피크 리미터. 결과 피크는 항상 ceiling 이하."""
ceiling = 10 ** (ceiling_dbfs / 20)
peak = float(np.max(np.abs(audio))) if audio.size else 0.0
if peak <= ceiling:
return audio
from scipy.ndimage import minimum_filter1d, uniform_filter1d
need = np.minimum(1.0, ceiling / np.maximum(np.abs(audio), 1e-9))
w = max(1, int(0.005 * sr)) # 5ms
# 최소값 필터 창(2w+1)이 평균 창(w)보다 넓으므로 평활 게인 <= 필요 게인이 보장된다
g = uniform_filter1d(minimum_filter1d(need, size=2 * w + 1), size=w)
return np.clip(audio * g, -ceiling, ceiling).astype(np.float32)
def denoise(audio: np.ndarray, sr: int = SR) -> np.ndarray:
"""간단한 스펙트럼 게이팅. 가장 조용한 프레임들로 잡음 스펙트럼을 추정해 그 아래를 감쇠한다."""
from scipy.signal import istft, stft
if audio.size < sr // 4:
return audio
_, _, z = stft(audio, fs=sr, nperseg=512, noverlap=384)
mag = np.abs(z)
energy = mag.mean(axis=0)
quiet = mag[:, energy <= np.quantile(energy, 0.1)]
noise = quiet.mean(axis=1, keepdims=True) if quiet.size else mag.min(axis=1, keepdims=True)
floor = 10 ** (-12 / 20)
mask = np.clip((mag - 1.5 * noise) / np.maximum(mag, 1e-9), floor, 1.0)
# 시간축 평활로 음악성 잡음 줄이기
from scipy.ndimage import uniform_filter1d
mask = uniform_filter1d(mask, size=3, axis=1)
_, out = istft(z * mask, fs=sr, nperseg=512, noverlap=384)
return out[: audio.size].astype(np.float32)
def prepare(
path: str,
target_lufs: float = -18.0,
profile_lufs: float | None = None,
use_denoise: bool = False,
) -> Prepared:
audio = decode(path)
duration = audio.size / SR
measured = measure_lufs(audio) if duration >= SHORT_S else None
lufs = measured if measured is not None else profile_lufs
if lufs is None and audio.size:
# 짧고 프로필도 없음: RMS 로 대충 추정 (완전 무음이면 게인 0)
rms = float(np.sqrt(np.mean(np.square(audio, dtype=np.float64))))
lufs = 20 * np.log10(rms) - 0.691 if rms > 1e-6 else None
if lufs is not None and lufs < SILENCE_LUFS:
lufs = None
gain_db = 0.0 if lufs is None else float(np.clip(target_lufs - lufs, MIN_GAIN_DB, MAX_GAIN_DB))
out = audio * np.float32(10 ** (gain_db / 20)) if gain_db else audio
if use_denoise:
out = denoise(out)
out = limit(out)
return Prepared(
audio=out.astype(np.float32, copy=False),
duration_s=round(duration, 3),
lufs=None if lufs is None else round(float(lufs), 2),
gain_db=round(gain_db, 2),
)

View File

@@ -0,0 +1,228 @@
"""후처리 교정: (a) 교정 사전 정확 일치 치환 → (b) 한글 자모 유사도로 사전 단어에 맞추기.
단어 타임스탬프를 유지하도록 Whisper 단어 목록(words) 단위로 고친다.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any, Iterable
# --- 자모 분해 ---------------------------------------------------------------
_L = "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ"
_V = ["ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅗㅏ", "ㅗㅐ", "ㅗㅣ", "ㅛ", "ㅜ", "ㅜㅓ", "ㅜㅔ", "ㅜㅣ",
"ㅠ", "ㅡ", "ㅡㅣ", "ㅣ"]
_T = ["", "ㄱ", "ㄲ", "ㄱㅅ", "ㄴ", "ㄴㅈ", "ㄴㅎ", "ㄷ", "ㄹ", "ㄹㄱ", "ㄹㅁ", "ㄹㅂ", "ㄹㅅ", "ㄹㅌ", "ㄹㅍ", "ㄹㅎ",
"ㅁ", "ㅂ", "ㅂㅅ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"]
def jamo(text: str) -> str:
"""완성형 한글을 자모로 분해 (겹모음·겹받침도 쪼갬). 그 외 문자는 소문자로 그대로."""
out = []
for ch in text:
code = ord(ch) - 0xAC00
if 0 <= code < 11172:
out.append(_L[code // 588])
out.append(_V[(code % 588) // 28])
out.append(_T[code % 28])
else:
out.append(ch.lower())
return "".join(out)
def _is_hangul(ch: str) -> bool:
return 0xAC00 <= ord(ch) <= 0xD7A3
# 발음이 비슷해 자주 헷갈리는 자모쌍은 치환 비용을 낮춘다
_SIMILAR: dict[frozenset[str], float] = {
frozenset(p): c
for p, c in [
(("ㅐ", "ㅔ"), 0.2), (("ㅒ", "ㅖ"), 0.2), (("ㅓ", "ㅗ"), 0.6), (("ㅓ", "ㅡ"), 0.5), (("ㅜ", "ㅡ"), 0.5),
(("ㅗ", "ㅜ"), 0.6), (("ㅕ", "ㅛ"), 0.6), (("ㅑ", "ㅏ"), 0.6), (("ㅣ", "ㅡ"), 0.6),
(("ㄱ", "ㄲ"), 0.4), (("ㄱ", "ㅋ"), 0.4), (("ㄷ", "ㄸ"), 0.4), (("ㄷ", "ㅌ"), 0.4), (("ㅂ", "ㅃ"), 0.4),
(("ㅂ", "ㅍ"), 0.4), (("ㅅ", "ㅆ"), 0.4), (("ㅈ", "ㅉ"), 0.4), (("ㅈ", "ㅊ"), 0.4), (("ㄴ", "ㄹ"), 0.6),
(("ㄴ", "ㅇ"), 0.6), (("ㅁ", "ㅂ"), 0.6),
]
}
def _sub_cost(a: str, b: str) -> float:
if a == b:
return 0.0
return _SIMILAR.get(frozenset((a, b)), 1.0)
def jamo_similarity(a: str, b: str) -> float:
"""가중 레벤슈타인 거리로 계산한 자모 유사도 (0~1)."""
ja, jb = jamo(a), jamo(b)
if not ja or not jb:
return 0.0
prev = [float(j) for j in range(len(jb) + 1)]
for i, ca in enumerate(ja, 1):
cur = [float(i)] + [0.0] * len(jb)
for j, cb in enumerate(jb, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + _sub_cost(ca, cb))
prev = cur
return 1.0 - prev[-1] / max(len(ja), len(jb))
# --- 토큰 처리 ---------------------------------------------------------------
PARTICLES = sorted(
["을", "를", "이", "가", "은", "는", "도", "에", "에서", "으로", "로", "한테", "랑", "이랑", "요", "의", "만",
"에게", "까지", "부터", "처럼", "보다", "하고", "이야", "야", "이요"],
key=len, reverse=True,
)
# 자모 교정 대상에서 빼는 아주 흔한 단어 (오교정 방지)
COMMON_WORDS = frozenset(
"""나 너 저 제 내 네 우리 너희 저희 그 이 저거 이거 그거 여기 거기 저기 지금 빨리 천천히 진짜 정말 아니 아니야 그래
그래서 근데 그런데 그리고 하지만 왜 뭐 뭐야 어디 언제 누구 어떻게 이제 아직 다시 같이 먼저 나중 오늘 내일 어제
사람 시간 하나 둘 셋 많이 조금 좀 다 잘 못 안 더 덜 가자 하자 해 해라 해줘 봐 보자 와 와라 가 가라 있어 없어
했어 됐어 된다 했다 좋아 싫어 맞아 알았어 몰라 괜찮아 미안 고마워 감사 대박 레전드 이번 다음 저번 처음 마지막
왼쪽 오른쪽 위 아래 앞 뒤 옆 안쪽 바깥 하나만 진짜로 계속 그냥 일단 이미 혹시 아마 너무 엄청 완전""".split()
)
_PUNCT_RE = re.compile(r"^([\"'“‘(\[{]*)(.*?)([.,!?…~\"'”’)\]}:;]*)$", re.S)
@dataclass
class Token:
text: str # 앞뒤 공백 없는 단어 (문장부호 포함)
lead: str = " " # 원래 앞 공백 (텍스트 재조립용)
s: float | None = None
e: float | None = None
p: float | None = None
locked: bool = False # 교정 사전으로 이미 바뀐 단어
extra: dict[str, Any] = field(default_factory=dict)
def _split_punct(word: str) -> tuple[str, str, str]:
m = _PUNCT_RE.match(word)
return (m.group(1), m.group(2), m.group(3)) if m else ("", word, "")
def _strip_particle(core: str) -> tuple[str, str]:
for p in PARTICLES:
if core.endswith(p) and len(core) - len(p) >= 2:
return core[: -len(p)], p
return core, ""
@dataclass
class Corrector:
corrections: list[tuple[str, str]]
dictionary: list[str]
threshold: float = 0.8
@classmethod
def from_request(
cls, corrections: Iterable[dict[str, Any]] | None, dictionary: Iterable[str] | None, threshold: float = 0.8
) -> "Corrector":
pairs = []
for c in corrections or []:
if isinstance(c, dict) and isinstance(c.get("from"), str) and isinstance(c.get("to"), str):
f = " ".join(c["from"].split())
if f:
pairs.append((f, c["to"].strip()))
pairs.sort(key=lambda x: len(x[0]), reverse=True) # 긴 것 먼저
words = [w.strip() for w in (dictionary or []) if isinstance(w, str) and w.strip()]
return cls(pairs, words, threshold)
def __post_init__(self) -> None:
self._dict_set = {w for w in self.dictionary}
self._targets = {to for _, to in self.corrections}
# 한 단어로 된 한글 사전 단어만 자모 교정 후보 (2음절 이상)
self._candidates = [
w for w in dict.fromkeys(self.dictionary)
if " " not in w and len(w) >= 2 and any(_is_hangul(c) for c in w)
]
# (a) 교정 사전 -----------------------------------------------------------
def _apply_corrections(self, toks: list[Token]) -> list[Token]:
for src, dst in self.corrections:
parts = src.split(" ")
n = len(parts)
i = 0
while i + n <= len(toks):
window = toks[i : i + n]
if any(t.locked for t in window):
i += 1
continue
cores = [_split_punct(t.text) for t in window]
ok = all(cores[k][1] == parts[k] for k in range(n - 1))
last_pre, last_core, last_post = cores[-1]
suffix = ""
if ok and last_core != parts[-1]:
stem, part = _strip_particle(last_core)
if stem == parts[-1]:
suffix = part
else:
ok = False
if not ok:
i += 1
continue
first = window[0]
merged = Token(
text=cores[0][0] + dst + suffix + last_post,
lead=first.lead,
s=first.s,
e=window[-1].e,
p=min((t.p for t in window if t.p is not None), default=None),
locked=True,
)
toks[i : i + n] = [merged]
i += 1
return toks
# (b) 자모 유사도 ---------------------------------------------------------
def _best_match(self, core: str) -> str | None:
if core in self._dict_set or core in self._targets or core in COMMON_WORDS:
return None
if len(core) < 2 or not all(_is_hangul(c) for c in core):
return None
best, best_sim = None, self.threshold
for w in self._candidates:
if abs(len(w) - len(core)) > 1:
continue
sim = jamo_similarity(core, w)
if sim >= best_sim and (best is None or sim > best_sim):
best, best_sim = w, sim
return best
def _apply_jamo(self, toks: list[Token]) -> None:
if not self._candidates:
return
for t in toks:
if t.locked:
continue
pre, core, post = _split_punct(t.text)
if not core:
continue
repl = self._best_match(core)
suffix = ""
if repl is None:
stem, part = _strip_particle(core)
if part and stem not in self._dict_set:
repl = self._best_match(stem)
suffix = part
if repl is not None:
t.text = pre + repl + suffix + post
def correct_tokens(self, toks: list[Token]) -> list[Token]:
toks = self._apply_corrections(toks)
self._apply_jamo(toks)
return toks
# 공개 API ----------------------------------------------------------------
def correct_text(self, text: str) -> str:
toks = [Token(w) for w in text.split()]
return " ".join(t.text for t in self.correct_tokens(toks))
def correct_words(self, words: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]:
"""words: [{"w","s","e","p","lead"}] → (교정된 텍스트, 교정된 words)."""
toks = [Token(w["w"], w.get("lead", " "), w.get("s"), w.get("e"), w.get("p")) for w in words]
toks = self.correct_tokens(toks)
text = "".join(t.lead + t.text for t in toks).strip()
return text, [{"w": t.text, "s": t.s, "e": t.e, "p": t.p} for t in toks]

View File

@@ -0,0 +1,70 @@
"""합성 매니페스트 + 사용자 교정 내보내기 → train/valid 분할.
검증 세트는 고정: 문장(공백 제거) 해시로 정하므로 학습을 다시 해도 같은 문장이 검증에 남고,
같은 문장의 다른 녹음/합성이 학습과 검증에 나뉘어 들어가지 않는다.
실제 목소리(사용자 교정)는 20%, 합성은 10% 를 검증으로 뺀다.
python build_dataset.py --synth work/synth/manifest.jsonl --user corrections.jsonl --out work/data
사용자 교정 jsonl 형식: {"audio": "<ogg 경로>", "text": "<고친 문장>"} (앱이 training/ 에서 내보냄)
"""
from __future__ import annotations
import argparse
import hashlib
from pathlib import Path
from common import log, read_jsonl, write_jsonl
VALID_RATIO = {"user": 0.2, "synth": 0.1}
def _key(text: str) -> str:
return "".join(text.split())
def is_valid(text: str, has_user: bool) -> bool:
"""문장 단위 판정. 사용자 녹음이 있는 문장은 20%, 합성만 있는 문장은 10% 확률(해시 고정)로 검증."""
bucket = int(hashlib.sha1(_key(text).encode("utf-8")).hexdigest()[:8], 16) / 0xFFFFFFFF
return bucket < VALID_RATIO["user" if has_user else "synth"]
def build(synth: str | None, user: str | None) -> tuple[list[dict], list[dict]]:
rows: list[dict] = []
for path, source in ((synth, "synth"), (user, "user")):
if not path or not Path(path).is_file():
continue
for r in read_jsonl(path):
text = str(r.get("text") or "").strip()
audio = r.get("audio")
if not text or not audio or not Path(audio).is_file():
continue
rows.append({"audio": str(audio), "text": text, "source": r.get("source") or source})
user_texts = {_key(r["text"]) for r in rows if r["source"] == "user"}
held = {_key(r["text"]) for r in rows if is_valid(r["text"], _key(r["text"]) in user_texts)}
texts = sorted({_key(r["text"]) for r in rows})
if not held and len(texts) >= 2: # 데이터가 아주 적어도 문장 하나는 검증으로 (정렬 첫 문장: 고정)
held = {texts[0]}
train = [r for r in rows if _key(r["text"]) not in held]
valid = [r for r in rows if _key(r["text"]) in held]
return train, valid
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--synth")
ap.add_argument("--user")
ap.add_argument("--out", required=True)
a = ap.parse_args()
train, valid = build(a.synth, a.user)
if not train or not valid:
raise SystemExit(f"학습 데이터가 부족합니다 (train {len(train)}, valid {len(valid)})")
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
write_jsonl(out / "train.jsonl", train)
write_jsonl(out / "valid.jsonl", valid)
log(f"train {len(train)} / valid {len(valid)} → {out}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,99 @@
"""파인튜닝 스크립트 공용 도구 (가벼운 의존성만: numpy, av)."""
from __future__ import annotations
import json
import re
import sys
import wave
from pathlib import Path
from typing import Any, Iterable, Iterator
import numpy as np
SR = 16000
def emit(obj: dict[str, Any]) -> None:
"""stdout 에 JSON 한 줄 (run.py / 워커가 읽는다). 로그는 stderr 로."""
sys.stdout.write(json.dumps(obj, ensure_ascii=False) + "\n")
sys.stdout.flush()
def progress(stage: str, step: int, total: int, **extra: Any) -> None:
emit({"event": "progress", "stage": stage, "step": step, "total": total, **extra})
def log(msg: str) -> None:
sys.stderr.write(msg + "\n")
sys.stderr.flush()
def read_jsonl(path: str | Path) -> Iterator[dict[str, Any]]:
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
yield json.loads(line)
def write_jsonl(path: str | Path, rows: Iterable[dict[str, Any]]) -> int:
n = 0
with open(path, "w", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
n += 1
return n
def load_audio(path: str | Path, sr: int = SR) -> np.ndarray:
"""아무 형식(ogg/mp3/wav) → 16k mono float32 (PyAV)."""
import av
with av.open(str(path)) as c:
res = av.AudioResampler(format="fltp", layout="mono", rate=sr)
chunks = []
for frame in c.decode(audio=0):
for f in res.resample(frame):
chunks.append(f.to_ndarray()[0])
for f in res.resample(None):
chunks.append(f.to_ndarray()[0])
return np.concatenate(chunks).astype(np.float32) if chunks else np.zeros(0, np.float32)
def write_wav(path: str | Path, audio: np.ndarray, sr: int = SR) -> None:
pcm = (np.clip(audio, -1.0, 1.0) * 32767).astype(np.int16)
with wave.open(str(path), "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sr)
w.writeframes(pcm.tobytes())
_CER_STRIP = re.compile(r"[\s.,!?…~\"'“”‘’()\[\]-]+")
def edit_distance(a: str, b: str) -> int:
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i] + [0] * len(b)
for j, cb in enumerate(b, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))
prev = cur
return prev[-1]
def cer(refs: list[str], hyps: list[str]) -> float:
"""말뭉치 CER: 공백·문장부호를 빼고 글자 편집 거리 합 / 정답 글자 수 합."""
dist = total = 0
for r, h in zip(refs, hyps, strict=True):
r2, h2 = _CER_STRIP.sub("", r).lower(), _CER_STRIP.sub("", h).lower()
dist += edit_distance(r2, h2)
total += len(r2)
return dist / max(total, 1)
def short_name(base: str) -> str:
"""openai/whisper-large-v3-turbo → large-v3-turbo"""
name = base.rstrip("/").split("/")[-1]
return name[len("whisper-"):] if name.startswith("whisper-") else name

View File

@@ -0,0 +1,57 @@
"""검증 세트 CER 계산 (기본 모델 또는 LoRA 어댑터 적용 모델).
python evaluate.py --base openai/whisper-large-v3-turbo --data work/data/valid.jsonl [--adapter work/adapter]
끝: {"result":{"cer":0.123,"n":40,"samples":[...]}}
"""
from __future__ import annotations
import argparse
import numpy as np
from common import cer, emit, load_audio, log, progress, read_jsonl
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--base", required=True)
ap.add_argument("--adapter")
ap.add_argument("--data", required=True)
ap.add_argument("--batch", type=int, default=8)
a = ap.parse_args()
import torch
from transformers import WhisperForConditionalGeneration, WhisperProcessor
cuda = torch.cuda.is_available()
dtype = torch.float16 if cuda else torch.float32
processor = WhisperProcessor.from_pretrained(a.base)
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=dtype)
if a.adapter:
from peft import PeftModel
model = PeftModel.from_pretrained(model, a.adapter).merge_and_unload()
model.to("cuda" if cuda else "cpu").eval()
rows = list(read_jsonl(a.data))
refs, hyps = [], []
stage = "evaluate_tuned" if a.adapter else "evaluate_base"
for i in range(0, len(rows), a.batch):
chunk = rows[i : i + a.batch]
audios = [load_audio(r["audio"])[: 30 * 16000] for r in chunk]
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)
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))
score = cer(refs, hyps)
log(f"{stage}: CER {score:.4f} (n={len(rows)})")
emit({"result": {"cer": round(score, 4), "n": len(rows),
"samples": [{"ref": r, "hyp": h} for r, h in list(zip(refs, hyps, strict=True))[:5]]}})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,72 @@
"""LoRA 를 기본 모델에 합치고 CTranslate2(float16) 로 변환 → models/<name>-ft-<날짜>/
python export_ct2.py --base openai/whisper-large-v3-turbo --adapter work/adapter --models-dir GVR-Data/models \
--cer-before 0.12 --cer-after 0.09
끝: {"result":{"model_dir": "...", "name": "..."}}
"""
from __future__ import annotations
import argparse
import json
import shutil
import time
from datetime import datetime
from pathlib import Path
from common import emit, log, progress, short_name
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--base", required=True)
ap.add_argument("--adapter", required=True)
ap.add_argument("--models-dir", required=True)
ap.add_argument("--name", help="기본: <기본모델 짧은 이름>-ft-<YYYYMMDD>")
ap.add_argument("--cer-before", type=float)
ap.add_argument("--cer-after", type=float)
ap.add_argument("--quantization", default="float16")
a = ap.parse_args()
import ctranslate2
import torch
from peft import PeftModel
from transformers import WhisperForConditionalGeneration, WhisperProcessor
name = a.name or f"{short_name(a.base)}-ft-{datetime.now():%Y%m%d}"
root = Path(a.models_dir)
root.mkdir(parents=True, exist_ok=True)
out = root / name
merged = root / f".merge-{name}"
shutil.rmtree(merged, ignore_errors=True)
try:
progress("export", 0, 2)
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.float32)
model = PeftModel.from_pretrained(model, a.adapter).merge_and_unload()
model.save_pretrained(str(merged))
processor = WhisperProcessor.from_pretrained(a.adapter)
processor.save_pretrained(str(merged))
# faster-whisper 는 preprocessor_config.json 의 feature_size(80/128 mel)를 읽는다.
# transformers 5 의 processor 저장은 processor_config.json 만 쓰므로 따로 저장한다.
processor.feature_extractor.save_pretrained(str(merged))
del model
progress("export", 1, 2)
copy = ["tokenizer.json", "preprocessor_config.json"]
missing = [f for f in copy if not (merged / f).exists()]
if missing:
raise SystemExit(f"내보내기에 필요한 파일이 없습니다: {missing}")
ctranslate2.converters.TransformersConverter(str(merged), copy_files=copy).convert(
str(out), quantization=a.quantization, force=True)
finally:
shutil.rmtree(merged, ignore_errors=True)
meta = {"base": a.base, "adapter": str(a.adapter), "cer_before": a.cer_before, "cer_after": a.cer_after,
"quantization": a.quantization, "created": datetime.now().isoformat(timespec="seconds"),
"created_ts": int(time.time())}
(out / "gvr-model.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
progress("export", 2, 2)
log(f"내보냄 → {out}")
emit({"result": {"model_dir": str(out), "name": name}})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,10 @@
# 파인튜닝 전용 환경 (워커와 별도). torch 는 아래 인덱스에서 따로 설치:
# Windows/RTX 50 (CUDA 12.8): pip install torch --index-url https://download.pytorch.org/whl/cu128
# CPU 테스트: pip install torch --index-url https://download.pytorch.org/whl/cpu
transformers==5.19.0
peft==0.21.2
accelerate==1.15.0
ctranslate2==4.8.3
edge-tts==7.3.1
av==18.1.0
numpy==2.4.6

View File

@@ -0,0 +1,133 @@
"""파인튜닝 전체 흐름: 합성 → 데이터셋 → 학습 → 평가(전/후) → CT2 내보내기.
각 단계는 같은 파이썬으로 별도 프로세스에서 돈다 (단계마다 메모리를 비움).
stdout: 진행 {"event":"progress","stage":..,"step":..,"total":..} / 마지막 {"result":{...,"adopt":bool}}
adopt = 학습 후 CER < 학습 전 CER. adopt 일 때만 내보낸다 (--export-always 면 항상).
python run.py --data-dir GVR-Data --dictionary words.txt --sentences s.txt --user-corrections c.jsonl
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
from common import emit, log
HERE = Path(__file__).resolve().parent
class Stopped(Exception):
pass
def stage(script: str, args: list[str]) -> dict[str, Any]:
"""하위 스크립트를 실행하고 진행 줄은 그대로 중계, 마지막 result 를 돌려준다."""
cmd = [sys.executable, str(HERE / script), *args]
log("$ " + " ".join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")
result: dict[str, Any] = {}
for line in proc.stdout or []:
try:
msg = json.loads(line)
except json.JSONDecodeError:
log(line.rstrip())
continue
if isinstance(msg, dict) and msg.get("event") == "progress":
emit(msg)
elif isinstance(msg, dict) and "result" in msg:
result = msg["result"]
if proc.wait() != 0:
raise SystemExit(f"{script} 실패 (종료 코드 {proc.returncode})")
return result
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--data-dir", required=True)
ap.add_argument("--base", default="openai/whisper-large-v3-turbo")
ap.add_argument("--sentences")
ap.add_argument("--dictionary")
ap.add_argument("--user-corrections")
ap.add_argument("--synth-count", type=int, default=300)
ap.add_argument("--epochs", type=float, default=3)
ap.add_argument("--max-steps", type=int, default=0)
ap.add_argument("--batch", type=int, default=4)
ap.add_argument("--accum", type=int, default=4)
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--stop-file", help="기본: <data-dir>/finetune.stop (앱이 게임 시작 때 만든다)")
ap.add_argument("--work", help="기본: <data-dir>/finetune/<시각>")
ap.add_argument("--name")
ap.add_argument("--export-always", action="store_true")
a = ap.parse_args()
data_dir = Path(a.data_dir)
stop_file = Path(a.stop_file) if a.stop_file else data_dir / "finetune.stop"
work = Path(a.work) if a.work else data_dir / "finetune" / datetime.now().strftime("%Y%m%d-%H%M%S")
work.mkdir(parents=True, exist_ok=True)
res: dict[str, Any] = {"base": a.base, "work": str(work), "adopt": False, "stopped": False}
def check_stop() -> None:
if stop_file.exists():
raise Stopped()
try:
check_stop()
synth_manifest = None
if a.synth_count > 0 and (a.sentences or a.dictionary):
sargs = ["--out", str(work / "synth"), "--count", str(a.synth_count)]
if a.sentences:
sargs += ["--sentences", a.sentences]
if a.dictionary:
sargs += ["--dictionary", a.dictionary]
stage("synth.py", sargs)
synth_manifest = str(work / "synth" / "manifest.jsonl")
check_stop()
dargs = ["--out", str(work / "data")]
if synth_manifest:
dargs += ["--synth", synth_manifest]
if a.user_corrections:
dargs += ["--user", a.user_corrections]
stage("build_dataset.py", dargs)
valid = str(work / "data" / "valid.jsonl")
check_stop()
before = stage("evaluate.py", ["--base", a.base, "--data", valid])
res["cer_before"] = before["cer"]
check_stop()
tr = stage("train_lora.py", [
"--base", a.base, "--train", str(work / "data" / "train.jsonl"), "--out", str(work / "adapter"),
"--epochs", str(a.epochs), "--max-steps", str(a.max_steps), "--batch", str(a.batch),
"--accum", str(a.accum), "--lr", str(a.lr), "--stop-file", str(stop_file)])
res["train"] = tr
if tr.get("stopped"):
raise Stopped()
after = stage("evaluate.py", ["--base", a.base, "--adapter", str(work / "adapter"), "--data", valid])
res["cer_after"] = after["cer"]
res["adopt"] = res["cer_after"] < res["cer_before"]
res["samples"] = after.get("samples")
if res["adopt"] or a.export_always:
check_stop()
eargs = ["--base", a.base, "--adapter", str(work / "adapter"), "--models-dir", str(data_dir / "models"),
"--cer-before", str(res["cer_before"]), "--cer-after", str(res["cer_after"])]
if a.name:
eargs += ["--name", a.name]
ex = stage("export_ct2.py", eargs)
res["model_dir"], res["model_name"] = ex["model_dir"], ex["name"]
except Stopped:
log("게임 실행 감지(중지 파일) → 파인튜닝 중단")
res["stopped"] = True
res["adopt"] = False
emit({"result": res})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,132 @@
"""단어사전 문장으로 합성 학습 음성 만들기 (edge-tts, 인터넷 필요).
python synth.py --sentences s.txt --dictionary words.txt --count 200 --out work/synth
출력: out/*.wav (16k mono) + out/manifest.jsonl ({"audio","text","source":"synth","voice"})
"""
from __future__ import annotations
import argparse
import asyncio
import random
import tempfile
from pathlib import Path
import numpy as np
from common import SR, load_audio, log, progress, write_jsonl, write_wav
VOICES = ["ko-KR-SunHiNeural", "ko-KR-InJoonNeural", "ko-KR-HyunsuMultilingualNeural"]
RATES = ["-10%", "+0%", "+10%", "+20%"]
PITCHES = ["-6Hz", "+0Hz", "+6Hz"]
TEMPLATES = [
"{w} 조심해", "{w} 어디 있어", "{w} 봤어", "지금 {w} 간다", "{w} 쪽으로 가자", "{w} 잡았어",
"{w} 각이야", "{w} 써줘", "나 {w} 할게", "{w} 빠졌어",
]
def build_sentences(sentences: list[str], words: list[str], count: int, rng: random.Random) -> list[str]:
pool = list(dict.fromkeys(s.strip() for s in sentences if s.strip()))
for w in words:
pool.append(rng.choice(TEMPLATES).format(w=w))
rng.shuffle(pool)
if not pool:
raise SystemExit("문장이 없습니다 (--sentences 또는 --dictionary 필요)")
return [pool[i % len(pool)] for i in range(count)]
def mix_noise(x: np.ndarray, rng: random.Random, noise_files: list[Path]) -> np.ndarray:
"""SNR 10~30dB 로 배경 잡음 섞기. 잡음 파일이 없으면 합성 잡음(백색+키보드 딸깍)."""
n = x.size
if noise_files:
noise = load_audio(rng.choice(noise_files))
if noise.size == 0:
return x
noise = np.tile(noise, int(np.ceil(n / noise.size)))[:n]
else:
g = np.random.default_rng(rng.randrange(1 << 30))
noise = g.normal(0, 1, n).astype(np.float32) * 0.3
for _ in range(int(n / SR * 4)): # 초당 4번 딸깍
i = g.integers(0, max(1, n - 200))
noise[i : i + 200] += g.normal(0, 3, min(200, n - i)) * np.exp(-np.linspace(0, 8, min(200, n - i)))
snr = rng.uniform(10, 30)
ps = float(np.mean(x**2)) + 1e-12
pn = float(np.mean(noise**2)) + 1e-12
out = x + noise * np.sqrt(ps / (pn * 10 ** (snr / 10)))
peak = float(np.max(np.abs(out)))
return (out / peak * 0.95 if peak > 0.99 else out).astype(np.float32)
async def synth_all(texts: list[str], out: Path, noise_prob: float, noise_files: list[Path], seed: int,
voices: list[str]) -> list[dict]:
import edge_tts
rng = random.Random(seed)
jobs = [(i, t, rng.choice(voices), rng.choice(RATES), rng.choice(PITCHES), rng.random() < noise_prob,
rng.randrange(1 << 30)) for i, t in enumerate(texts)]
sem = asyncio.Semaphore(4)
rows: list[dict | None] = [None] * len(jobs)
done = 0
bad_voices: set[str] = set()
async def one(job: tuple) -> None:
nonlocal done
i, text, voice, rate, pitch, noisy, s = job
async with sem:
for v in [voice] + [x for x in voices if x != voice]:
if v in bad_voices:
continue
with tempfile.NamedTemporaryFile(suffix=".mp3", dir=out, delete=False) as tf:
mp3 = Path(tf.name)
try:
await edge_tts.Communicate(text, v, rate=rate, pitch=pitch).save(str(mp3))
audio = load_audio(mp3)
if audio.size == 0:
raise RuntimeError("빈 음성")
if noisy:
audio = mix_noise(audio, random.Random(s), noise_files)
wav = out / f"synth_{i:05d}.wav"
write_wav(wav, audio)
rows[i] = {"audio": str(wav.resolve()), "text": text, "source": "synth", "voice": v,
"rate": rate, "pitch": pitch, "noise": noisy}
break
except Exception as e: # noqa: BLE001 - 목소리 하나 실패하면 다른 목소리로
log(f"TTS 실패 ({v}): {e}")
if "voice" in str(e).lower() or "No audio" in str(e):
bad_voices.add(v)
finally:
mp3.unlink(missing_ok=True)
done += 1
progress("synth", done, len(jobs))
await asyncio.gather(*(one(j) for j in jobs))
return [r for r in rows if r]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--sentences", help="문장 파일 (한 줄에 하나)")
ap.add_argument("--dictionary", help="단어 파일 (한 줄에 하나). 템플릿 문장으로 만든다")
ap.add_argument("--count", type=int, default=200)
ap.add_argument("--out", required=True)
ap.add_argument("--noise-prob", type=float, default=0.3)
ap.add_argument("--noise-dir", help="배경 잡음 오디오 폴더 (선택)")
ap.add_argument("--voices", default=",".join(VOICES))
ap.add_argument("--seed", type=int, default=1234)
a = ap.parse_args()
read = lambda p: Path(p).read_text(encoding="utf-8").splitlines() if p else [] # noqa: E731
rng = random.Random(a.seed)
texts = build_sentences(read(a.sentences), [w.strip() for w in read(a.dictionary) if w.strip()], a.count, rng)
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
noise_files = sorted(p for p in Path(a.noise_dir).glob("*") if p.is_file()) if a.noise_dir else []
rows = asyncio.run(synth_all(texts, out, a.noise_prob, noise_files, a.seed, a.voices.split(",")))
if not rows:
raise SystemExit("합성 음성을 하나도 만들지 못했습니다 (인터넷 연결 확인)")
n = write_jsonl(out / "manifest.jsonl", rows)
log(f"합성 {n}개 → {out / 'manifest.jsonl'}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,141 @@
"""Whisper LoRA 학습 (peft). CUDA 면 bf16 autocast, 아니면 CPU fp32.
python train_lora.py --base openai/whisper-large-v3-turbo --train work/data/train.jsonl --out work/adapter
진행: {"event":"progress","stage":"train","step":k,"total":n,"loss":x} / 끝: {"result":{...}}
--stop-file 이 생기면 (게임 시작) 지금까지 학습한 어댑터를 저장하고 멈춘다.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import time
from pathlib import Path
import numpy as np
from common import emit, load_audio, log, progress, read_jsonl
MAX_SAMPLES = 30 * 16000
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--base", default="openai/whisper-large-v3-turbo")
ap.add_argument("--train", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--epochs", type=float, default=3)
ap.add_argument("--max-steps", type=int, default=0, help="0 이면 epochs 로 계산")
ap.add_argument("--batch", type=int, default=4)
ap.add_argument("--accum", type=int, default=4)
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--rank", type=int, default=32)
ap.add_argument("--no-grad-ckpt", action="store_true")
ap.add_argument("--stop-file")
ap.add_argument("--seed", type=int, default=42)
a = ap.parse_args()
import torch
from peft import LoraConfig, get_peft_model
from transformers import WhisperForConditionalGeneration, WhisperProcessor
random.seed(a.seed)
torch.manual_seed(a.seed)
cuda = torch.cuda.is_available()
device = torch.device("cuda" if cuda else "cpu")
bf16 = cuda and torch.cuda.is_bf16_supported()
log(f"device={device} bf16={bf16} base={a.base}")
processor = WhisperProcessor.from_pretrained(a.base)
processor.tokenizer.set_prefix_tokens(language="korean", task="transcribe")
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.float32)
model.config.use_cache = False
model.generation_config.language = "ko"
model.generation_config.task = "transcribe"
model.generation_config.forced_decoder_ids = None
if not a.no_grad_ckpt:
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
model = get_peft_model(model, LoraConfig(
r=a.rank, lora_alpha=a.rank * 2, lora_dropout=0.05, bias="none",
target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
))
model.print_trainable_parameters()
model.to(device)
rows = list(read_jsonl(a.train))
if not rows:
raise SystemExit("학습 데이터가 없습니다")
start_id = model.config.decoder_start_token_id
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:]
return feats, labels
def batches():
while True:
order = list(range(len(rows)))
random.shuffle(order)
for i in range(0, len(order), a.batch):
items = [featurize(rows[j]) for j in order[i : i + a.batch]]
feats = torch.tensor(np.stack([f for f, _ in items]))
n = max(len(lab) for _, lab in items)
labels = torch.full((len(items), n), -100, dtype=torch.long)
for k, (_, lab) in enumerate(items):
labels[k, : len(lab)] = torch.tensor(lab)
yield feats, labels
steps_per_epoch = math.ceil(len(rows) / (a.batch * a.accum))
total = a.max_steps or max(1, int(steps_per_epoch * a.epochs))
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.01)
warmup = max(1, total // 10)
sched = torch.optim.lr_scheduler.LambdaLR( # 선형 워밍업 → 선형 감소
opt, lambda s: (s + 1) / warmup if s < warmup else max(0.0, (total - s) / max(1, total - warmup)))
stop_file = Path(a.stop_file) if a.stop_file else None
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
model.train()
it = batches()
step, stopped, t0, last_loss = 0, False, time.time(), float("nan")
progress("train", 0, total)
while step < total:
if stop_file and stop_file.exists():
log("중지 파일 발견 → 저장 후 종료")
stopped = True
break
opt.zero_grad(set_to_none=True)
acc_loss = 0.0
for _ in range(a.accum):
feats, labels = next(it)
feats, labels = feats.to(device), labels.to(device)
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=bf16):
loss = model(input_features=feats, labels=labels).loss / a.accum
loss.backward()
acc_loss += float(loss.detach())
torch.nn.utils.clip_grad_norm_(params, 1.0)
opt.step()
sched.step()
step += 1
last_loss = acc_loss
progress("train", step, total, loss=round(acc_loss, 4), lr=sched.get_last_lr()[0])
model.save_pretrained(str(out))
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}
(out / "train_meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
emit({"result": {"adapter": str(out), **meta}})
if __name__ == "__main__":
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
main()

174
worker/gvr_worker/gpu.py Normal file
View File

@@ -0,0 +1,174 @@
"""NVIDIA GPU 감지 (NVML → nvidia-smi 순) 와 VRAM 별 모델 추천."""
from __future__ import annotations
import logging
import re
import shutil
import subprocess
from typing import Any
log = logging.getLogger(__name__)
GAME_RESERVE_MB = 3072 # 게임 프로필 기본값 (발로란트·롤 중 큰 값, 추정)
def _as_str(v: Any) -> str:
return v.decode() if isinstance(v, bytes) else str(v)
def _from_nvml() -> list[dict[str, Any]] | None:
try:
import pynvml
except ImportError:
return None
try:
pynvml.nvmlInit()
except Exception as e: # noqa: BLE001 - 드라이버 없음 등
log.info("NVML 초기화 실패: %s", e)
return None
try:
driver = _as_str(pynvml.nvmlSystemGetDriverVersion())
try:
cv = int(pynvml.nvmlSystemGetCudaDriverVersion_v2())
cuda_driver = f"{cv // 1000}.{(cv % 1000) // 10}"
except Exception: # noqa: BLE001
cuda_driver = None
gpus = []
for i in range(pynvml.nvmlDeviceGetCount()):
h = pynvml.nvmlDeviceGetHandleByIndex(i)
mem = pynvml.nvmlDeviceGetMemoryInfo(h)
try:
major, minor = pynvml.nvmlDeviceGetCudaComputeCapability(h)
cc = f"{major}.{minor}"
except Exception: # noqa: BLE001
cc = None
gpus.append(
{
"index": i,
"name": _as_str(pynvml.nvmlDeviceGetName(h)),
"vram_total_mb": int(mem.total // 1048576),
"vram_used_mb": int(mem.used // 1048576),
"driver": driver,
"cuda_driver": cuda_driver,
"compute_capability": cc,
}
)
return gpus
finally:
try:
pynvml.nvmlShutdown()
except Exception: # noqa: BLE001
pass
def _run_smi(args: list[str]) -> str | None:
exe = shutil.which("nvidia-smi")
if not exe:
return None
try:
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
out = subprocess.run([exe, *args], capture_output=True, text=True, timeout=10, creationflags=flags)
except (OSError, subprocess.TimeoutExpired) as e:
log.info("nvidia-smi 실행 실패: %s", e)
return None
return out.stdout if out.returncode == 0 else None
def parse_smi_csv(csv_text: str, cuda_driver: str | None) -> list[dict[str, Any]]:
gpus = []
for line in csv_text.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 6:
continue
try:
gpus.append(
{
"index": int(parts[0]),
"name": parts[1],
"vram_total_mb": int(float(parts[2])),
"vram_used_mb": int(float(parts[3])),
"driver": parts[4],
"cuda_driver": cuda_driver,
"compute_capability": parts[5] if parts[5] not in ("", "[N/A]") else None,
}
)
except ValueError:
continue
return gpus
def _from_smi() -> list[dict[str, Any]]:
csv_text = _run_smi(
[
"--query-gpu=index,name,memory.total,memory.used,driver_version,compute_cap",
"--format=csv,noheader,nounits",
]
)
if not csv_text:
return []
header = _run_smi([]) or ""
m = re.search(r"CUDA Version:\s*([\d.]+)", header)
return parse_smi_csv(csv_text, m.group(1) if m else None)
def gpu_list() -> list[dict[str, Any]]:
gpus = _from_nvml()
if gpus is None:
gpus = _from_smi()
return gpus
def recommend(gpus: list[dict[str, Any]], game_reserve_mb: int = GAME_RESERVE_MB) -> dict[str, Any]:
"""VRAM 표(보고서 5-2)에 따라 실시간/정밀 모델을 고른다. 임계값은 GPU 전체 VRAM 기준."""
if not gpus:
return {
"device": "cpu",
"supported": False,
"realtime": "small",
"precise": "medium",
"compute_type": "int8",
"budget_mb": 0,
"precise_after_match": True,
"reason": "NVIDIA GPU 를 찾지 못했습니다. 겜녹이는 NVIDIA GPU 만 지원하며, CPU 로는 매우 느립니다.",
}
gpu = max(gpus, key=lambda g: g["vram_total_mb"])
total_mb = int(gpu["vram_total_mb"])
total_gb = total_mb / 1024
budget_mb = max(0, (total_mb - game_reserve_mb) // 100 * 100)
shown_gb = round(total_gb)
rec: dict[str, Any] = {"device": "cuda", "supported": True, "gpu_index": gpu["index"], "budget_mb": budget_mb}
if total_gb >= 14:
rec.update(
realtime="large-v3-turbo", precise="large-v3", compute_type="float16", precise_after_match=False,
reason=f"{shown_gb}GB: 게임 3GB 예약 후 실시간(large-v3-turbo)+정밀(large-v3) 동시 적재",
)
elif total_gb >= 10:
rec.update(
realtime="large-v3", precise="large-v3", compute_type="float16", precise_after_match=True,
reason=f"{shown_gb}GB: 게임 3GB 예약 후 large-v3 하나만 여유. 정밀 변환은 경기 종료 뒤에 적재",
)
elif total_gb >= 7:
rec.update(
realtime="large-v3-turbo", precise="large-v3-turbo", compute_type="float16", precise_after_match=True,
reason=f"{shown_gb}GB: 게임 3GB 예약 후 large-v3-turbo(float16) 하나로 실시간·정밀 모두 처리",
)
elif total_gb >= 5:
rec.update(
realtime="large-v3-turbo", precise="large-v3-turbo", compute_type="int8_float16", precise_after_match=True,
reason=f"{shown_gb}GB: VRAM 이 빠듯해 large-v3-turbo 를 int8_float16 으로 적재",
)
else:
rec.update(
realtime="small", precise="medium", compute_type="float16", precise_after_match=True,
reason=f"{shown_gb}GB: VRAM 이 작아 실시간은 small, 정밀(경기 후)은 medium 사용",
)
cc = gpu.get("compute_capability") or ""
if rec["compute_type"].startswith("int8") and cc.startswith("12."):
rec["warning"] = "RTX 50 시리즈(Blackwell)에서 int8 연산이 cuBLAS 오류를 낸 사례가 있습니다. 오류 시 float16 으로 바꾸세요."
return rec
def gpu_info() -> dict[str, Any]:
gpus = gpu_list()
return {"gpus": gpus, "recommend": recommend(gpus)}

198
worker/gvr_worker/main.py Normal file
View File

@@ -0,0 +1,198 @@
"""워커 진입점: 요청 라우팅."""
from __future__ import annotations
import json
import logging
import os
import platform
import subprocess
import sys
import threading
from collections import deque
from pathlib import Path
from typing import Any
from . import __version__
from .paths import data_dir, setup_cuda_dll_path
from .protocol import Context, Server, WorkerError, Writer, require, setup_stdio
log = logging.getLogger("gvr_worker")
def build_server(writer: Writer) -> Server:
from . import gpu, models
from .stt import SttEngine
server = Server(writer)
engine = SttEngine()
ocr_state: dict[str, Any] = {"session": None}
ocr_lock = threading.Lock()
@server.route("hello")
def hello(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return {"version": __version__, "python": platform.python_version(),
"device": "cuda" if gpu.gpu_list() else "cpu"}
@server.route("gpu_info")
def gpu_info(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return gpu.gpu_info()
@server.route("models")
def models_op(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
res = models.list_models()
res["loaded"] = engine.status()
return res
@server.route("download", "thread")
def download(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
target = require(req, "target")
if target == "model":
return models.download_model(require(req, "name"), ctx.emit)
if target == "cuda_runtime":
return models.download_cuda_runtime(ctx.emit)
raise WorkerError("bad_request", "target 은 model 또는 cuda_runtime 이어야 합니다")
@server.route("load", "slot")
def load(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
cpu_threads = req.get("cpu_threads")
return engine.load(req["slot"], require(req, "model"), req.get("device"), req.get("compute_type"),
int(cpu_threads) if isinstance(cpu_threads, int) else 0)
@server.route("unload", "slot")
def unload(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return engine.unload(req["slot"])
@server.route("transcribe", "slot")
def transcribe(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return engine.transcribe(req)
@server.route("ocr_start")
def ocr_start(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .ocr import OcrSession
title = require(req, "window_title")
region = req.get("region") or {"x": 0, "y": 0.62, "w": 0.32, "h": 0.25}
if not all(isinstance(region.get(k), (int, float)) for k in ("x", "y", "w", "h")):
raise WorkerError("bad_request", "region 은 {x,y,w,h} 비율이어야 합니다")
with ocr_lock:
if ocr_state["session"] is not None:
ocr_state["session"].stop()
ocr_state["session"] = None
session = OcrSession(title, region, float(req.get("fps") or 3), str(req.get("lang") or "ko"),
writer.send)
session.start()
ocr_state["session"] = session
return {"started": True}
@server.route("ocr_stop")
def ocr_stop(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
with ocr_lock:
session = ocr_state["session"]
ocr_state["session"] = None
if session is not None:
session.stop()
return {"stopped": session is not None}
@server.route("ocr_image", "thread")
def ocr_image(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .ocr import ocr_image as run
path = require(req, "path")
if not os.path.isfile(path):
raise WorkerError("file_not_found", f"이미지 파일이 없습니다: {path}")
return run(path, str(req.get("lang") or "ko"))
@server.route("r3dlog_check")
def r3dlog_check(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .r3dlog import check
return check(require(req, "logs_dir"))
@server.route("r3dlog_read", "thread")
def r3dlog_read(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .r3dlog import read
since = req.get("since_ms")
if since is not None and not isinstance(since, (int, float)):
raise WorkerError("bad_request", "since_ms 는 숫자(Unix ms) 또는 null 이어야 합니다")
return read(require(req, "logs_dir"), since)
@server.route("train", "thread")
def train(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return run_finetune(req, ctx)
@server.route("shutdown")
def shutdown(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
with ocr_lock:
if ocr_state["session"] is not None:
ocr_state["session"].stop()
ocr_state["session"] = None
server.stop()
return {"bye": True}
return server
def run_finetune(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
"""별도 파인튜닝 파이썬 환경에서 finetune/run.py 를 돌리고 진행 이벤트를 중계한다."""
py = req.get("python") or os.environ.get("GVR_FINETUNE_PYTHON")
if not py or not os.path.isfile(py):
raise WorkerError("finetune_env_missing", "파인튜닝용 파이썬 환경이 없습니다 (python 필드 또는 GVR_FINETUNE_PYTHON)")
script = Path(__file__).parent / "finetune" / "run.py"
cmd = [py, str(script), "--data-dir", str(data_dir())]
for k, v in (req.get("args") or {}).items():
flag = "--" + str(k).replace("_", "-")
if v is True:
cmd.append(flag)
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",
errors="replace", creationflags=flags, env={**os.environ, "PYTHONIOENCODING": "utf-8"})
err_tail: deque[str] = deque(maxlen=30)
def pump_stderr() -> None:
for x in proc.stderr or []:
err_tail.append(x)
sys.stderr.write(x)
t = threading.Thread(target=pump_stderr, daemon=True)
t.start()
result: dict[str, Any] | None = None
for line in proc.stdout or []:
try:
msg = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(msg, dict) and msg.get("event") == "progress":
ctx.emit("progress", **{k: v for k, v in msg.items() if k not in ("event", "id")})
elif isinstance(msg, dict) and "result" in msg:
result = msg["result"]
code = proc.wait()
t.join(timeout=2)
if code != 0 or result is None:
raise WorkerError("train_failed", f"파인튜닝 실패 (종료 코드 {code}): {''.join(err_tail)[-800:]}")
return result
def main() -> None:
logging.basicConfig(stream=sys.stderr, level=os.environ.get("GVR_LOG_LEVEL", "INFO"),
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
for noisy in ("httpx", "httpx2", "huggingface_hub", "faster_whisper"):
logging.getLogger(noisy).setLevel(logging.WARNING)
setup_cuda_dll_path() # ctranslate2 import 전에
stdin, stdout = setup_stdio()
writer = Writer(stdout)
server = build_server(writer)
log.info("gvr-worker %s 시작 (python %s, data=%s)", __version__, platform.python_version(), data_dir())
try:
server.serve(stdin)
except KeyboardInterrupt:
pass
finally:
try:
stdout.flush()
finally:
# 진행 중 다운로드 스레드는 기다리지 않는다 (다음 실행에서 이어받기)
os._exit(0)

368
worker/gvr_worker/models.py Normal file
View File

@@ -0,0 +1,368 @@
"""모델 레지스트리, 모델·CUDA 런타임 다운로드 (이어받기·디스크 확인·해시 검사·진행률)."""
from __future__ import annotations
import fnmatch
import hashlib
import json
import logging
import os
import shutil
import threading
import time
import urllib.request
import zipfile
from pathlib import Path
from typing import Any, Callable
from .paths import IS_WINDOWS, cuda_dir, models_dir
from .protocol import WorkerError
log = logging.getLogger(__name__)
MB = 1048576
# 이름 → (HF 저장소, 대략 크기 MiB: 설치 전 표시용)
REGISTRY: dict[str, tuple[str, int]] = {
"large-v3-turbo": ("mobiuslabsgmbh/faster-whisper-large-v3-turbo", 1548),
"large-v3": ("Systran/faster-whisper-large-v3", 2949),
"medium": ("Systran/faster-whisper-medium", 1457),
"small": ("Systran/faster-whisper-small", 464),
"tiny": ("Systran/faster-whisper-tiny", 75),
}
MODEL_FILE_PATTERNS = ["config.json", "preprocessor_config.json", "model.bin", "tokenizer.json", "vocabulary.*"]
REQUIRED_FILES = ["config.json", "model.bin"]
PARTIAL_MARKER = ".gvr-downloading"
DOWNLOAD_META = "gvr-download.json"
CUDA_WHEELS = ["nvidia-cublas-cu12", "nvidia-cudnn-cu12"]
CUDA_META = "gvr-cuda.json"
DISK_MARGIN_MB = 300
ProgressFn = Callable[..., None]
_busy: set[str] = set()
_busy_lock = threading.Lock()
# --- 조회 --------------------------------------------------------------------
def _dir_size(path: Path) -> int:
total = 0
for root, _dirs, files in os.walk(path):
for f in files:
try:
total += os.path.getsize(os.path.join(root, f))
except OSError:
pass
return total
def is_model_dir(path: Path) -> bool:
return all((path / f).is_file() for f in REQUIRED_FILES) and not (path / PARTIAL_MARKER).exists()
def resolve_model_path(name: str) -> Path:
"""모델 이름(레지스트리·파인튜닝 모델 폴더명) 또는 절대 경로를 모델 폴더로 바꾼다."""
cand = models_dir() / name
if is_model_dir(cand):
return cand
p = Path(name)
if p.is_absolute() and is_model_dir(p):
return p
if name in REGISTRY or (models_dir() / name).exists():
raise WorkerError("model_not_installed", f"모델 '{name}' 이(가) 설치되지 않았습니다. 먼저 다운로드하세요.")
raise WorkerError("unknown_model", f"알 수 없는 모델: {name}")
def list_models() -> dict[str, Any]:
root = models_dir()
out: list[dict[str, Any]] = []
for name, (repo, approx_mb) in REGISTRY.items():
d = root / name
installed = is_model_dir(d)
out.append(
{
"name": name,
"repo": repo,
"size_mb": round(_dir_size(d) / MB) if installed else approx_mb,
"installed": installed,
"partial": (d / PARTIAL_MARKER).exists(),
"path": str(d),
}
)
# 파인튜닝 등으로 만든 추가 모델 (gvr-model.json 포함)
if root.is_dir():
for d in sorted(root.iterdir()):
if d.name in REGISTRY or not d.is_dir() or not is_model_dir(d):
continue
meta: dict[str, Any] = {}
try:
meta = json.loads((d / "gvr-model.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
pass
out.append(
{"name": d.name, "repo": None, "size_mb": round(_dir_size(d) / MB), "installed": True,
"partial": False, "path": str(d), "meta": meta or None}
)
cd = cuda_dir()
cuda_installed = (cd / CUDA_META).is_file()
return {
"models": out,
"cuda_runtime": {
"installed": cuda_installed,
"required": IS_WINDOWS,
"path": str(cd),
"size_mb": round(_dir_size(cd) / MB) if cd.is_dir() else 0,
},
}
# --- 공통 -------------------------------------------------------------------
def _check_disk(path: Path, need_bytes: int) -> None:
path.mkdir(parents=True, exist_ok=True)
free = shutil.disk_usage(path).free
if free < need_bytes + DISK_MARGIN_MB * MB:
raise WorkerError(
"disk_full",
f"디스크 공간이 부족합니다. 필요 {need_bytes / MB / 1024:.1f}GB, 남은 공간 {free / MB / 1024:.1f}GB ({path})",
)
def _sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8 * MB), b""):
h.update(chunk)
return h.hexdigest()
class ProgressReporter:
"""완료 바이트를 받아 progress 이벤트를 초당 약 2회로 줄여 보낸다."""
def __init__(self, emit: ProgressFn, total_bytes: int, interval: float = 0.5) -> None:
self.emit = emit
self.total = total_bytes
self.interval = interval
self._start = time.monotonic()
self._last = 0.0
self._base: int | None = None
def update(self, done_bytes: int, force: bool = False, **extra: Any) -> None:
now = time.monotonic()
if not force and now - self._last < self.interval:
return
self._last = now
if self._base is None: # 이어받기: 이미 있던 양은 속도 계산에서 뺀다
self._base = done_bytes
elapsed = max(now - self._start, 1e-3)
speed = max(done_bytes - self._base, 0) / elapsed / MB
remain = max(self.total - done_bytes, 0) / MB
self.emit(
"progress",
done_mb=round(done_bytes / MB, 1),
total_mb=round(self.total / MB, 1),
speed_mbps=round(speed, 2),
eta_s=int(remain / speed) if speed > 0.01 else None,
**extra,
)
def _claim(key: str) -> None:
with _busy_lock:
if key in _busy:
raise WorkerError("busy", f"이미 다운로드 중입니다: {key}")
_busy.add(key)
def _release(key: str) -> None:
with _busy_lock:
_busy.discard(key)
# --- 모델 다운로드 ------------------------------------------------------------
def download_model(name: str, emit: ProgressFn) -> dict[str, Any]:
if name not in REGISTRY:
raise WorkerError("unknown_model", f"알 수 없는 모델: {name}")
repo = REGISTRY[name][0]
target = models_dir() / name
if is_model_dir(target):
return {"path": str(target), "already": True}
_claim(f"model:{name}")
try:
return _download_model(repo, target, emit)
finally:
_release(f"model:{name}")
def _download_model(repo: str, target: Path, emit: ProgressFn) -> dict[str, Any]:
from huggingface_hub import HfApi, hf_hub_download
try:
info = HfApi().model_info(repo, files_metadata=True)
except Exception as e: # noqa: BLE001 - 네트워크 오류 등
raise WorkerError("network", f"모델 정보를 가져오지 못했습니다 ({repo}): {e}") from e
files = [
s for s in (info.siblings or [])
if any(fnmatch.fnmatch(s.rfilename, p) for p in MODEL_FILE_PATTERNS)
]
if not any(s.rfilename == "model.bin" for s in files):
raise WorkerError("bad_repo", f"{repo} 에 model.bin 이 없습니다")
total = sum(int(s.size or 0) for s in files)
target.mkdir(parents=True, exist_ok=True)
(target / PARTIAL_MARKER).write_text(repo, encoding="utf-8")
_check_disk(target, max(total - _dir_size(target), 0))
reporter = ProgressReporter(emit, total)
stop = threading.Event()
def poll() -> None: # 디스크에 쌓인 바이트로 진행률 계산 (.incomplete 포함)
while not stop.wait(0.5):
reporter.update(min(_dir_size(target), total))
poller = threading.Thread(target=poll, daemon=True)
poller.start()
try:
for s in files:
for attempt in range(3):
try:
hf_hub_download(repo, s.rfilename, revision=info.sha, local_dir=str(target))
break
except Exception as e: # noqa: BLE001
if attempt == 2:
raise WorkerError("network", f"다운로드 실패 ({s.rfilename}): {e}") from e
log.warning("다운로드 재시도 %s: %s", s.rfilename, e)
time.sleep(2 * (attempt + 1))
finally:
stop.set()
poller.join(timeout=2)
# 검증: 크기, LFS sha256
reporter.update(total, force=True, stage="verify")
for s in files:
p = target / s.rfilename
if s.size is not None and p.stat().st_size != s.size:
p.unlink(missing_ok=True)
raise WorkerError("verify_failed", f"파일 크기가 맞지 않습니다: {s.rfilename}. 다시 다운로드하세요.")
lfs = getattr(s, "lfs", None)
sha = getattr(lfs, "sha256", None) if lfs is not None else None
if sha and _sha256(p) != sha:
p.unlink(missing_ok=True)
raise WorkerError("verify_failed", f"해시가 맞지 않습니다: {s.rfilename}. 다시 다운로드하세요.")
shutil.rmtree(target / ".cache", ignore_errors=True)
(target / DOWNLOAD_META).write_text(
json.dumps({"repo": repo, "revision": info.sha, "files": [s.rfilename for s in files],
"created": int(time.time())}, ensure_ascii=False),
encoding="utf-8",
)
(target / PARTIAL_MARKER).unlink(missing_ok=True)
return {"path": str(target)}
# --- CUDA 런타임 (Windows) -----------------------------------------------------
def pypi_win_wheel(meta: dict[str, Any]) -> dict[str, Any]:
"""PyPI JSON 에서 win_amd64 휠 정보를 고른다."""
for f in meta.get("urls", []):
if f.get("packagetype") == "bdist_wheel" and f["filename"].endswith("win_amd64.whl"):
return {"version": meta["info"]["version"], "filename": f["filename"], "url": f["url"],
"size": int(f["size"]), "sha256": f["digests"]["sha256"]}
raise WorkerError("no_wheel", f"{meta.get('info', {}).get('name')} 의 Windows 휠을 찾지 못했습니다")
def _fetch_json(url: str) -> dict[str, Any]:
with urllib.request.urlopen(url, timeout=30) as r:
return json.loads(r.read().decode("utf-8"))
def extract_dlls(wheel: Path, dest: Path) -> list[str]:
"""휠(zip) 안의 */bin/*.dll 만 dest 로 푼다."""
names = []
dest.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(wheel) as z:
for m in z.infolist():
parts = m.filename.split("/")
if len(parts) >= 2 and parts[-2] == "bin" and parts[-1].lower().endswith(".dll"):
with z.open(m) as src, open(dest / parts[-1], "wb") as dst:
shutil.copyfileobj(src, dst, 4 * MB)
names.append(parts[-1])
return names
def _stream_download(url: str, part: Path, size: int, on_bytes: Callable[[int], None]) -> None:
"""Range 로 이어받는 스트리밍 다운로드."""
have = part.stat().st_size if part.exists() else 0
if have > size:
part.unlink()
have = 0
if have == size:
return
req = urllib.request.Request(url, headers={"Range": f"bytes={have}-"} if have else {})
with urllib.request.urlopen(req, timeout=60) as r:
if have and r.status != 206: # 서버가 Range 를 무시하면 처음부터
have = 0
with open(part, "ab" if have else "wb") as f:
while True:
chunk = r.read(1 * MB)
if not chunk:
break
f.write(chunk)
on_bytes(len(chunk))
def download_cuda_runtime(emit: ProgressFn) -> dict[str, Any]:
dest = cuda_dir()
if not IS_WINDOWS:
return {"path": str(dest), "skipped": True,
"note": "Windows 전용입니다. 리눅스는 시스템 CUDA 나 pip 의 nvidia-* 패키지를 쓰세요."}
if (dest / CUDA_META).is_file():
return {"path": str(dest), "already": True}
_claim("cuda_runtime")
try:
try:
metas = [_fetch_json(f"https://pypi.org/pypi/{p}/json") for p in CUDA_WHEELS]
except Exception as e: # noqa: BLE001
raise WorkerError("network", f"PyPI 에서 CUDA 런타임 정보를 가져오지 못했습니다: {e}") from e
wheels = [pypi_win_wheel(m) for m in metas]
total = sum(w["size"] for w in wheels)
tmp = dest / ".download"
tmp.mkdir(parents=True, exist_ok=True)
have = sum((tmp / (w["filename"] + ".part")).stat().st_size
for w in wheels if (tmp / (w["filename"] + ".part")).exists())
_check_disk(dest, (total - have) + int(total * 2.5)) # 휠 + 압축 해제된 DLL
reporter = ProgressReporter(emit, total)
done = [have]
def on_bytes(n: int) -> None:
done[0] += n
reporter.update(done[0])
dlls: list[str] = []
for w in wheels:
part = tmp / (w["filename"] + ".part")
for attempt in range(3):
try:
_stream_download(w["url"], part, w["size"], on_bytes)
break
except OSError as e:
if attempt == 2:
raise WorkerError("network", f"다운로드 실패 ({w['filename']}): {e}") from e
done[0] = sum((tmp / (x["filename"] + ".part")).stat().st_size
for x in wheels if (tmp / (x["filename"] + ".part")).exists())
time.sleep(2 * (attempt + 1))
reporter.update(done[0], force=True, stage="verify")
if _sha256(part) != w["sha256"]:
part.unlink(missing_ok=True)
raise WorkerError("verify_failed", f"해시가 맞지 않습니다: {w['filename']}. 다시 다운로드하세요.")
reporter.update(done[0], force=True, stage="extract")
dlls += extract_dlls(part, dest)
part.unlink(missing_ok=True)
shutil.rmtree(tmp, ignore_errors=True)
(dest / CUDA_META).write_text(
json.dumps({"wheels": [{k: w[k] for k in ("filename", "version", "sha256")} for w in wheels],
"dlls": dlls, "created": int(time.time())}, ensure_ascii=False),
encoding="utf-8",
)
return {"path": str(dest), "dlls": dlls, "restart_required": True}
finally:
_release("cuda_runtime")

193
worker/gvr_worker/noise.py Normal file
View File

@@ -0,0 +1,193 @@
"""잡음 판정 4단계 (보고서 4-3): ① VAD → ② no_speech → ③ 환각 문구 → ④ 반복.
noise_sensitivity(0~1) 가 클수록 기준이 엄격해져 잡음으로 쉽게 판정된다.
"""
from __future__ import annotations
import re
import zlib
from collections import Counter
from dataclasses import dataclass
from typing import Iterable
# 한국어 Whisper 가 무음·키보드·숨소리에서 자주 지어내는 문장 (공백·문장부호 제거 후 비교)
HALLUCINATION_PHRASES: list[str] = [
"시청해주셔서감사합니다",
"시청해주셔서고맙습니다",
"시청해주신여러분감사합니다",
"봐주셔서감사합니다",
"영상봐주셔서감사합니다",
"끝까지시청해주셔서감사합니다",
"구독과좋아요",
"구독좋아요",
"구독과좋아요부탁드립니다",
"구독좋아요알림설정",
"좋아요와구독",
"알림설정까지",
"구독버튼",
"채널에가입",
"다음영상에서만나요",
"다음영상에서뵙겠습니다",
"다음시간에만나요",
"다음에또만나요",
"오늘도시청해주셔서",
"mbc뉴스",
"kbs뉴스",
"sbs뉴스",
"jtbc뉴스",
"ytn뉴스",
"mbn뉴스",
"뉴스데스크",
"뉴스는여기까지",
"이덕영입니다",
"기자입니다",
"자막제공",
"자막제공배달의민족",
"자막제공및광고",
"자막제작",
"자막by",
"한글자막",
"번역자막",
"자막은설정에서",
"제작지원",
"후원해주신",
"광고를포함하고",
"유료광고",
"여러분안녕하세요",
"이영상은",
"amaraorg",
"벨소리",
]
# 짧고 신뢰도 낮은 발화에서만 환각으로 보는 문장 (실제로도 자주 말하는 표현이라 조건부)
WEAK_PHRASES: list[str] = [
"감사합니다",
"고맙습니다",
"수고하셨습니다",
"안녕하세요",
"안녕히계세요",
"네감사합니다",
"감사합니다감사합니다",
"잘먹겠습니다",
"잘먹었습니다",
"아멘",
"음악",
"박수",
"웃음",
]
_NORM_RE = re.compile(r"[\s\W_]+", re.UNICODE)
_LAUGH_RE = re.compile(r"^[ㅋㅎㅠㅜㄷ]{3,}$")
_BRACKET_RE = re.compile(r"^[\[((♪].*[\]))♪]$")
def normalize(text: str) -> str:
return _NORM_RE.sub("", text).lower()
@dataclass
class SegInfo:
no_speech_prob: float
avg_logprob: float
compression_ratio: float
@dataclass
class Thresholds:
vad_ratio: float
vad_min_speech_s: float
no_speech_prob: float
logprob: float
weak_conf: float
weak_max_s: float
repeat_runs: int
token_dominance: float
compression: float
def thresholds(sensitivity: float) -> Thresholds:
s = min(max(float(sensitivity), 0.0), 1.0)
return Thresholds(
vad_ratio=0.03 + 0.17 * s, # 0.5 → 0.115
vad_min_speech_s=0.08 + 0.14 * s, # 0.5 → 0.15s
no_speech_prob=0.85 - 0.3 * s, # 0.5 → 0.70
logprob=-1.3 + 0.6 * s, # 0.5 → -1.0
weak_conf=0.3 + 0.4 * s, # 0.5 → 0.5
weak_max_s=1.5 + 1.5 * s, # 0.5 → 2.25s
repeat_runs=max(2, round(6 - 4 * s)), # 0.5 → 4번 반복(=5회 등장)
token_dominance=0.75 - 0.3 * s, # 0.5 → 0.6
compression=2.8 - 0.8 * s, # 0.5 → 2.4
)
def judge_vad(speech_ratio: float, speech_s: float, sensitivity: float) -> bool:
t = thresholds(sensitivity)
return speech_ratio < t.vad_ratio or speech_s < t.vad_min_speech_s
def judge_no_speech(segs: list[SegInfo], text: str, sensitivity: float) -> bool:
if not segs or not normalize(text):
return True
t = thresholds(sensitivity)
return all(s.no_speech_prob > t.no_speech_prob and s.avg_logprob < t.logprob for s in segs)
def _covered(norm: str, phrases: Iterable[str]) -> int:
covered = 0
rest = norm
for p in sorted(phrases, key=len, reverse=True):
if p in rest:
covered += len(p) * rest.count(p)
rest = rest.replace(p, "")
return covered
def judge_hallucination(text: str, confidence: float, duration_s: float, sensitivity: float) -> bool:
raw = text.strip()
norm = normalize(raw)
if not norm:
return False
if _LAUGH_RE.match(norm) or _BRACKET_RE.match(raw):
return True
t = thresholds(sensitivity)
# 강한 문구: 문장 대부분(50% 이상)을 차지하면 환각
if _covered(norm, HALLUCINATION_PHRASES) >= 0.5 * len(norm):
return True
# 약한 문구: 짧고 신뢰도 낮을 때 문장 전체가 그 문구면 환각
if norm in WEAK_PHRASES and duration_s <= t.weak_max_s and confidence < t.weak_conf:
return True
return False
def judge_repetition(text: str, segs: list[SegInfo], sensitivity: float) -> bool:
norm = normalize(text)
if len(norm) < 6:
return False
t = thresholds(sensitivity)
# 같은 1~10자 덩어리가 연속으로 repeat_runs 번 이상 더 반복
if re.search(r"(.{1,10}?)\1{%d,}" % t.repeat_runs, norm):
return True
tokens = [normalize(w) for w in text.split() if normalize(w)]
if len(tokens) >= 5:
_, n = Counter(tokens).most_common(1)[0]
if n / len(tokens) >= t.token_dominance:
return True
if len(norm) >= 20:
b = norm.encode("utf-8")
if len(b) / len(zlib.compress(b)) > t.compression:
return True
return any(s.compression_ratio > t.compression + 0.4 for s in segs) and len(norm) >= 12
def judge_text(
text: str, segs: list[SegInfo], confidence: float, duration_s: float, sensitivity: float
) -> str | None:
"""②~④ 단계. 잡음이면 사유 문자열, 아니면 None."""
if judge_no_speech(segs, text, sensitivity):
return "no_speech"
if judge_hallucination(text, confidence, duration_s, sensitivity):
return "hallucination"
if judge_repetition(text, segs, sensitivity):
return "repetition"
return None

307
worker/gvr_worker/ocr.py Normal file
View File

@@ -0,0 +1,307 @@
"""롤 인게임 채팅 화면 OCR (Windows 전용 캡처/OCR, 줄 파싱은 플랫폼 무관).
- 창 찾기: user32 EnumWindows/GetWindowTextW → GetClientRect/ClientToScreen
- 캡처: mss (테두리 없는 창/창 모드에서 동작. '전체 화면(독점)'은 검은 화면이 잡힐 수 있어
게임 설정에서 '테두리 없음' 을 권장)
- 채팅 영역이 바뀐 프레임에서만 Windows.Media.Ocr(ko) 실행
- 같은 (보낸 사람, 내용, 게임 시각) 줄은 한 번만 보낸다
"""
from __future__ import annotations
import asyncio
import logging
import re
import threading
import time
from collections import deque
from typing import Any, Callable
import numpy as np
from .paths import IS_WINDOWS
from .protocol import WorkerError
log = logging.getLogger(__name__)
LANG_MISSING_MSG = (
"Windows 한국어 OCR 이 설치되어 있지 않습니다. 설정 > 시간 및 언어 > 언어 및 지역 > 한국어 > 언어 옵션 > "
"'광학 문자 인식(OCR)' 을 설치하거나, 관리자 PowerShell 에서 "
"Add-WindowsCapability -Online -Name \"Language.OCR~~~ko-KR~0.0.1.0\" 을 실행하세요."
)
# --- 채팅 줄 파싱 --------------------------------------------------------------
CHANNELS = {
"팀": "team", "team": "team", "아군": "team",
"전체": "all", "all": "all", "모두": "all",
"파티": "party", "party": "party",
}
_TIME = r"\[?\s*(?P<time>\d{1,2}\s*:\s*\d{2}(?:\s*:\s*\d{2})?)\s*\]"
_CHAN = r"\[\s*(?P<chan>팀|전체|파티|아군|모두|[Tt]eam|[Aa]ll|[Pp]arty)\s*\]"
LINE_RE = re.compile(
rf"^\s*(?:{_TIME}\s*)?(?:{_CHAN}\s*)?"
r"(?P<sender>[^\[\]()::]{1,32}?)\s*(?:\(\s*(?P<champ>[^()]{1,24}?)\s*\))?\s*[::](?!\d)\s*(?P<msg>.+?)\s*$"
)
SYSTEM_RE = re.compile(rf"^\s*(?:{_TIME}\s*)?(?P<msg>.+?)\s*$")
def _norm_time(t: str | None) -> str | None:
return re.sub(r"\s+", "", t) if t else None
def time_to_seconds(t: str | None) -> float | None:
""""12:34" → 754.0, "1:02:03" → 3723.0."""
if not t:
return None
try:
parts = [int(x) for x in t.split(":")]
except ValueError:
return None
sec = 0
for x in parts:
sec = sec * 60 + x
return float(sec)
def seconds_to_time(sec: float) -> str:
s = int(sec)
h, m, s = s // 3600, (s % 3600) // 60, s % 60
return f"{h}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
def parse_chat_line(text: str) -> dict[str, Any] | None:
"""롤 채팅 한 줄 → {game_time, game_time_s, channel, sender, champion, message}. 빈 줄은 None."""
line = text.replace("​", "").strip()
if not line:
return None
m = LINE_RE.match(line)
if m and m.group("msg") and m.group("sender").strip():
chan = m.group("chan")
gt = _norm_time(m.group("time"))
return {
"game_time": gt,
"game_time_s": time_to_seconds(gt),
"channel": CHANNELS[chan.lower()] if chan else "team",
"sender": m.group("sender").strip(),
"champion": m.group("champ").strip() if m.group("champ") else None,
"message": m.group("msg"),
}
s = SYSTEM_RE.match(line)
gt = _norm_time(s.group("time")) if s else None
return {
"game_time": gt,
"game_time_s": time_to_seconds(gt),
"channel": "system",
"sender": None,
"champion": None,
"message": s.group("msg") if s else line,
}
class Deduper:
"""최근 본 (보낸 사람, 내용, 게임 시각) 키를 기억해 같은 줄을 한 번만 통과시킨다."""
def __init__(self, size: int = 500) -> None:
self._q: deque[tuple[Any, ...]] = deque()
self._set: set[tuple[Any, ...]] = set()
self._size = size
def first_time(self, parsed: dict[str, Any]) -> bool:
key = (parsed.get("sender"), re.sub(r"\s+", "", parsed.get("message") or ""), parsed.get("game_time"))
if key in self._set:
return False
self._set.add(key)
self._q.append(key)
if len(self._q) > self._size:
self._set.discard(self._q.popleft())
return True
def frame_changed(prev: np.ndarray | None, cur: np.ndarray, threshold: float = 2.0) -> bool:
"""축소한 회색조 프레임의 평균 절대 차이로 변화 판단."""
if prev is None or prev.shape != cur.shape:
return True
return float(np.mean(np.abs(prev.astype(np.int16) - cur.astype(np.int16)))) > threshold
def _thumb(bgra: np.ndarray) -> np.ndarray:
gray = bgra[..., :3].mean(axis=2)
return gray[::4, ::4].astype(np.uint8)
# --- Windows 창 · OCR ---------------------------------------------------------
def find_window_client_rect(title: str) -> tuple[int, int, int, int] | None:
"""창 제목(완전 일치 우선, 없으면 포함)으로 찾아 클라이언트 영역의 화면 좌표 (x, y, w, h)."""
if not IS_WINDOWS:
return None
import ctypes
from ctypes import wintypes
user32 = ctypes.windll.user32 # type: ignore[attr-defined]
found: list[tuple[int, str]] = []
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
def cb(hwnd: int, _lp: int) -> bool:
if user32.IsWindowVisible(hwnd) and not user32.IsIconic(hwnd):
n = user32.GetWindowTextLengthW(hwnd)
if n:
buf = ctypes.create_unicode_buffer(n + 1)
user32.GetWindowTextW(hwnd, buf, n + 1)
if title in buf.value:
found.append((hwnd, buf.value))
return True
user32.EnumWindows(cb, 0)
if not found:
return None
hwnd = next((h for h, t in found if t == title), found[0][0])
rect = wintypes.RECT()
if not user32.GetClientRect(hwnd, ctypes.byref(rect)):
return None
pt = wintypes.POINT(0, 0)
user32.ClientToScreen(hwnd, ctypes.byref(pt))
w, h = rect.right - rect.left, rect.bottom - rect.top
return (pt.x, pt.y, w, h) if w > 0 and h > 0 else None
def _set_dpi_aware() -> None:
if not IS_WINDOWS:
return
import ctypes
try:
ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # type: ignore[attr-defined]
except Exception: # noqa: BLE001
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # type: ignore[attr-defined]
except Exception: # noqa: BLE001
pass
class WinOcr:
"""Windows.Media.Ocr 래퍼 (pywinrt)."""
def __init__(self, lang: str = "ko") -> None:
if not IS_WINDOWS:
raise WorkerError("ocr_unavailable", "화면 OCR 은 Windows 에서만 지원합니다")
try:
from winrt.windows.globalization import Language
from winrt.windows.graphics.imaging import BitmapPixelFormat, SoftwareBitmap
from winrt.windows.media.ocr import OcrEngine
from winrt.windows.storage.streams import DataWriter
except ImportError as e:
raise WorkerError("ocr_unavailable", f"Windows OCR 모듈(pywinrt)을 불러오지 못했습니다: {e}") from e
self._SoftwareBitmap = SoftwareBitmap
self._fmt = BitmapPixelFormat.BGRA8
self._DataWriter = DataWriter
language = Language(lang)
if not OcrEngine.is_language_supported(language):
raise WorkerError("ocr_lang_missing", LANG_MISSING_MSG)
engine = OcrEngine.try_create_from_language(language)
if engine is None:
raise WorkerError("ocr_lang_missing", LANG_MISSING_MSG)
self._engine = engine
self._loop = asyncio.new_event_loop()
def recognize(self, bgra: np.ndarray) -> list[str]:
h, w = bgra.shape[:2]
writer = self._DataWriter()
writer.write_bytes(np.ascontiguousarray(bgra, dtype=np.uint8).tobytes())
bitmap = self._SoftwareBitmap.create_copy_from_buffer(writer.detach_buffer(), self._fmt, w, h)
result = self._loop.run_until_complete(self._engine.recognize_async(bitmap))
return [line.text for line in result.lines]
def close(self) -> None:
self._loop.close()
OCR_MAX_DIM = 2600 # Windows.Media.Ocr 의 OcrEngine.MaxImageDimension 기본값
def _upscale(bgra: np.ndarray, factor: int = 2) -> np.ndarray:
"""작은 채팅 글씨 인식률을 높이려고 정수배 확대 (OCR 최대 크기를 넘지 않을 때만)."""
if max(bgra.shape[:2]) * factor > OCR_MAX_DIM:
return bgra
return np.repeat(np.repeat(bgra, factor, axis=0), factor, axis=1)
def load_image_bgra(path: str) -> np.ndarray:
from PIL import Image
with Image.open(path) as im:
rgba = np.asarray(im.convert("RGBA"))
return rgba[..., [2, 1, 0, 3]].copy()
def ocr_image(path: str, lang: str = "ko") -> dict[str, Any]:
eng = WinOcr(lang)
try:
img = load_image_bgra(path)
if img.shape[0] < 400:
img = _upscale(img)
lines = [ln for ln in eng.recognize(img) if ln.strip()]
finally:
eng.close()
return {"lines": [{"text": ln, "parsed": parse_chat_line(ln)} for ln in lines]}
# --- 백그라운드 캡처 루프 ------------------------------------------------------
class OcrSession:
def __init__(self, window_title: str, region: dict[str, float], fps: float, lang: str,
send: Callable[[dict[str, Any]], None]) -> None:
self.window_title = window_title
self.region = region
self.interval = 1.0 / min(max(float(fps), 0.5), 10.0)
self.send = send
self._stop = threading.Event()
_set_dpi_aware()
self.engine = WinOcr(lang) # 언어 미설치 등은 시작 시점에 오류로 돌려준다
self.thread = threading.Thread(target=self._run, name="gvr-ocr", daemon=True)
def start(self) -> None:
self.thread.start()
def stop(self) -> None:
self._stop.set()
self.thread.join(timeout=3)
def _status(self, state: str, last: list[str]) -> None:
if last[0] != state:
last[0] = state
self.send({"event": "ocr_status", "state": state})
def _run(self) -> None:
import mss
dedupe = Deduper()
prev: np.ndarray | None = None
last_state = [""]
try:
with mss.mss() as sct:
while not self._stop.is_set():
t0 = time.monotonic()
try:
rect = find_window_client_rect(self.window_title)
if rect is None:
self._status("window_not_found", last_state)
else:
self._status("capturing", last_state)
x, y, w, h = rect
r = self.region
box = {"left": x + int(r["x"] * w), "top": y + int(r["y"] * h),
"width": max(1, int(r["w"] * w)), "height": max(1, int(r["h"] * h))}
img = np.asarray(sct.grab(box)) # BGRA
thumb = _thumb(img)
if frame_changed(prev, thumb):
prev = thumb
for text in self.engine.recognize(_upscale(img)):
parsed = parse_chat_line(text)
if parsed and dedupe.first_time(parsed):
self.send({"event": "ocr_line", "ts": int(time.time() * 1000),
"text": text, "parsed": parsed})
except Exception as e: # noqa: BLE001 - 한 프레임 실패로 루프를 멈추지 않는다
log.warning("OCR 프레임 실패: %s", e)
self._status("error", last_state)
self._stop.wait(max(0.0, self.interval - (time.monotonic() - t0)))
finally:
self.engine.close()

View File

@@ -0,0 +1,47 @@
"""데이터 폴더 경로와 Windows CUDA DLL 경로 설정."""
from __future__ import annotations
import logging
import os
import sys
from pathlib import Path
log = logging.getLogger(__name__)
IS_WINDOWS = sys.platform == "win32"
def data_dir() -> Path:
"""GVR_DATA_DIR. 없으면 실행 파일(또는 작업 폴더) 옆 GVR-Data."""
env = os.environ.get("GVR_DATA_DIR")
if env:
return Path(env)
base = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path.cwd()
return base / "GVR-Data"
def models_dir() -> Path:
env = os.environ.get("GVR_MODELS_DIR")
return Path(env) if env else data_dir() / "models"
def cuda_dir() -> Path:
return data_dir() / "cuda"
_dll_handles: list[object] = []
def setup_cuda_dll_path() -> None:
"""Windows: 내려받은 cuBLAS/cuDNN DLL 폴더를 ctranslate2 import 전에 검색 경로에 넣는다."""
if not IS_WINDOWS:
return
d = cuda_dir()
if not d.is_dir():
return
try:
_dll_handles.append(os.add_dll_directory(str(d))) # type: ignore[attr-defined]
except OSError as e: # pragma: no cover - Windows 전용
log.warning("add_dll_directory 실패: %s", e)
os.environ["PATH"] = str(d) + os.pathsep + os.environ.get("PATH", "")

View File

@@ -0,0 +1,181 @@
"""JSON Lines 프로토콜: stdin 요청 읽기, stdout 응답/이벤트 쓰기, 요청 디스패치.
- stdout 에는 프로토콜 메시지만 쓴다 (UTF-8, 한 줄 = JSON 하나). 로그는 stderr.
- 요청 처리 방식(mode):
- "inline": 읽기 루프에서 바로 처리 (빠른 요청)
- "slot": 슬롯(realtime/precise)별 단일 스레드 큐. 같은 슬롯의 load/unload/transcribe 는
순서대로, 다른 슬롯끼리는 동시에 돈다.
- "thread": 별도 스레드 (download, train 처럼 오래 걸리고 진행 이벤트를 내는 요청)
- 잘못된 요청은 루프를 죽이지 않고 오류 응답으로 돌려준다.
"""
from __future__ import annotations
import json
import logging
import sys
import threading
import traceback
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any, Callable, Literal, TextIO
log = logging.getLogger(__name__)
Mode = Literal["inline", "slot", "thread"]
Handler = Callable[[dict[str, Any], "Context"], Any]
class WorkerError(Exception):
"""요청 단위 오류. {"ok":false,"error":{"code","message"}} 로 응답된다."""
def __init__(self, code: str, message: str) -> None:
super().__init__(message)
self.code = code
self.message = message
class Writer:
"""스레드 안전한 stdout JSON Lines 쓰기."""
def __init__(self, stream: TextIO) -> None:
self._stream = stream
self._lock = threading.Lock()
def send(self, obj: dict[str, Any]) -> None:
line = json.dumps(obj, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
with self._lock:
self._stream.write(line + "\n")
self._stream.flush()
@dataclass
class Context:
"""핸들러에 넘기는 요청 컨텍스트. emit() 으로 진행 이벤트를 보낸다."""
req_id: Any
writer: Writer
def emit(self, event: str, **fields: Any) -> None:
msg: dict[str, Any] = {"event": event}
if self.req_id is not None:
msg["id"] = self.req_id
msg.update(fields)
self.writer.send(msg)
@dataclass
class Route:
handler: Handler
mode: Mode
class Server:
def __init__(self, writer: Writer) -> None:
self.writer = writer
self.routes: dict[str, Route] = {}
self._slot_pools: dict[str, ThreadPoolExecutor] = {}
self._pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix="gvr-job")
self._stopping = threading.Event()
def route(self, op: str, mode: Mode = "inline") -> Callable[[Handler], Handler]:
def deco(fn: Handler) -> Handler:
self.routes[op] = Route(fn, mode)
return fn
return deco
# --- 응답 ---------------------------------------------------------------
def _reply_ok(self, req_id: Any, result: Any) -> None:
self.writer.send({"id": req_id, "ok": True, "result": result if result is not None else {}})
def _reply_err(self, req_id: Any, code: str, message: str) -> None:
self.writer.send({"id": req_id, "ok": False, "error": {"code": code, "message": message}})
def _run(self, route: Route, req: dict[str, Any]) -> None:
req_id = req.get("id")
try:
result = route.handler(req, Context(req_id, self.writer))
self._reply_ok(req_id, result)
except WorkerError as e:
self._reply_err(req_id, e.code, e.message)
except Exception as e: # noqa: BLE001 - 경계에서 모든 예외를 오류 응답으로
log.error("op=%s 처리 중 예외\n%s", req.get("op"), traceback.format_exc())
self._reply_err(req_id, "internal", f"{type(e).__name__}: {e}")
def _slot_pool(self, slot: str) -> ThreadPoolExecutor:
pool = self._slot_pools.get(slot)
if pool is None:
pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix=f"gvr-slot-{slot}")
self._slot_pools[slot] = pool
return pool
# --- 디스패치 -------------------------------------------------------------
def handle_line(self, line: str) -> None:
line = line.strip()
if not line:
return
try:
req = json.loads(line)
except json.JSONDecodeError as e:
self._reply_err(None, "bad_json", f"JSON 파싱 실패: {e}")
return
if not isinstance(req, dict):
self._reply_err(None, "bad_request", "요청은 JSON 객체여야 합니다")
return
req_id = req.get("id")
op = req.get("op")
route = self.routes.get(op) if isinstance(op, str) else None
if route is None:
self._reply_err(req_id, "unknown_op", f"알 수 없는 op: {op!r}")
return
if route.mode == "inline":
self._run(route, req)
elif route.mode == "slot":
slot = req.get("slot")
if slot not in ("realtime", "precise"):
self._reply_err(req_id, "bad_request", "slot 은 realtime 또는 precise 여야 합니다")
return
self._slot_pool(slot).submit(self._run, route, req)
else:
self._pool.submit(self._run, route, req)
def stop(self) -> None:
self._stopping.set()
@property
def stopping(self) -> bool:
return self._stopping.is_set()
def serve(self, stdin: TextIO) -> None:
for line in stdin:
try:
self.handle_line(line)
except Exception: # noqa: BLE001 - 루프는 절대 죽지 않는다
log.error("요청 처리 루프 예외\n%s", traceback.format_exc())
if self._stopping.is_set():
break
self.shutdown_pools()
def shutdown_pools(self) -> None:
for pool in self._slot_pools.values():
pool.shutdown(wait=True, cancel_futures=True)
self._pool.shutdown(wait=False, cancel_futures=True)
def setup_stdio() -> tuple[TextIO, TextIO]:
"""stdin/stdout 을 UTF-8 로 고정한다 (Windows 기본 코드페이지 회피)."""
for s in (sys.stdin, sys.stdout, sys.stderr):
try:
kw = {"newline": "\n"} if s is sys.stdout else {} # Windows 에서도 \r\n 이 아닌 \n
s.reconfigure(encoding="utf-8", errors="replace", line_buffering=True, **kw) # type: ignore[union-attr]
except (AttributeError, ValueError):
pass
return sys.stdin, sys.stdout
def require(req: dict[str, Any], key: str, typ: type | tuple[type, ...] = str) -> Any:
val = req.get(key)
if val is None or not isinstance(val, typ) or (isinstance(val, str) and not val):
raise WorkerError("bad_request", f"'{key}' 필드가 필요합니다")
return val

105
worker/gvr_worker/r3dlog.py Normal file
View File

@@ -0,0 +1,105 @@
"""롤 게임 로그(*_r3dlog.txt)에서 채팅 줄 찾기.
2024년 12월 패치 전에는 `[팀] 이름 (챔피언): 내용` 형태 채팅이 r3dlog 에 남았다. 줄 앞에는
`000754.123| ALWAYS| ` 같은 경과 초 접두어가 붙을 수 있고, 있으면 game_time_s 로 쓴다.
지금 게임 PC 로그에 남는지는 r3dlog_check 로 확인한다.
"""
from __future__ import annotations
import re
import threading
from pathlib import Path
from typing import Any, Iterator
from .ocr import CHANNELS, seconds_to_time, time_to_seconds
CHAT_RE = re.compile(
r"(?:\[\s*(?P<time>\d{1,2}:\d{2}(?::\d{2})?)\s*\]\s*)?"
r"\[\s*(?P<chan>팀|전체|파티|아군|모두|[Tt]eam|[Aa]ll|[Pp]arty)\s*\]\s*"
r"(?P<sender>[^\[\]():|]{1,32}?)\s*(?:\(\s*(?P<champ>[^()]{1,24}?)\s*\))?\s*:\s*(?P<msg>.+?)\s*$"
)
LOG_TIME_RE = re.compile(r"^\s*(?P<t>\d+\.\d+)\s*\|")
def parse_r3d_line(line: str) -> dict[str, Any] | None:
"""r3dlog 한 줄 → {game_time, game_time_s, channel, sender, champion, message} 또는 None."""
m = CHAT_RE.search(line)
if not m:
return None
t = LOG_TIME_RE.match(line)
explicit = m.group("time")
if explicit:
game_time, game_time_s = explicit, time_to_seconds(explicit)
elif t:
game_time_s = float(t.group("t"))
game_time = seconds_to_time(game_time_s)
else:
game_time, game_time_s = None, None
return {
"game_time": game_time,
"game_time_s": game_time_s,
"channel": CHANNELS[m.group("chan").lower()],
"sender": m.group("sender").strip(),
"champion": m.group("champ").strip() if m.group("champ") else None,
"message": m.group("msg"),
}
def latest_log(logs_dir: str | Path, since_ms: float | None = None) -> Path | None:
"""가장 최근 *_r3dlog.txt. since_ms 가 있으면 그 뒤에 수정된 파일만."""
root = Path(logs_dir)
if not root.is_dir():
return None
files = [p for p in root.rglob("*_r3dlog.txt") if p.is_file()]
if since_ms is not None:
files = [p for p in files if p.stat().st_mtime * 1000 > since_ms]
return max(files, key=lambda p: p.stat().st_mtime) if files else None
def scan(path: Path, limit: int | None = None) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
p = parse_r3d_line(line)
if p:
out.append(p)
if limit and len(out) >= limit:
break
return out
def follow(path: Path, stop: threading.Event, from_start: bool = False, poll_s: float = 0.5
) -> Iterator[dict[str, Any]]:
"""tail -f 처럼 새로 붙는 줄에서 채팅을 꺼낸다. stop 이 설정되면 끝난다."""
with open(path, encoding="utf-8", errors="replace") as f:
if not from_start:
f.seek(0, 2)
buf = ""
while not stop.is_set():
chunk = f.readline()
if not chunk:
stop.wait(poll_s)
continue
buf += chunk
if not buf.endswith("\n"):
continue # 아직 덜 쓰인 줄
line, buf = buf, ""
p = parse_r3d_line(line)
if p:
yield p
def check(logs_dir: str) -> dict[str, Any]:
path = latest_log(logs_dir)
if path is None:
return {"found_chat": False, "file": None, "sample": []}
sample = scan(path, limit=5)
return {"found_chat": bool(sample), "file": str(path), "sample": sample}
def read(logs_dir: str, since_ms: float | None = None) -> dict[str, Any]:
path = latest_log(logs_dir, since_ms)
if path is None:
return {"file": None, "lines": []}
return {"file": str(path), "lines": scan(path)}

197
worker/gvr_worker/stt.py Normal file
View File

@@ -0,0 +1,197 @@
"""STT 슬롯(realtime/precise) 관리와 변환 파이프라인.
정규화 → VAD 말소리 비율 → faster-whisper → 잡음 판정 → 교정 사전 순서.
"""
from __future__ import annotations
import gc
import logging
import math
import os
import threading
import time
from dataclasses import dataclass
from typing import Any
import numpy as np
from . import audio as audio_mod
from . import noise
from .dictionary import Corrector
from .models import resolve_model_path
from .protocol import WorkerError
log = logging.getLogger(__name__)
SLOTS = ("realtime", "precise")
BEAM = {"realtime": 3, "precise": 5}
VAD_MIN_SILENCE_MS = 500
@dataclass
class LoadedModel:
name: str
path: str
device: str
compute_type: str
model: Any # faster_whisper.WhisperModel
def _vad_speech(audio: np.ndarray) -> tuple[float, float]:
"""(말소리 비율, 말소리 초). faster-whisper 내장 Silero VAD 사용."""
from faster_whisper.vad import VadOptions, get_speech_timestamps
if audio.size == 0:
return 0.0, 0.0
opts = VadOptions(min_silence_duration_ms=VAD_MIN_SILENCE_MS, min_speech_duration_ms=100, speech_pad_ms=30)
stamps = get_speech_timestamps(audio, opts, sampling_rate=audio_mod.SR)
speech = sum(s["end"] - s["start"] for s in stamps) / audio_mod.SR
return min(speech / (audio.size / audio_mod.SR), 1.0), speech
def _is_cuda_dll_error(msg: str) -> bool:
m = msg.lower()
return any(k in m for k in ("cublas", "cudnn", ".dll", "libcuda", "cuda driver", "no cuda", "cudart"))
class SttEngine:
def __init__(self) -> None:
self.slots: dict[str, LoadedModel | None] = {s: None for s in SLOTS}
self._lock = threading.Lock()
# --- 적재 ---------------------------------------------------------------
def load(self, slot: str, model: str, device: str | None, compute_type: str | None,
cpu_threads: int = 0) -> dict[str, Any]:
from faster_whisper import WhisperModel
from .gpu import gpu_list
path = resolve_model_path(model)
fallback = None
if device in (None, "auto"):
device = "cuda" if gpu_list() else "cpu"
elif device == "cuda" and not gpu_list():
device, fallback = "cpu", "no_gpu"
if device not in ("cuda", "cpu"):
raise WorkerError("bad_request", "device 는 cuda 또는 cpu 여야 합니다")
if not compute_type or fallback:
compute_type = "float16" if device == "cuda" else "int8"
self.unload(slot) # VRAM 먼저 비우기
t0 = time.monotonic()
try:
m = WhisperModel(str(path), device=device, compute_type=compute_type, cpu_threads=cpu_threads)
except Exception as e: # noqa: BLE001
msg = str(e)
if device == "cuda" and _is_cuda_dll_error(msg):
raise WorkerError(
"cuda_runtime_missing",
f"CUDA 런타임(cuBLAS/cuDNN)을 불러오지 못했습니다. CUDA 런타임을 다운로드한 뒤 다시 시도하세요. ({msg})",
) from e
raise WorkerError("load_failed", f"모델을 불러오지 못했습니다: {msg}") from e
with self._lock:
self.slots[slot] = LoadedModel(model, str(path), device, compute_type, m)
res: dict[str, Any] = {"slot": slot, "model": model, "device": device, "compute_type": compute_type,
"path": str(path), "elapsed_ms": int((time.monotonic() - t0) * 1000)}
if fallback:
res["fallback"] = fallback
return res
def unload(self, slot: str) -> dict[str, Any]:
with self._lock:
had = self.slots.get(slot)
self.slots[slot] = None
if had is not None:
del had
gc.collect()
return {"slot": slot, "unloaded": True}
def status(self) -> dict[str, Any]:
return {s: (None if m is None else {"model": m.name, "device": m.device, "compute_type": m.compute_type})
for s, m in self.slots.items()}
# --- 변환 ---------------------------------------------------------------
def transcribe(self, req: dict[str, Any]) -> dict[str, Any]:
t0 = time.monotonic()
slot = req["slot"]
lm = self.slots.get(slot)
if lm is None:
raise WorkerError("model_not_loaded", f"'{slot}' 슬롯에 모델이 적재되지 않았습니다")
path = req.get("path")
if not isinstance(path, str) or not path:
raise WorkerError("bad_request", "'path' 필드가 필요합니다")
if not os.path.isfile(path):
raise WorkerError("file_not_found", f"오디오 파일이 없습니다: {path}")
sensitivity = float(req.get("noise_sensitivity") if req.get("noise_sensitivity") is not None else 0.5)
try:
prep = audio_mod.prepare(
path,
target_lufs=float(req.get("target_lufs") if req.get("target_lufs") is not None else -18.0),
profile_lufs=req.get("profile_lufs"),
use_denoise=bool(req.get("denoise")),
)
except Exception as e: # noqa: BLE001 - 손상된 파일 등
raise WorkerError("decode_failed", f"오디오를 읽지 못했습니다: {e}") from e
speech_ratio, speech_s = _vad_speech(prep.audio)
result: dict[str, Any] = {
"text": None, "raw_text": None, "words": [], "noise": False, "noise_reason": None,
"confidence": None, "lufs": prep.lufs, "gain_db": prep.gain_db,
"speech_ratio": round(speech_ratio, 3), "duration_s": prep.duration_s, "model": lm.name,
}
def done(noise_reason: str | None = None) -> dict[str, Any]:
if noise_reason:
result.update(noise=True, noise_reason=noise_reason, text=None, words=[])
result["elapsed_ms"] = int((time.monotonic() - t0) * 1000)
return result
# ① VAD: 말소리가 거의 없으면 Whisper 를 돌리지 않는다 (환각 방지 + GPU 절약)
if noise.judge_vad(speech_ratio, speech_s, sensitivity):
return done("vad")
hotwords = req.get("hotwords") or None
try:
segments, _info = lm.model.transcribe(
prep.audio,
language="ko",
task="transcribe",
beam_size=BEAM.get(slot, 5),
word_timestamps=True,
vad_filter=True,
vad_parameters={"min_silence_duration_ms": VAD_MIN_SILENCE_MS},
hotwords=hotwords if isinstance(hotwords, str) else None,
initial_prompt=req.get("initial_prompt") or None,
condition_on_previous_text=False,
)
segs = list(segments)
except Exception as e: # noqa: BLE001
raise WorkerError("transcribe_failed", f"음성 변환 실패: {e}") from e
words: list[dict[str, Any]] = []
for seg in segs:
for w in seg.words or []:
text = w.word.strip()
if not text:
continue
lead = w.word[: len(w.word) - len(w.word.lstrip())]
words.append({"w": text, "s": round(w.start, 2), "e": round(w.end, 2),
"p": round(w.probability, 3), "lead": lead})
raw_text = "".join(s.text for s in segs).strip()
infos = [noise.SegInfo(s.no_speech_prob, s.avg_logprob, s.compression_ratio) for s in segs]
confidence = float(np.mean([math.exp(s.avg_logprob) for s in segs])) if segs else 0.0
result.update(raw_text=raw_text or None, confidence=round(confidence, 3))
reason = noise.judge_text(raw_text, infos, confidence, prep.duration_s, sensitivity)
if reason:
return done(reason)
corrector = Corrector.from_request(req.get("corrections"), req.get("dictionary"))
if words:
text, out_words = corrector.correct_words(words)
else:
text, out_words = corrector.correct_text(raw_text), []
result.update(text=text, words=out_words)
return done()

3
worker/pytest.ini Normal file
View File

@@ -0,0 +1,3 @@
[pytest]
testpaths = tests
addopts = -p no:cacheprovider --basetemp=.pytest-tmp

View File

@@ -0,0 +1,4 @@
-r requirements.txt
pytest==9.1.1
pyinstaller==6.22.3
edge-tts==7.3.1 # tests/make_fixtures.py 용

19
worker/requirements.txt Normal file
View File

@@ -0,0 +1,19 @@
# 겜녹이 STT 워커 런타임 의존성 (Python 3.11)
faster-whisper==1.2.1
ctranslate2==4.8.3 # Windows 휠은 CUDA 12.8 + cuDNN 9 로 빌드됨 (RTX 50 / sm_120 지원)
av==18.1.0
onnxruntime==1.31.0 # Silero VAD
huggingface_hub==2.2.0
nvidia-ml-py==13.615.71
pyloudnorm==0.2.0
numpy==2.4.6
scipy==1.17.1
mss==10.2.0
pillow==12.3.0; sys_platform == "win32"
winrt-runtime==3.2.1; sys_platform == "win32"
winrt-Windows.Foundation==3.2.1; sys_platform == "win32"
winrt-Windows.Foundation.Collections==3.2.1; sys_platform == "win32"
winrt-Windows.Globalization==3.2.1; sys_platform == "win32"
winrt-Windows.Graphics.Imaging==3.2.1; sys_platform == "win32"
winrt-Windows.Media.Ocr==3.2.1; sys_platform == "win32"
winrt-Windows.Storage.Streams==3.2.1; sys_platform == "win32"

6
worker/run_worker.py Normal file
View File

@@ -0,0 +1,6 @@
"""PyInstaller 진입점 (gvr-worker.exe)."""
from gvr_worker.main import main
if __name__ == "__main__":
main()

95
worker/tests/conftest.py Normal file
View File

@@ -0,0 +1,95 @@
from __future__ import annotations
import json
import os
import queue
import subprocess
import sys
import threading
from pathlib import Path
from typing import Any
import pytest
WORKER_DIR = Path(__file__).resolve().parent.parent
FIXTURES = Path(__file__).resolve().parent / "fixtures"
HF_TINY = Path.home() / ".cache/huggingface/hub/models--Systran--faster-whisper-tiny/snapshots"
sys.path.insert(0, str(WORKER_DIR))
class WorkerProc:
"""python -m gvr_worker 를 자식 프로세스로 띄워 JSON Lines 로 대화한다."""
def __init__(self, env: dict[str, str]) -> None:
self.proc = subprocess.Popen(
[sys.executable, "-m", "gvr_worker"], cwd=WORKER_DIR, env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding="utf-8",
)
self.lines: queue.Queue[dict[str, Any]] = queue.Queue()
self.raw: list[str] = []
self.stderr: list[str] = []
threading.Thread(target=self._read, daemon=True).start()
threading.Thread(target=self._drain_stderr, daemon=True).start()
def _drain_stderr(self) -> None:
for line in self.proc.stderr: # type: ignore[union-attr]
self.stderr.append(line)
def _read(self) -> None:
for line in self.proc.stdout: # type: ignore[union-attr]
self.raw.append(line)
self.lines.put(json.loads(line)) # stdout 은 항상 유효한 JSON 이어야 한다
def send(self, obj: dict[str, Any] | str) -> None:
text = obj if isinstance(obj, str) else json.dumps(obj, ensure_ascii=False)
self.proc.stdin.write(text + "\n") # type: ignore[union-attr]
self.proc.stdin.flush() # type: ignore[union-attr]
def recv(self, timeout: float = 60) -> dict[str, Any]:
return self.lines.get(timeout=timeout)
def request(self, obj: dict[str, Any], timeout: float = 120) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""응답과 그 사이에 온 같은 id 의 이벤트들을 돌려준다."""
self.send(obj)
events = []
while True:
msg = self.recv(timeout)
if msg.get("id") != obj.get("id"):
continue
if "event" in msg:
events.append(msg)
continue
return msg, events
def close(self) -> int:
if self.proc.poll() is None:
try:
self.send({"id": "bye", "op": "shutdown"})
except (BrokenPipeError, OSError):
pass
try:
return self.proc.wait(timeout=30)
except subprocess.TimeoutExpired:
self.proc.kill()
return self.proc.wait()
@pytest.fixture(scope="session")
def models_dir(tmp_path_factory: pytest.TempPathFactory) -> Path:
"""tiny 모델을 HF 캐시에서 링크하거나 (없으면 테스트 중 download 로 받음)."""
d = tmp_path_factory.mktemp("models")
snaps = sorted(HF_TINY.glob("*/model.bin")) if HF_TINY.is_dir() else []
if snaps:
(d / "tiny").symlink_to(snaps[0].parent, target_is_directory=True)
return d
@pytest.fixture(scope="session")
def worker(models_dir: Path, tmp_path_factory: pytest.TempPathFactory):
env = {**os.environ, "GVR_DATA_DIR": str(tmp_path_factory.mktemp("data")),
"GVR_MODELS_DIR": str(models_dir), "PYTHONIOENCODING": "utf-8"}
w = WorkerProc(env)
yield w
w.close()

Binary file not shown.

BIN
worker/tests/fixtures/silence.ogg vendored Normal file

Binary file not shown.

BIN
worker/tests/fixtures/speech_ko.ogg vendored Normal file

Binary file not shown.

Binary file not shown.

BIN
worker/tests/fixtures/white_noise.ogg vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,71 @@
"""테스트 오디오 픽스처 생성 (edge-tts + ffmpeg 필요, 인터넷 필요). 결과는 저장소에 커밋되어 있다.
.venv/bin/python tests/make_fixtures.py
"""
from __future__ import annotations
import asyncio
import subprocess
import tempfile
import wave
from pathlib import Path
import numpy as np
FIX = Path(__file__).parent / "fixtures"
SENTENCE = "레이즈 궁 빠졌어 B 사이트 로테 하자"
OPUS = ["-ac", "1", "-ar", "48000", "-c:a", "libopus", "-b:a", "32k"]
def ffmpeg(*args: str) -> None:
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", *args], check=True)
def write_wav(path: Path, x: np.ndarray, sr: int = 48000) -> None:
pcm = (np.clip(x, -1, 1) * 32767).astype(np.int16)
with wave.open(str(path), "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(sr)
w.writeframes(pcm.tobytes())
async def tts(text: str, out: Path) -> None:
import edge_tts
await edge_tts.Communicate(text, "ko-KR-SunHiNeural").save(str(out))
def main() -> None:
FIX.mkdir(exist_ok=True)
rng = np.random.default_rng(0)
with tempfile.TemporaryDirectory(dir=Path.home() / ".tmp") as td:
tmp = Path(td)
mp3 = tmp / "s.mp3"
asyncio.run(tts(SENTENCE, mp3))
ffmpeg("-i", str(mp3), *OPUS, str(FIX / "speech_ko.ogg"))
ffmpeg("-i", str(mp3), "-af", "volume=-30dB", *OPUS, str(FIX / "speech_ko_quiet.ogg"))
sr = 48000
# 무음 + 키보드 딸깍 소리 (짧은 감쇠 잡음 버스트)
x = rng.normal(0, 0.0005, int(2.5 * sr))
for t in np.arange(0.2, 2.3, 0.17) + rng.uniform(-0.03, 0.03, 13):
i = int(t * sr)
n = int(0.012 * sr)
x[i : i + n] += rng.normal(0, 0.25, n) * np.exp(-np.linspace(0, 8, n))
wav = tmp / "c.wav"
write_wav(wav, x)
ffmpeg("-i", str(wav), *OPUS, str(FIX / "keyboard_clicks.ogg"))
# 백색 잡음
write_wav(wav, rng.normal(0, 0.08, int(2.0 * sr)))
ffmpeg("-i", str(wav), *OPUS, str(FIX / "white_noise.ogg"))
# 완전 무음에 가까운 소리
write_wav(wav, rng.normal(0, 0.0002, int(1.5 * sr)))
ffmpeg("-i", str(wav), *OPUS, str(FIX / "silence.ogg"))
for p in sorted(FIX.glob("*.ogg")):
print(p.name, p.stat().st_size)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,41 @@
from __future__ import annotations
import numpy as np
from conftest import FIXTURES
from gvr_worker import audio
def test_limiter_never_exceeds_ceiling() -> None:
rng = np.random.default_rng(1)
x = (rng.normal(0, 0.6, 16000)).astype(np.float32)
y = audio.limit(x)
assert np.max(np.abs(y)) <= 10 ** (-1 / 20) + 1e-6
quiet = x * 0.1
assert np.array_equal(audio.limit(quiet), quiet) # 피크가 낮으면 손대지 않음
def test_prepare_normalizes_quiet_speech() -> None:
loud = audio.prepare(str(FIXTURES / "speech_ko.ogg"))
quiet = audio.prepare(str(FIXTURES / "speech_ko_quiet.ogg"))
assert loud.lufs is not None and quiet.lufs is not None
assert abs(loud.lufs - quiet.lufs - 30) < 2
assert quiet.gain_db == 24.0 # 클램프 상한
assert np.max(np.abs(quiet.audio)) <= 10 ** (-1 / 20) + 1e-6
assert abs(loud.duration_s - quiet.duration_s) < 0.05
def test_short_utterance_uses_profile(tmp_path) -> None:
import subprocess
src = tmp_path / "short.ogg"
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(FIXTURES / "speech_ko.ogg"), "-t", "0.3",
"-c:a", "libopus", str(src)], check=True)
p = audio.prepare(str(src), target_lufs=-18, profile_lufs=-30)
assert p.lufs == -30 and p.gain_db == 12
def test_denoise_keeps_length() -> None:
a = audio.decode(str(FIXTURES / "white_noise.ogg"))
d = audio.denoise(a)
assert d.shape == a.shape and np.sqrt(np.mean(d**2)) < np.sqrt(np.mean(a**2))

View File

@@ -0,0 +1,58 @@
from __future__ import annotations
from gvr_worker.dictionary import Corrector, jamo, jamo_similarity
DICT = ["레이즈", "로테", "오퍼레이터", "제트", "세이지", "소바", "오멘", "킬조이", "사이퍼", "스파이크", "사이트",
"어센트", "바인드", "헤이븐", "팬텀", "밴달", "에코", "세이브", "하버", "게코", "네온", "페이드"]
def make() -> Corrector:
return Corrector.from_request([{"from": "비 싸이트", "to": "B 사이트"}], DICT)
def test_report_example() -> None:
assert (make().correct_text("레이저 궁 빠졌어 비 싸이트 로태 하자 나 오퍼래이터 삼")
== "레이즈 궁 빠졌어 B 사이트 로테 하자 나 오퍼레이터 삼")
def test_jamo() -> None:
assert jamo("각") == "ㄱㅏㄱ"
assert jamo("왔") == "ㅇㅗㅏㅆ" # 겹모음 분해
assert jamo("값A") == "ㄱㅏㅂㅅa"
assert jamo_similarity("로태", "로테") > 0.9
assert jamo_similarity("빠졌어", "바인드") < 0.5
def test_particles_and_punctuation() -> None:
c = make()
assert c.correct_text("레이저가 스파이크를 설치했어.") == "레이즈가 스파이크를 설치했어."
assert c.correct_text("오맨이랑 같이 가자!") == "오멘이랑 같이 가자!"
assert c.correct_text("비 싸이트로 가자") == "B 사이트로 가자"
def test_no_overcorrection() -> None:
c = make()
text = "지금 빨리 가자 나 진짜 배고파 하자"
assert c.correct_text(text) == text
assert c.correct_text("세이브 하자") == "세이브 하자" # 사전 단어는 그대로
def test_words_keep_timestamps() -> None:
words = [
{"w": "레이저", "s": 0.1, "e": 0.5, "p": 0.9, "lead": " "},
{"w": "비", "s": 0.6, "e": 0.7, "p": 0.4, "lead": " "},
{"w": "싸이트", "s": 0.7, "e": 1.1, "p": 0.8, "lead": " "},
{"w": "가자.", "s": 1.2, "e": 1.5, "p": 0.95, "lead": " "},
]
text, out = make().correct_words(words)
assert text == "레이즈 B 사이트 가자."
assert out == [
{"w": "레이즈", "s": 0.1, "e": 0.5, "p": 0.9},
{"w": "B 사이트", "s": 0.6, "e": 1.1, "p": 0.4},
{"w": "가자.", "s": 1.2, "e": 1.5, "p": 0.95},
]
def test_bad_input_is_ignored() -> None:
c = Corrector.from_request([{"from": 1}, "x", {"from": "", "to": "a"}], [None, "", "레이즈"]) # type: ignore[list-item]
assert c.correct_text("레이저") == "레이즈"

View File

@@ -0,0 +1,48 @@
"""파인튜닝 스크립트의 가벼운 부분 (torch 없이 도는 것만)."""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
FT = Path(__file__).resolve().parent.parent / "gvr_worker" / "finetune"
sys.path.insert(0, str(FT))
import build_dataset # noqa: E402
from common import cer, short_name # noqa: E402
def test_cer() -> None:
assert cer(["레이즈 궁 빠졌어"], ["레이즈궁 빠졌어."]) == 0.0
assert abs(cer(["레이즈 궁"], ["레이저 궁"]) - 1 / 4) < 1e-9
assert cer(["가나", "다라"], ["가나", "다마"]) == 0.25
def test_short_name() -> None:
assert short_name("openai/whisper-large-v3-turbo") == "large-v3-turbo"
assert short_name("openai/whisper-tiny") == "tiny"
def test_split_by_text_is_fixed(tmp_path: Path) -> None:
rows = []
for i in range(60):
wav = tmp_path / f"s{i}.wav"
wav.write_bytes(b"x")
rows.append({"audio": str(wav), "text": f"문장 {i % 20}", "source": "synth"})
man = tmp_path / "m.jsonl"
man.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in rows), encoding="utf-8")
train, valid = build_dataset.build(str(man), None)
assert valid and train and len(train) + len(valid) == 60
assert not ({r["text"] for r in train} & {r["text"] for r in valid}) # 같은 문장이 양쪽에 없음
assert build_dataset.build(str(man), None) == (train, valid) # 매번 같은 분할
def test_run_respects_stop_file(tmp_path: Path) -> None:
(tmp_path / "finetune.stop").write_text("game")
out = subprocess.run([sys.executable, str(FT / "run.py"), "--data-dir", str(tmp_path)],
capture_output=True, text=True, encoding="utf-8", timeout=60)
assert out.returncode == 0
res = json.loads(out.stdout.strip().splitlines()[-1])["result"]
assert res["stopped"] is True and res["adopt"] is False

30
worker/tests/test_gpu.py Normal file
View File

@@ -0,0 +1,30 @@
from __future__ import annotations
from gvr_worker.gpu import parse_smi_csv, recommend
def g(mb: int, cc: str = "12.0") -> list[dict]:
return [{"index": 0, "name": "GPU", "vram_total_mb": mb, "vram_used_mb": 0, "compute_capability": cc}]
def test_vram_table() -> None:
r = recommend(g(16303))
assert (r["realtime"], r["precise"], r["compute_type"]) == ("large-v3-turbo", "large-v3", "float16")
assert r["budget_mb"] == 13200 and "16GB" in r["reason"] and r["precise_after_match"] is False
r = recommend(g(12282))
assert (r["realtime"], r["precise"], r["precise_after_match"]) == ("large-v3", "large-v3", True)
r = recommend(g(8188))
assert (r["realtime"], r["compute_type"]) == ("large-v3-turbo", "float16")
r = recommend(g(6144))
assert r["compute_type"] == "int8_float16" and "warning" in r
assert "warning" not in recommend(g(6144, "8.6"))
r = recommend(g(4096))
assert (r["realtime"], r["precise"]) == ("small", "medium")
r = recommend([])
assert r["device"] == "cpu" and r["supported"] is False
def test_parse_smi() -> None:
out = parse_smi_csv("0, NVIDIA GeForce RTX 5070 Ti, 16303, 1200, 581.15, 12.0\n", "13.0")
assert out == [{"index": 0, "name": "NVIDIA GeForce RTX 5070 Ti", "vram_total_mb": 16303, "vram_used_mb": 1200,
"driver": "581.15", "cuda_driver": "13.0", "compute_capability": "12.0"}]

View File

@@ -0,0 +1,70 @@
from __future__ import annotations
import time
import zipfile
import pytest
from gvr_worker import models
from gvr_worker.protocol import WorkerError
def test_pypi_win_wheel() -> None:
meta = {"info": {"name": "nvidia-cublas-cu12", "version": "12.9.2.10"}, "urls": [
{"packagetype": "bdist_wheel", "filename": "x-manylinux_2_27_x86_64.whl", "url": "u1", "size": 1,
"digests": {"sha256": "a"}},
{"packagetype": "bdist_wheel", "filename": "x-py3-none-win_amd64.whl", "url": "u2", "size": 2,
"digests": {"sha256": "b"}},
]}
assert models.pypi_win_wheel(meta) == {"version": "12.9.2.10", "filename": "x-py3-none-win_amd64.whl",
"url": "u2", "size": 2, "sha256": "b"}
with pytest.raises(WorkerError):
models.pypi_win_wheel({"info": {"name": "x", "version": "1"}, "urls": meta["urls"][:1]})
def test_extract_dlls(tmp_path) -> None:
whl = tmp_path / "w.whl"
with zipfile.ZipFile(whl, "w") as z:
z.writestr("nvidia/cublas/bin/cublas64_12.dll", b"dll")
z.writestr("nvidia/cublas/bin/cublasLt64_12.dll", b"dll2")
z.writestr("nvidia/cublas/lib/cublas.lib", b"lib")
z.writestr("nvidia/cublas/include/cublas.h", b"h")
out = tmp_path / "cuda"
assert sorted(models.extract_dlls(whl, out)) == ["cublas64_12.dll", "cublasLt64_12.dll"]
assert sorted(p.name for p in out.iterdir()) == ["cublas64_12.dll", "cublasLt64_12.dll"]
def test_resolve_and_list(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("GVR_MODELS_DIR", str(tmp_path))
monkeypatch.setenv("GVR_DATA_DIR", str(tmp_path / "data"))
with pytest.raises(WorkerError) as e:
models.resolve_model_path("large-v3")
assert e.value.code == "model_not_installed"
ft = tmp_path / "tiny-ft-20261015"
ft.mkdir()
(ft / "config.json").write_text("{}")
(ft / "model.bin").write_bytes(b"0")
(ft / "gvr-model.json").write_text('{"base":"openai/whisper-tiny","cer_before":0.3,"cer_after":0.2}')
assert models.resolve_model_path("tiny-ft-20261015") == ft
listed = {m["name"]: m for m in models.list_models()["models"]}
assert listed["tiny-ft-20261015"]["meta"]["cer_after"] == 0.2
(ft / models.PARTIAL_MARKER).write_text("x")
assert not models.is_model_dir(ft)
def test_progress_throttle() -> None:
events: list[dict] = []
rep = models.ProgressReporter(lambda ev, **kw: events.append(kw), total_bytes=100 * models.MB, interval=0.2)
for i in range(50):
rep.update(i * models.MB)
assert len(events) == 1
time.sleep(0.25)
rep.update(60 * models.MB)
assert len(events) == 2 and events[-1]["done_mb"] == 60.0 and events[-1]["total_mb"] == 100.0
assert set(events[-1]) == {"done_mb", "total_mb", "speed_mbps", "eta_s"}
def test_disk_check(tmp_path) -> None:
with pytest.raises(WorkerError) as e:
models._check_disk(tmp_path, 10**18)
assert e.value.code == "disk_full"

View File

@@ -0,0 +1,40 @@
from __future__ import annotations
from gvr_worker.noise import HALLUCINATION_PHRASES, SegInfo, judge_text, judge_vad, thresholds
GOOD = [SegInfo(0.05, -0.3, 1.2)]
def test_phrase_list_size() -> None:
assert len(HALLUCINATION_PHRASES) >= 30
def test_clean_text_passes() -> None:
assert judge_text("레이즈 궁 빠졌어 B 사이트 로테 하자", GOOD, 0.8, 2.4, 0.5) is None
assert judge_text("감사합니다", GOOD, 0.9, 1.0, 0.5) is None # 신뢰도 높으면 실제 발화
def test_no_speech() -> None:
assert judge_text("음", [SegInfo(0.9, -1.5, 1.0)], 0.2, 1.0, 0.5) == "no_speech"
assert judge_text("", [], 0.0, 1.0, 0.5) == "no_speech"
def test_hallucination() -> None:
for t in ["시청해 주셔서 감사합니다.", "구독과 좋아요 부탁드립니다", "MBC 뉴스 이덕영입니다.", "자막 제공 배달의민족",
"다음 영상에서 만나요!", "ㅋㅋㅋㅋㅋㅋ", "(음악)"]:
assert judge_text(t, GOOD, 0.7, 2.0, 0.5) == "hallucination", t
assert judge_text("감사합니다.", GOOD, 0.3, 0.8, 0.5) == "hallucination"
def test_repetition() -> None:
assert judge_text("아 아 아 아 아 아 아 아", GOOD, 0.6, 3.0, 0.5) == "repetition"
assert judge_text("가자가자가자가자가자가자가자", GOOD, 0.6, 3.0, 0.5) == "repetition"
assert judge_text("가자 가자", GOOD, 0.6, 1.0, 0.5) is None
def test_vad_and_sensitivity() -> None:
assert judge_vad(0.0, 0.0, 0.5)
assert not judge_vad(0.7, 2.0, 0.5)
lo, hi = thresholds(0.0), thresholds(1.0)
assert lo.vad_ratio < hi.vad_ratio and lo.no_speech_prob > hi.no_speech_prob
assert judge_vad(0.15, 0.4, 1.0) and not judge_vad(0.15, 0.4, 0.0)

View File

@@ -0,0 +1,91 @@
from __future__ import annotations
import threading
import time
import numpy as np
from gvr_worker.ocr import Deduper, frame_changed, parse_chat_line
from gvr_worker.r3dlog import follow, latest_log, parse_r3d_line, read
def test_parse_team_with_time_and_champion() -> None:
assert parse_chat_line("[12:34] [팀] 민수 (아리): 드래곤 가자") == {
"game_time": "12:34", "game_time_s": 754.0, "channel": "team", "sender": "민수", "champion": "아리",
"message": "드래곤 가자"}
def test_parse_variants() -> None:
p = parse_chat_line("[All] Faker (Ahri): gg wp")
assert (p["channel"], p["sender"], p["champion"], p["message"], p["game_time"]) == ("all", "Faker", "Ahri", "gg wp", None)
p = parse_chat_line("[1:02:03] [파티] 지우: 바론 치자 3:00 에")
assert (p["game_time_s"], p["channel"], p["message"]) == (3723.0, "party", "바론 치자 3:00 에")
p = parse_chat_line("[05:10] [전체] 승한 (리 신): ㅋㅋ") # 전각 콜론
assert (p["channel"], p["champion"], p["message"]) == ("all", "리 신", "ㅋㅋ")
p = parse_chat_line("민수: 갱 와줘")
assert (p["channel"], p["sender"]) == ("team", "민수")
p = parse_chat_line("[12:40] 민수 님이 드래곤을 처치했습니다")
assert (p["channel"], p["sender"], p["game_time"]) == ("system", None, "12:40")
p = parse_chat_line("드래곤 등장까지 1:00")
assert p["channel"] == "system"
assert parse_chat_line(" ") is None
def test_dedupe() -> None:
d = Deduper(size=3)
a = parse_chat_line("[12:34] [팀] 민수 (아리): 드래곤 가자")
assert d.first_time(a) and not d.first_time(dict(a))
assert d.first_time(parse_chat_line("[12:35] [팀] 민수 (아리): 드래곤 가자"))
for i in range(4):
d.first_time(parse_chat_line(f"[13:0{i}] 지우: x"))
assert d.first_time(a) # 오래된 키는 밀려남
def test_frame_changed() -> None:
a = np.zeros((10, 10), np.uint8)
assert frame_changed(None, a)
assert not frame_changed(a, a.copy())
b = a.copy()
b[:5] = 200
assert frame_changed(a, b)
def test_r3dlog_parse() -> None:
assert parse_r3d_line("000754.123| ALWAYS| [팀] 민수 (아리): 드래곤 가자\n") == {
"game_time": "12:34", "game_time_s": 754.123, "channel": "team", "sender": "민수", "champion": "아리",
"message": "드래곤 가자"}
p = parse_r3d_line("[All] Faker (Ahri): gg")
assert p["channel"] == "all" and p["game_time_s"] is None
assert parse_r3d_line("000012.000| ALWAYS| r3dRenderLayer::Init") is None
def test_r3dlog_latest_read_and_follow(tmp_path) -> None:
old = tmp_path / "a" / "old_r3dlog.txt"
new = tmp_path / "b" / "new_r3dlog.txt"
old.parent.mkdir()
new.parent.mkdir()
old.write_text("[팀] 옛날 (티모): 하이\n", encoding="utf-8")
time.sleep(0.05)
new.write_text("000001.000| x\n000065.500| [전체] 지우 (럭스): 안녕\n", encoding="utf-8")
assert latest_log(tmp_path) == new
r = read(str(tmp_path), since_ms=None)
assert r["file"] == str(new) and r["lines"][0]["game_time"] == "01:05"
stop = threading.Event()
got: list[dict] = []
def run() -> None:
for p in follow(new, stop, poll_s=0.05):
got.append(p)
stop.set()
t = threading.Thread(target=run)
t.start()
time.sleep(0.2)
with open(new, "a", encoding="utf-8") as f:
f.write("000070.000| [팀] 민수 (아리): 미드 ")
f.flush()
time.sleep(0.15)
f.write("갱\n")
t.join(timeout=3)
assert got and got[0]["message"] == "미드 갱"

View File

@@ -0,0 +1,177 @@
"""워커 프로세스와 JSON Lines 왕복 (실제 tiny 모델, CPU int8)."""
from __future__ import annotations
import sys
from pathlib import Path
from conftest import FIXTURES
KO_EXPECTED = "레이즈 궁 빠졌어 B 사이트 로테 하자"
COMMON = {
"hotwords": "레이즈 로테 사이트 오퍼레이터",
"initial_prompt": None,
"corrections": [{"from": "비 싸이트", "to": "B 사이트"}, {"from": "비 사이트", "to": "B 사이트"}],
"dictionary": ["레이즈", "로테", "오퍼레이터", "사이트"],
"profile_lufs": None,
"target_lufs": -18,
"noise_sensitivity": 0.5,
"denoise": False,
}
def cer(ref: str, hyp: str) -> float:
a, b = ref.replace(" ", ""), hyp.replace(" ", "")
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i] + [0] * len(b)
for j, cb in enumerate(b, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))
prev = cur
return prev[-1] / len(a)
def test_hello_and_errors(worker) -> None:
res, _ = worker.request({"id": "1", "op": "hello"})
assert res["ok"] is True
assert res["result"]["version"] == "1.0.0"
assert res["result"]["device"] in ("cuda", "cpu")
assert res["result"]["python"].startswith("3.")
worker.send("this is not json")
msg = worker.recv()
assert msg == {"id": None, "ok": False, "error": {"code": "bad_json", "message": msg["error"]["message"]}}
res, _ = worker.request({"id": "2", "op": "does_not_exist"})
assert res["ok"] is False and res["error"]["code"] == "unknown_op"
res, _ = worker.request({"id": "3", "op": "transcribe", "slot": "nope", "path": "x"})
assert res["error"]["code"] == "bad_request"
res, _ = worker.request({"id": "4", "op": "transcribe", "slot": "precise", "path": "x"})
assert res["error"]["code"] == "model_not_loaded"
res, _ = worker.request({"id": "5", "op": "load", "slot": "precise", "model": "no-such-model"})
assert res["error"]["code"] == "unknown_model"
def test_gpu_info_and_models(worker) -> None:
res, _ = worker.request({"id": "g", "op": "gpu_info"})
r = res["result"]
assert isinstance(r["gpus"], list)
for g in r["gpus"]:
assert {"index", "name", "vram_total_mb", "vram_used_mb", "driver", "cuda_driver", "compute_capability"} <= set(g)
assert {"realtime", "precise", "compute_type", "budget_mb", "reason"} <= set(r["recommend"])
res, _ = worker.request({"id": "m", "op": "models"})
names = {m["name"]: m for m in res["result"]["models"]}
assert set(names) >= {"large-v3-turbo", "large-v3", "medium", "small", "tiny"}
assert names["large-v3-turbo"]["repo"] == "mobiuslabsgmbh/faster-whisper-large-v3-turbo"
assert {"installed", "path", "size_mb"} <= set(res["result"]["cuda_runtime"])
def test_load_and_transcribe(worker, models_dir: Path) -> None:
if not (models_dir / "tiny" / "model.bin").exists():
res, events = worker.request({"id": "dl", "op": "download", "target": "model", "name": "tiny"}, timeout=600)
assert res["ok"], res
assert all(e["event"] == "progress" for e in events)
res, _ = worker.request({"id": "L", "op": "load", "slot": "realtime", "model": "tiny",
"device": "cpu", "compute_type": "int8"})
assert res["ok"], res
assert res["result"]["device"] == "cpu"
res, _ = worker.request({"id": "T1", "op": "transcribe", "slot": "realtime",
"path": str(FIXTURES / "speech_ko.ogg"), **COMMON})
assert res["ok"], res
r = res["result"]
assert set(r) >= {"text", "raw_text", "words", "noise", "noise_reason", "confidence", "lufs", "gain_db",
"speech_ratio", "duration_s", "model", "elapsed_ms"}
assert r["noise"] is False and r["noise_reason"] is None
assert r["model"] == "tiny"
assert "레이즈" in r["text"]
assert cer(KO_EXPECTED, r["text"]) < 0.4, r["text"]
assert r["words"] and all(set(w) == {"w", "s", "e", "p"} for w in r["words"])
assert all(not w["w"].startswith(" ") for w in r["words"])
starts = [w["s"] for w in r["words"]]
assert starts == sorted(starts) and r["words"][-1]["e"] <= r["duration_s"] + 0.1
assert 0 < r["confidence"] <= 1 and r["speech_ratio"] > 0.4
print("\nCPU tiny:", r["text"], f"{r['elapsed_ms']}ms")
# 작은 목소리: 정규화가 게인을 크게 올리고 같은 문장으로 인식
res, _ = worker.request({"id": "T2", "op": "transcribe", "slot": "realtime",
"path": str(FIXTURES / "speech_ko_quiet.ogg"), **COMMON})
q = res["result"]
assert q["gain_db"] >= r["gain_db"] + 20
assert q["lufs"] < r["lufs"] - 25
assert q["noise"] is False and "레이즈" in q["text"]
def test_noise_samples(worker) -> None:
worker.request({"id": "L2", "op": "load", "slot": "precise", "model": "tiny", "device": "cpu",
"compute_type": "int8"})
for name in ("keyboard_clicks", "white_noise", "silence"):
res, _ = worker.request({"id": name, "op": "transcribe", "slot": "precise",
"path": str(FIXTURES / f"{name}.ogg"), **COMMON})
r = res["result"]
assert r["noise"] is True, (name, r)
assert r["noise_reason"] in ("vad", "no_speech", "hallucination", "repetition")
assert r["text"] is None and r["words"] == []
res, _ = worker.request({"id": "nf", "op": "transcribe", "slot": "precise", "path": "/no/such.ogg"})
assert res["error"]["code"] == "file_not_found"
res, _ = worker.request({"id": "U", "op": "unload", "slot": "precise"})
assert res["ok"]
def test_misc_ops(worker, tmp_path: Path) -> None:
logs = tmp_path / "GameLogs" / "2024-05-01T20-00-00"
logs.mkdir(parents=True)
(logs / "2024-05-01T20-00-00_r3dlog.txt").write_text(
"000010.000| ALWAYS| Game started\n"
"000754.123| ALWAYS| [팀] 민수 (아리): 드래곤 가자\n", encoding="utf-8")
res, _ = worker.request({"id": "r", "op": "r3dlog_check", "logs_dir": str(tmp_path / "GameLogs")})
assert res["result"]["found_chat"] is True
res, _ = worker.request({"id": "r2", "op": "r3dlog_read", "logs_dir": str(tmp_path / "GameLogs"),
"since_ms": None})
line = res["result"]["lines"][0]
assert line == {"game_time": "12:34", "game_time_s": 754.123, "channel": "team", "sender": "민수",
"champion": "아리", "message": "드래곤 가자"}
res, _ = worker.request({"id": "r3", "op": "r3dlog_read", "logs_dir": str(tmp_path / "GameLogs"),
"since_ms": 4102444800000})
assert res["result"] == {"file": None, "lines": []}
img = tmp_path / "x.png"
img.write_bytes(b"\x89PNG")
res, _ = worker.request({"id": "o", "op": "ocr_image", "path": str(img)})
if sys.platform != "win32":
assert res["error"]["code"] == "ocr_unavailable"
res, _ = worker.request({"id": "o2", "op": "ocr_start", "window_title": "League of Legends (TM) Client"})
assert res["error"]["code"] == "ocr_unavailable"
res, _ = worker.request({"id": "c", "op": "download", "target": "cuda_runtime"})
assert res["ok"] and res["result"]["skipped"] is True
res, _ = worker.request({"id": "s", "op": "ocr_stop"})
assert res["ok"] and res["result"]["stopped"] is False
# train: 별도 파이썬으로 finetune/run.py 실행 → 중지 파일이 있으면 바로 stopped
stop = tmp_path / "finetune.stop"
stop.write_text("game")
res, _ = worker.request({"id": "t", "op": "train", "python": sys.executable,
"args": {"stop_file": str(stop), "base": "openai/whisper-tiny"}})
assert res["ok"], res
assert res["result"]["stopped"] is True and res["result"]["adopt"] is False
res, _ = worker.request({"id": "t2", "op": "train", "python": "/no/python"})
assert res["error"]["code"] == "finetune_env_missing"
def test_shutdown_exits_cleanly(models_dir: Path, tmp_path: Path) -> None:
import os
from conftest import WorkerProc
w = WorkerProc({**os.environ, "GVR_DATA_DIR": str(tmp_path), "GVR_MODELS_DIR": str(models_dir)})
res, _ = w.request({"id": "x", "op": "shutdown"})
assert res == {"id": "x", "ok": True, "result": {"bye": True}}
assert w.proc.wait(timeout=20) == 0
assert all(line.endswith("\n") for line in w.raw)