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:
211
docs/dev/ARCHITECTURE.md
Normal file
211
docs/dev/ARCHITECTURE.md
Normal 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 이미지 캐시 프록시 |
|
||||
Reference in New Issue
Block a user