# 겜녹이 (GVR) 개발 구조 · 인터페이스 계약 이 문서는 구현용 계약서다. 컴포넌트 사이의 경계(프로세스, 프로토콜, 데이터 형식)를 고정해 두고, 각 컴포넌트는 이 계약만 지키면 따로 만들 수 있다. ## 저장소 구조 ``` app/ 게임 PC 앱 (Electron + Node.js 코어, TypeScript) src/core/ 헤드리스 코어. Electron 없이 `node` 로도 돈다 (리눅스 테스트용) src/main/ Electron 메인 프로세스 (트레이, 창, 마법사, safeStorage) src/renderer/ 설정 창 · 첫 실행 마법사 UI worker/ Python STT 워커 (faster-whisper, VAD, 음량 정규화, 롤 로그 채팅, 모델 관리, 파인튜닝) 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}} // 화면 OCR(ocr_start · ocr_stop · ocr_image)은 v1.3.3 에서 뺐다. 롤 게임 중 채팅은 r3dlog_read (worker/README.md) {"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) 앱 로그인 토큰 · 마지막 로그인 확인(오프라인 3일 유예용) 포함. 겜녹이 봇 토큰은 없다 (8장) gvr.sqlite 기록 DB audio/YYYY-MM-DD/.ogg training/.ogg 교정한 문장의 음성 조각 (자동 삭제 제외, A3) models// 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)` - `noise_phrases(id PK, phrase UNIQUE (띄어쓰기 · 문장부호 뺀 값), sample, hits, created_at)` — "잡음이라 삭제"로 배운 문장 (v1.4.0) ## 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` | 사전 목록 | | POST | `/api/utterances/:id/delete` | `{noise}` → 발화 · 음성 · 학습 데이터 지우기 (관리자 · 말한 사람). noise=true 면 문장을 잡음으로 배움. 응답 `{ok, learned}`, 실시간 `utterance.deleted` | | GET | `/api/noise-phrases` | `{phrases:[{id,text,hits,createdAt}]}` 잡음으로 배운 문장 | | DELETE | `/api/noise-phrases/:id` | 배운 문장 지우기 | `/api/timeline` 쿼리: `users=a,b` · `game=valorant|lol|none` · `match=` · `from=&to=` · `q=<키워드>` · `types=utterance,kill,chat,object,round` · `hideNoise=1` · `cursor=` · `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'|'lcu'|'log'|'ocr'(v1.3.2 까지 기록)}` · 오브젝트 `{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 .`. 기기 키는 등록 때 한 번 받는다 (서버는 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":""} // 작은 응답 {"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}` 확인 → 세션 쿠키. GUILD_ID = 게임 PC 앱에서 녹음할 서버로 고른 서버 (앱이 hello 로 알려 줌, 그 전에는 ALLOWED_GUILD_IDS). 아니면 `/?login=not_member` ("봇과 다른 서버") | | `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}` | | `POST /auth/app/begin` | 앱 로그인 시작 → `{id, secret, url, expiresAt}` (url 을 브라우저로 연다, 10분 유효) | | `GET /auth/app/start/:id` | 브라우저: state 쿠키(`app..`) → 디스코드 OAuth → 같은 `/auth/discord/callback` | | `POST /auth/app/poll` | `{id, secret}` → `{state:'pending'}` · `{state:'ok', token, user, role}` · `{state:'not_registered', user}` (결과는 한 번만) | | `GET /app/me` | `Authorization: Bearer <앱 토큰>` → `{user, role, serverTime}`. 미등록 403 `not_registered`, 토큰 무효 401 | | `WS /app/bot/ws` | `Authorization: Bearer <앱 토큰>`. 겜녹이 봇 중계 (8장). 토큰 무효 · 미등록 401, 연결 중 등록 해제 · 로그아웃되면 4401 로 끊는다 | | `POST /auth/app/logout` | 앱 토큰 무효화 | | `GET /app/admin/users` | 관리자 이상 → `{users: AppUserRow[]}` (최고 관리자 고정 행 포함) | | `POST /app/admin/users` · `PATCH`/`DELETE /app/admin/users/:id` | 최고 관리자만: 등록(`{id, role:'admin'|'user'}`, 디스코드에서 계정 확인) · 역할 변경 · 등록 해제 | | `GET /game-assets//` | valorant-api.com · ddragon · cdragon 이미지 캐시 프록시 | | `GET /auth/guild` | 로그인 화면 안내용 `{name}`: 들어올 수 있는 서버 이름 | | `GET /site/maps3d` · `GET /site/maps3d/:dir/:code.glb` | 로그인 필요. 발로란트 맵 3D (data/maps3d, `tools/map-extract`). glb 는 gzip 그대로 보낸다 | ## 8. 겜녹이 봇 중계 (v1.2.1~) 겜녹이 봇 토큰은 사이트 서버에만 있다 (앱에 보내지 않는다). 서버가 discord.js 로 디스코드 게이트웨이에 한 번 붙고 (`site/server/src/discord-source.ts`), 로그인한 앱은 `WS /app/bot/ws` 로 필요한 정보만 받는다 (`site/server/src/bot-broker.ts`, 앱 쪽 `app/src/core/discord/gateway.ts` 의 `RemoteGateway`. 다른 봇 모드는 `LocalGateway` 로 PC 가 직접 연결). 형식은 `packages/shared` 의 `BotGw*`. - 서버 → 앱: `ready{me, guilds}` · `guilds` · `guild{guild, channels, voice}`(watch 응답) · `voiceState`(지켜보는 서버만) · `cmd`(슬래시 명령) · `vserver`/`vstate`(봇 자신의 VOICE_SERVER/STATE_UPDATE 원문 = 일회용 음성 접속 정보) · `taken` · `res` - 앱 → 서버: `watch{guildId, commands}` · `voice{guildId, payload}`(@discordjs/voice 어댑터의 op 4) · `cmd_res{id, content}` · `req{op:'members'}` - 권한 (앱 유저의 디스코드 아이디 기준): 서버 목록 · watch 는 그 유저가 가입한 서버만 (아니면 `watch_denied`), 채널 · 음성 상태는 그 유저가 볼 수 있는(ViewChannel) 채널만 (볼 수 없는 채널로 옮기면 "나감"으로 가린다), 음성 참여는 그 유저가 들어갈 수 있는(ViewChannel + Connect) 음성채널만. 슬래시 명령 /녹음시작 도 그 채널에 들어갈 수 있는 유저의 PC 로만 보낸다 - 권한 회수: 연결한 뒤에도 탈퇴 · 추방 · 역할 · 채널 권한 변경 이벤트(`access`), 음성 접속 정보를 넘기기 직전, 30초 주기로 다시 확인한다. 봇이 있는 채널에 그 유저가 더는 들어갈 수 없으면 음성 접속 정보 전달을 멈추고 봇을 빼고(op 4 null) 앱에 `taken` 을 보낸다. 서버 멤버가 아니게 되면 `watch_denied` - 음성채널 참여: 앱의 @discordjs/voice 가 어댑터로 op 4 를 보내면 서버가 검사(지켜보는 서버 · 들어갈 수 있는 음성채널 · op 4 만, 필드를 다시 만들어)한 뒤 대신 보내고, 디스코드가 준 session_id · 음성 서버 token · endpoint 를 그 앱에만 넘긴다. 음성(UDP · DAVE)은 앱 ↔ 디스코드 음성 서버로 바로 간다 (Lavalink 와 같은 방식) - 한 서버에서 봇은 음성채널 하나에만 있을 수 있다: 마지막으로 참여를 요청한 앱이 가져가고 이전 앱은 `taken` 을 받는다. 이전 앱의 늦은 나가기는 무시한다. 음성을 가진 앱이 끊기면 서버가 봇을 음성채널에서 뺀다 - 슬래시 명령: 서버가 받아 바로 defer 하고, 그 서버를 지켜보는 앱에 보낸다 (녹음시작: 명령한 사람의 PC → 녹음 중인 PC → 가장 최근 PC, 녹음종료: 녹음 중인 PC, 녹음제외 · 참여: 모든 PC). 첫 응답을 답장으로 쓴다 - 사이트 서버에 못 붙으면 겜녹이 봇은 쓸 수 없다 (다른 봇 모드는 상관없음)