diff --git a/README.md b/README.md index 445b985..bd2f339 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ | 단계 | 내용 | 상태 | |---|---|---| | M0 기술 검증 | DAVE 음성 연결, faster-whisper STT·음량·잡음·사전, 게임 로컬 API 처리, 게임 PC 진단 기능 | ✅ 완료 ([결과](docs/dev/M0-verification.md)) | -| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ⏳ | +| M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ✅ 완료 ([실음성 테스트](docs/dev/test-results.md)) | | M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ⏳ | | M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ⏳ | | M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ⏳ | diff --git a/app/scripts/vc-list.mts b/app/scripts/vc-list.mts index 440d7b8..8dce3bf 100644 --- a/app/scripts/vc-list.mts +++ b/app/scripts/vc-list.mts @@ -3,14 +3,8 @@ 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')); - } - } + const g = c.guilds.cache.get(process.argv[2])!; + for (const ch of g.channels.cache.values()) if (ch.type === ChannelType.GuildVoice) console.log(ch.id, ch.name, [...ch.members.values()].map((m) => m.displayName).join(',')); await c.destroy(); }); await c.login(s.token); diff --git a/app/scripts/voice-e2e.mts b/app/scripts/voice-e2e.mts new file mode 100644 index 0000000..ecf3722 --- /dev/null +++ b/app/scripts/voice-e2e.mts @@ -0,0 +1,95 @@ +// M1 실제 음성 E2E: 테스트봇이 음성채널에 들어가 한국어 문장을 말하면, 겜녹이(코어)가 따라 들어와 녹음 → STT → DB 저장까지. +// node --import tsx scripts/voice-e2e.mts +// 필요: secrets.json 의 겜녹이·테스트봇 토큰, worker/.venv, tiny 모델(HF 캐시) +import { Client, GatewayIntentBits } from 'discord.js'; +import { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus } from '@discordjs/voice'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { synthesize } from '../src/core/discord/tts.ts'; + +const [guildId, channelId] = process.argv.slice(2); +const secrets = JSON.parse(fs.readFileSync('/home/claude/.config/ejclaw/secrets.json', 'utf8')).credentials; +const GVR_TOKEN = secrets['discord.com/bot/game-voice-recorder'].token; +const SPEAKER_TOKEN = secrets['discord.com/bot/testbot'].token; +const SPEAKER_ID = secrets['discord.com/bot/testbot'].client_id || '1538122882528321536'; +const root = path.resolve(import.meta.dirname, '..', '..'); +const work = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-voice-e2e-')); +const models = path.join(work, 'models'); +fs.mkdirSync(models, { recursive: true }); +const hf = path.join(os.homedir(), '.cache/huggingface/hub/models--Systran--faster-whisper-small/snapshots'); +const model = fs.existsSync(hf) ? 'small' : 'tiny'; +fs.symlinkSync(path.join(hf.replace('small', model), fs.readdirSync(hf.replace('small', model))[0]), path.join(models, model)); +fs.writeFileSync( + path.join(work, 'settings.json'), + JSON.stringify({ + discord: { guildId, followUserId: SPEAKER_ID, followEnabled: true, ttsEnabled: true, ttsOnNewMember: false }, + stt: { realtimeModel: model, preciseModel: model, device: 'cpu', computeType: 'int8' }, + games: { valorant: false, lol: false }, + }), +); +process.env.GVR_RECORD_BOTS = '1'; +process.env.GVR_BOT_TOKEN = GVR_TOKEN; +const SENTENCES = ['레이즈 궁 빠졌어 B 사이트 로테 하자', '오늘 저녁에 치킨 먹을래', '나 오퍼레이터 살게']; +const clips: string[] = []; +const clipDir = path.join(os.homedir(), '.tmp', 'gvr-e2e-clips'); +for (const [i, s] of SENTENCES.entries()) { + const f = path.join(clipDir, `say-${i}.webm`); + if (!fs.existsSync(f)) await synthesize(s, i % 2 ? 'ko-KR-InJoonNeural' : 'ko-KR-SunHiNeural', f); + clips.push(f); +} +const { startCore } = await import('../src/core/index.ts'); +const core = await startCore({ dataDir: work, resourcesDir: path.join(root, 'app', 'resources'), worker: { cmd: path.join(root, 'worker/.venv/bin/python'), args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') }, version: 'e2e' }); +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); + await new Promise((r) => setTimeout(r, 200)); + } +}; +let ok = false; +const spk = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] }); +try { + await wait(() => core.bot.state.status === 'ready', 30000, 'gvr bot ready'); + await wait(() => core.stt.status.slots.realtime.state === 'loaded', 120000, 'model'); + await spk.login(SPEAKER_TOKEN); + await new Promise((r) => spk.once('clientReady', r)); + const ch: any = await spk.channels.fetch(channelId); + const conn = joinVoiceChannel({ channelId, guildId, adapterCreator: ch.guild.voiceAdapterCreator, selfDeaf: false, selfMute: false, daveEncryption: true }); + await entersState(conn, VoiceConnectionStatus.Ready, 20000); + console.log('speaker joined', ch.name); + await wait(() => core.bot.state.recording.active, 20000, 'gvr follows speaker'); + console.log('겜녹이 따라 들어옴 (follow):', core.bot.state.recording.channel); + await new Promise((r) => setTimeout(r, 9000)); // 안내 음성이 끝나고 DAVE 키 교환이 안정될 때까지 + const player = createAudioPlayer(); + conn.subscribe(player); + for (const f of clips) { + player.play(createAudioResource(fs.createReadStream(f), { inputType: StreamType.WebmOpus })); + await entersState(player, AudioPlayerStatus.Playing, 5000); + await entersState(player, AudioPlayerStatus.Idle, 30000); + await new Promise((r) => setTimeout(r, 1500)); + } + await wait(() => core.store.db.prepare(`SELECT count(*) n FROM utterances WHERE status!='pending'`).get().n >= SENTENCES.length, 90000, 'stt'); + const rows = core.store.db.prepare('SELECT user_id, started_at, ended_at, text, gain_db, status FROM utterances ORDER BY started_at').all() as any[]; + for (const r of rows) console.log(` [${r.user_id === SPEAKER_ID ? '테스트봇' : r.user_id}] ${((r.ended_at - r.started_at) / 1000).toFixed(1)}s gain ${r.gain_db?.toFixed(1)}dB ${r.status}: ${r.text}`); + // 녹음 제외 확인 + core.store.setExcluded(SPEAKER_ID, true); + const before = rows.length; + player.play(createAudioResource(fs.createReadStream(clips[0]), { inputType: StreamType.WebmOpus })); + await entersState(player, AudioPlayerStatus.Idle, 30000).catch(() => undefined); + await new Promise((r) => setTimeout(r, 2500)); + const after = (core.store.db.prepare('SELECT count(*) n FROM utterances').get() as any).n; + console.log(`녹음 제외 후 새 발화: ${after - before}개 (0 이어야 함)`); + const texts = rows.map((r) => r.text || '').join(' '); + ok = rows.length >= SENTENCES.length && /레이즈|오퍼|치킨/.test(texts) && after === before; + conn.destroy(); + await wait(() => !core.bot.state.recording.active, 20000, 'gvr leaves after speaker').catch(() => console.log('(겜녹이 퇴장 대기 시간 초과)')); + console.log('겜녹이 퇴장:', !core.bot.state.recording.active); +} catch (e) { + console.error('E2E 실패', e); +} finally { + await spk.destroy(); + await core.stop(); + console.log(ok ? 'VOICE E2E PASS' : 'VOICE E2E FAIL'); + process.exit(ok ? 0 : 1); +} diff --git a/app/src/core/discord/bot.ts b/app/src/core/discord/bot.ts index cf4c0c3..3901067 100644 --- a/app/src/core/discord/bot.ts +++ b/app/src/core/discord/bot.ts @@ -166,7 +166,7 @@ export class Bot { const myCh = this.state.recording.channelId; if (!myCh) return; // 새 사람이 들어오면 안내를 다시 튼다 - if (n.channelId === myCh && o.channelId !== myCh && n.member && !n.member.user.bot) { + if (n.channelId === myCh && o.channelId !== myCh && n.member && (!n.member.user.bot || process.env.GVR_RECORD_BOTS === '1')) { this.touchUser(n.member); this.updateParticipants(); if (s.ttsEnabled && s.ttsOnNewMember) void this.announce(); @@ -231,7 +231,7 @@ export class Bot { 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); + for (const m of channel.members.values()) if (!m.user.bot || process.env.GVR_RECORD_BOTS === '1') 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); diff --git a/app/src/core/discord/tts.ts b/app/src/core/discord/tts.ts index 4d89282..26caf42 100644 --- a/app/src/core/discord/tts.ts +++ b/app/src/core/discord/tts.ts @@ -42,7 +42,19 @@ export class Announcer { } } -export async function synthesize(text: string, voice: string, outFile: string): Promise { +/** Edge TTS 는 짧은 시간에 여러 번 부르면 429 를 준다. 몇 번 쉬었다가 다시 시도한다. */ +export async function synthesize(text: string, voice: string, outFile: string, tries = 4): Promise { + for (let i = 1; ; i++) { + try { + return await synthesizeOnce(text, voice, outFile); + } catch (e: any) { + if (i >= tries) throw e; + await new Promise((r) => setTimeout(r, 1500 * 2 ** i)); + } + } +} + +async function synthesizeOnce(text: string, voice: string, outFile: string): Promise { fs.mkdirSync(path.dirname(outFile), { recursive: true }); const tts = new MsEdgeTTS(); const tmpDir = fs.mkdtempSync(path.join(path.dirname(outFile), '.tts-')); diff --git a/app/src/core/index.ts b/app/src/core/index.ts index 8340fd7..7d59348 100644 --- a/app/src/core/index.ts +++ b/app/src/core/index.ts @@ -62,7 +62,8 @@ export async function startCore(opts: CoreOptions) { skip: (uid): boolean => { const u = store.getUser(uid); if (u?.excluded) return true; - return !!bot.client?.users.cache.get(uid)?.bot; + // 다른 봇(음악봇 등)은 녹음하지 않는다. 자동 테스트에서만 GVR_RECORD_BOTS=1 로 연다. + return process.env.GVR_RECORD_BOTS !== '1' && !!bot.client?.users.cache.get(uid)?.bot; }, matchAt: (ts) => games.liveMatchAt(ts), }); diff --git a/docs/dev/test-results.md b/docs/dev/test-results.md new file mode 100644 index 0000000..2c87ede --- /dev/null +++ b/docs/dev/test-results.md @@ -0,0 +1,28 @@ +# 테스트 기록 + +단계별로 실제로 돌린 테스트와 결과. 명령은 저장소 루트 기준. + +## M1 녹음 + STT (2026-10-15) + +### 실제 디스코드 음성 E2E — `app/scripts/voice-e2e.mts` + +F&L 서버 "음성" 채널. 테스트봇이 들어가 한국어 TTS 문장 3개를 말하고, 겜녹이(헤드리스 코어)가 따라 들어와 녹음했다. +STT 는 개발 서버라 CPU + `small` 모델(게임 PC 는 GPU + large-v3-turbo/large-v3). + +``` +겜녹이 따라 들어옴 (follow): 음성 + [테스트봇] 3.9s gain 0.9dB realtime: 레이즈 공 빠졌어 비사이트로 태하자 + [테스트봇] 3.4s gain 0.1dB realtime: 오늘 저녁에 치킨 먹을래 + [테스트봇] 2.6s gain -0.7dB realtime: 나우퍼레이터 살게 +녹음 제외 후 새 발화: 0개 (0 이어야 함) +음성채널 나감 (follow-left) +VOICE E2E PASS +``` + +확인한 것: 따라가기 입장·퇴장, DAVE 수신, 유저별 발화 분할(3문장 → 3발화), Ogg 저장, 대기열 STT, 녹음 제외 즉시 반영. +인식 오류("궁"→"공", 붙은 단어)는 small 모델 한계로, 게임 PC 의 large 모델 + 사전·교정 학습으로 줄인다. + +### 자동 테스트 + +- `cd app && npm test` — 9개 통과 (Ogg 쓰기, 사전·diff, 경기 상세·시간 표시, 타임라인 조회, 7일 삭제, STT E2E, 가짜 Riot 서버 통합) +- `cd worker && .venv/bin/python -m pytest -q` — 39개 통과 diff --git a/worker/gvr_worker/main.py b/worker/gvr_worker/main.py index 456655e..28db085 100644 --- a/worker/gvr_worker/main.py +++ b/worker/gvr_worker/main.py @@ -177,7 +177,10 @@ def run_finetune(req: dict[str, Any], ctx: Context) -> dict[str, Any]: def main() -> None: - logging.basicConfig(stream=sys.stderr, level=os.environ.get("GVR_LOG_LEVEL", "INFO"), + level = os.environ.get("GVR_LOG_LEVEL", "INFO").upper() + if level not in ("DEBUG", "INFO", "WARNING", "WARN", "ERROR", "CRITICAL"): + level = "INFO" + logging.basicConfig(stream=sys.stderr, level="WARNING" if level == "WARN" else level, format="%(asctime)s %(levelname)s %(name)s: %(message)s") for noisy in ("httpx", "httpx2", "huggingface_hub", "faster_whisper"): logging.getLogger(noisy).setLevel(logging.WARNING)