diff --git a/README.md b/README.md index 505cf33..2fd3873 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ | M0 기술 검증 | DAVE 음성 연결, faster-whisper STT·음량·잡음·사전, 게임 로컬 API 처리, 게임 PC 진단 기능 | ✅ 완료 ([결과](docs/dev/M0-verification.md)) | | M1 녹음 + STT 기본 | 따라가기·명령 참여, TTS 안내, 유저별 녹음, 대기열 STT, /녹음제외·참여 | ✅ 완료 ([실음성 테스트](docs/dev/test-results.md)) | | M2 사이트 서버 · 사이트 v1 | 디스코드 로그인, 연결 확인·잠금, 타임라인·따라 읽기·필터·검색·실시간 | ✅ 완료 · https://gvr.tkrmagid.kr 배포 | -| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ⏳ | +| M3 발로란트 연동 | 경기 감지, 킬·라운드·채팅, 라운드 시간 + 경기 경과 시간, 경기 상세 | ✅ 완료 ([전체 스택 테스트](docs/dev/test-results.md)) | | M4 롤 연동 · 채팅 OCR | 게임 API 이벤트, LCU 결과·타임라인, 채팅 OCR·로그, 롤 경기 상세 | ⏳ | | M5 exe · 설정 · 모델 | 포터블 exe, 첫 실행 마법사, GPU 감지·모델 다운로드, 암호화 저장, 7일 삭제 | ⏳ | | M6 단어사전 · UI/UX | 핫워드·교정 사전, 사이트 교정 반영, 테마·애니메이션·효과음 | ⏳ | diff --git a/app/scripts/demo-stack.mts b/app/scripts/demo-stack.mts new file mode 100644 index 0000000..1e4bb66 --- /dev/null +++ b/app/scripts/demo-stack.mts @@ -0,0 +1,259 @@ +// 전체 스택 시연·통합 테스트 (M3·M4·M7): +// 실제 코어(+STT 워커) ← 경기 데이터(발로란트 22라운드·롤 28분, 실제 API 구조) + TTS 로 만든 대화 음성 +// → 로컬 사이트 서버(실제 코드) ← 코어가 중계로 연결 → 헤드리스 브라우저로 화면 확인·스크린샷 +// +// node --import tsx scripts/demo-stack.mts [--serve] [--model small] +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { synthesize } from '../src/core/discord/tts.ts'; +import { processMatchDetails } from '../src/core/games/valorant.ts'; +import { makeDemoLol, makeDemoValorant } from '../test/fixtures/demo-matches.ts'; + +const args = process.argv.slice(2); +const serve = args.includes('--serve'); +const model = args.includes('--model') ? args[args.indexOf('--model') + 1] : 'small'; +const root = path.resolve(import.meta.dirname, '..', '..'); +const work = path.join(os.homedir(), '.tmp', 'gvr-demo'); +const shotDir = process.env.SHOT_DIR || path.join(root, 'docs', 'dev', 'screens'); +fs.rmSync(work, { recursive: true, force: true }); +fs.mkdirSync(path.join(work, 'models'), { recursive: true }); +const hf = path.join(os.homedir(), `.cache/huggingface/hub/models--Systran--faster-whisper-${model}/snapshots`); +fs.symlinkSync(path.join(hf, fs.readdirSync(hf)[0]), path.join(work, 'models', model)); +fs.writeFileSync(path.join(work, 'settings.json'), JSON.stringify({ stt: { realtimeModel: model, preciseModel: model, device: 'cpu', computeType: 'int8' }, games: { valorant: false, lol: false } })); + +const USERS = [ + { id: '100000000000000001', name: '승한', voice: 'ko-KR-InJoonNeural', val: 'p-sh', lol: 'l-sh' }, + { id: '100000000000000002', name: '민수', voice: 'ko-KR-HyunsuMultilingualNeural', val: 'p-ms', lol: 'l-ms' }, + { id: '100000000000000003', name: '지우', voice: 'ko-KR-SunHiNeural', val: 'p-jw', lol: 'l-jw' }, + { id: '100000000000000004', name: '현우', voice: 'ko-KR-InJoonNeural', pitch: '-8Hz', val: 'p-hw', lol: 'l-hw' }, +]; +type Line = { u: number; text: string; at: { val: [number, number] } | { lol: number } | { off: number } }; +const LINES: Line[] = [ + { u: 0, text: '오늘 랭겜 몇 판 할까', at: { off: -200 } }, + { u: 2, text: '나 과제 끝내고 왔어 두 판만 하자', at: { off: -190 } }, + { u: 1, text: '피스톨 라운드 A 메인 러시 가자', at: { val: [1, 2] } }, + { u: 0, text: '제트 대시로 먼저 들어갈게', at: { val: [1, 12] } }, + { u: 2, text: '세이지 벽 칠게 미드 막을게', at: { val: [1, 20] } }, + { u: 3, text: '스모크 깔았어 들어가', at: { val: [2, 15] } }, + { u: 1, text: '소바 화살 B 메인에 두 명 보여', at: { val: [3, 18] } }, + { u: 0, text: '레이즈 궁 빠졌어 B 사이트 로테 하자', at: { val: [5, 30] } }, + { u: 2, text: '스파이크 설치됐어 해체 들어가', at: { val: [7, 55] } }, + { u: 3, text: '내가 스모크 깔게 들어가 들어가', at: { val: [7, 38] } }, + { u: 1, text: '나이스 원탭', at: { val: [7, 41] } }, + { u: 0, text: '이번 라운드 세이브하자 돈 없어', at: { val: [9, 3] } }, + { u: 2, text: '나 오퍼레이터 살게', at: { val: [11, 2] } }, + { u: 3, text: '클러치 가능 침착하게 해', at: { val: [13, 60] } }, + { u: 0, text: '에이스 미쳤다 레전드', at: { val: [16, 50] } }, + { u: 1, text: '마지막 라운드 집중하자', at: { val: [22, 5] } }, + { u: 2, text: '이겼다 지지', at: { val: [22, 95] } }, + { u: 0, text: '롤 한 판 하자 나 미드 갈게', at: { lol: -60 } }, + { u: 1, text: '정글 탑 갱 갈게 라인 당겨줘', at: { lol: 4 } }, + { u: 3, text: '가렌 점멸 빠졌어', at: { lol: 7 } }, + { u: 2, text: '바텀 와드 박았어 쓰레쉬 어디 있어', at: { lol: 9.5 } }, + { u: 1, text: '드래곤 가자 바텀으로 모여', at: { lol: 11.6 } }, + { u: 0, text: '아리 궁 있어 한타 열자', at: { lol: 15 } }, + { u: 3, text: '바론 치자 시야 잡아줘', at: { lol: 21.4 } }, + { u: 2, text: '억제기 밀고 귀환하자', at: { lol: 26.5 } }, + { u: 0, text: '배고프다 치킨 시킬까', at: { off: -25 } }, + { u: 3, text: '내일 팀플 회의 몇 시였지', at: { off: -15 } }, + { u: 1, text: '중간고사 끝나면 피시방 가자', at: { off: -8 } }, +]; + +// ---- 대화 음성 (Edge TTS → Ogg Opus 48kHz). 캐시해서 다시 쓴다 +const clipDir = path.join(os.homedir(), '.tmp', 'gvr-demo-clips'); +fs.mkdirSync(clipDir, { recursive: true }); +for (const [i, l] of LINES.entries()) { + const ogg = path.join(clipDir, `${i}.ogg`); + if (fs.existsSync(ogg)) continue; + const webm = path.join(clipDir, `${i}.webm`); + const u = USERS[l.u]; + await synthesize(l.text, u.voice, webm); + execFileSync('ffmpeg', ['-v', 'error', '-y', '-i', webm, ...(u.pitch ? ['-af', 'asetrate=48000*0.92,aresample=48000,atempo=1.087'] : []), '-ac', '2', '-ar', '48000', '-c:a', 'libopus', '-b:a', '32k', ogg]); + await new Promise((r) => setTimeout(r, 400)); +} +const durMs = (f: string) => Math.round(Number(execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', f]).toString()) * 1000); + +// ---- 코어 +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: '1.0.0' }); +const { store, games } = core; +await core.assets.refresh(true); +for (const u of USERS) { + store.upsertUser({ id: u.id, name: u.name, avatar: null }); + store.setAccounts(u.id, [ + { puuid: u.val, riotId: `${u.name}#V` }, + { puuid: u.lol, riotId: `${u.name}#L` }, + ]); +} +store.upsertUser({ id: '100000000000000005', name: '도윤', avatar: null }); +store.setExcluded('100000000000000005', true); + +const now = Date.now(); +const VS = now - 3 * 3600_000; // 발로란트 시작 +const LS = now - 80 * 60_000; // 롤 시작 +const md = makeDemoValorant(VS); +const pre = processMatchDetails(md, 'p-sh', core.assets, 'x', VS); +const lol = makeDemoLol(); +const audioDir = path.join(core.paths().audio, 'demo'); +fs.mkdirSync(audioDir, { recursive: true }); + +function addUtterance(i: number, ts: number) { + const src = path.join(clipDir, `${i}.ogg`); + const id = `demo${String(i).padStart(3, '0')}`; + const dst = path.join(audioDir, `${id}.ogg`); + fs.copyFileSync(src, dst); + const row = store.insertUtterance({ id, session_id: null, user_id: USERS[LINES[i].u].id, started_at: ts, ended_at: ts + durMs(src), audio_path: dst, match_id: games.liveMatchAt(ts) }); + core.stt.enqueue(row.id, 'realtime'); +} + +// 발로란트 +const valId = 'val-demo-ascent-01'; +games.matchStarted({ id: valId, game: 'valorant', startedAt: VS, map: md.matchInfo.mapId, mode: 'competitive', queue: 'competitive', detail: { live: true } }); +LINES.forEach((l, i) => { + if (!('val' in l.at)) return; + const [r, s] = l.at.val; + const rr = pre.rounds[r - 1]; + addUtterance(i, rr.combat_at + s * 1000); +}); +for (const [t, who, ch, text] of [ + [3, 'p-ms', 'team', '미드 조심 오퍼 있음'], + [10, 'e-lm', 'all', 'gg ez'], + [16, 'p-dk', 'team', '나 돈 없음 드랍 좀'], +] as const) { + const r = pre.rounds[t - 1]; + games.event({ id: `${valId}:chat:demo${t}`, match_id: valId, game: 'valorant', type: 'chat', ts: r.combat_at + 25000, game_time_ms: null, round: null, actor_puuid: who, target_puuid: null, data: JSON.stringify({ sender: { puuid: who, name: md.players.find((p: any) => p.subject === who)!.gameName }, channel: ch, text, source: 'api' }) }); +} +games.matchEnded(valId, VS + md.matchInfo.gameLengthMillis); +(games.adapters[0] as any).applyDetails(valId, md, 'p-sh', VS); + +// 롤 +const lolId = 'lol-7700123'; +games.matchStarted({ id: lolId, game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } }); +LINES.forEach((l, i) => { + if ('lol' in l.at) addUtterance(i, LS + l.at.lol * 60_000); +}); +for (const [m, name, ch, text, src] of [ + [-1.5, '민수', 'team', '정글 갱 갈게요', 'lcu'], + [5.2, 'Lumi', 'all', '아리 잘하네', 'ocr'], + [11.4, '지우', 'team', '드래곤 가자', 'ocr'], + [28.5, 'Kiwi', 'all', 'gg', 'lcu'], +] as const) { + games.event({ id: `${lolId}:chat:demo${m}`, match_id: lolId, game: 'lol', type: 'chat', ts: LS + m * 60_000, game_time_ms: m * 60_000, round: null, actor_puuid: null, target_puuid: null, data: JSON.stringify({ sender: { name }, channel: ch, text, source: src }) }); +} +games.matchEnded(lolId, LS + lol.durationMs); +store.setMeta('riot_self_puuid', 'l-sh'); +(games.adapters[1] as any).applyHistory(lolId, lol.game, lol.timeline, LS); + +// 경기 밖 +LINES.forEach((l, i) => { + if ('off' in l.at) addUtterance(i, now + l.at.off * 60_000); +}); + +// STT 끝날 때까지 +const total = LINES.length; +const t0 = Date.now(); +for (;;) { + const done = (store.db.prepare(`SELECT count(*) n FROM utterances WHERE status!='pending'`).get() as any).n; + process.stdout.write(`\rSTT ${done}/${total}`); + if (done >= total) break; + if (Date.now() - t0 > 15 * 60_000) throw new Error('STT timeout'); + await new Promise((r) => setTimeout(r, 1000)); +} +console.log(`\nSTT 완료 (${((Date.now() - t0) / 1000).toFixed(0)}초)`); +let exact = 0; +for (const [i, l] of LINES.entries()) { + const r = store.getUtterance(`demo${String(i).padStart(3, '0')}`)!; + const ok = (r.text || '').replace(/\s/g, '') === l.text.replace(/\s/g, ''); + if (ok) exact++; + console.log(`${ok ? '=' : '≠'} ${l.text} → ${r.text}`); +} +console.log(`완전 일치 ${exact}/${total}`); + +// ---- 로컬 사이트 서버 + 중계 +const { buildServer } = await import('../../site/server/src/app.ts'); +const site = await buildServer({ + port: 0, + host: '127.0.0.1', + publicUrl: 'http://127.0.0.1', + clientId: 'x', + clientSecret: 'x', + botToken: 'x', + allowedGuilds: [], + owners: [USERS[0].id], + sessionSecret: 'demo-secret-'.repeat(3), + dataDir: path.join(work, 'site'), + webDir: path.join(root, 'site', 'web', 'dist'), + version: '1.0.0', + discordApi: 'http://127.0.0.1:1', + assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' }, +}); +site.app.log.level = 'warn'; +await site.app.listen({ host: '127.0.0.1', port: Number(process.env.DEMO_PORT || 0) }); +const base = `http://127.0.0.1:${(site.app.server.address() as any).port}`; +const { registerDevice } = await import('../src/core/relay/client.ts'); +const code = site.store.createCode('demo'); +const reg = await registerDevice(base, code.code, 'GAME-PC'); +core.settings.update({ site: { serverUrl: base, deviceId: reg.deviceId, deviceName: 'GAME-PC' } }); +core.settings.setSecret('deviceKey', reg.deviceKey); +core.relay.restart(); +const sess = site.store.createSession({ id: USERS[0].id, name: '승한', avatar: null }); +const cookie = { name: 'gvr_sid', value: site.app.signCookie(sess.id), url: base }; +while (core.relay.status.state !== 'online') await new Promise((r) => setTimeout(r, 100)); +console.log(`사이트: ${base} (쿠키 gvr_sid=${cookie.value})`); + +// ---- 화면 확인 +const puppeteer = (await import(path.join(os.homedir(), '.tmp/gvr-shot/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js'))).default; +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required', '--lang=ko-KR'] }); +const page = await browser.newPage(); +await page.setCookie(cookie); +const errs: string[] = []; +page.on('pageerror', (e: any) => errs.push(e.message)); +page.on('console', (m: any) => m.type() === 'error' && errs.push(m.text())); +fs.mkdirSync(shotDir, { recursive: true }); +const shot = async (url: string, name: string, w = 1440, h = 900, after?: () => Promise) => { + await page.setViewport({ width: w, height: h }); + await page.goto(base + url, { waitUntil: 'networkidle2' }); + await new Promise((r) => setTimeout(r, 1800)); + if (after) await after(); + await page.screenshot({ path: path.join(shotDir, name) }); + console.log('screenshot', name); +}; +await shot('/', 'real-timeline.png'); +await shot('/', 'real-timeline-playing.png', 1440, 900, async () => { + await page.evaluate(() => { + const rows = [...document.querySelectorAll('.it.utt')] as HTMLElement[]; + const target = rows.find((r) => r.textContent?.includes('치킨')) || rows[0]; + target?.click(); + }); + await new Promise((r) => setTimeout(r, 900)); +}); +await shot(`/matches/${valId}`, 'real-match-valorant.png', 1440, 900, async () => { + await page.evaluate(() => { + const b = [...document.querySelectorAll('button, .rnd, [data-round]')].find((x) => x.textContent?.trim() === '7') as HTMLElement | undefined; + b?.click(); + }); + await new Promise((r) => setTimeout(r, 800)); +}); +await shot(`/matches/${lolId}`, 'real-match-lol.png'); +await shot(`/users/${USERS[0].id}`, 'real-user.png'); +await shot('/', 'real-mobile.png', 390, 844); +// 연결 끊김 → 잠금, 다시 연결 → 해제 +core.relay.stop(); +await new Promise((r) => setTimeout(r, 2500)); +await page.setViewport({ width: 1440, height: 900 }); +await page.screenshot({ path: path.join(shotDir, 'real-locked.png') }); +const lockedVisible = await page.evaluate(() => !!document.querySelector('.lock')); +core.relay.start(); +await new Promise((r) => setTimeout(r, 4000)); +const unlocked = await page.evaluate(() => !document.querySelector('.lock')); +console.log(`잠금 표시 ${lockedVisible}, 재연결 후 해제 ${unlocked}`); +console.log('브라우저 오류:', errs.filter((e) => !/favicon|401/.test(e))); +await browser.close(); +if (!serve) { + await core.stop(); + await site.app.close(); + process.exit(lockedVisible && unlocked ? 0 : 1); +} +console.log('--serve: Ctrl+C 로 종료'); diff --git a/app/src/core/dict/dictionary.ts b/app/src/core/dict/dictionary.ts index fcb1bfc..822c576 100644 --- a/app/src/core/dict/dictionary.ts +++ b/app/src/core/dict/dictionary.ts @@ -14,7 +14,7 @@ const CONTEXT_PACKS: Record = { none: ['site', 'user', 'daily', 'university', 'slang20s', 'game', 'valorant', 'lol'], }; /** Whisper 프롬프트 길이 제한 때문에 핫워드는 이 정도까지만 */ -const MAX_HOTWORDS = 60; +const MAX_HOTWORDS = 40; export interface PackFile { meta: { generatedAt: string }; diff --git a/app/src/core/games/valorant.ts b/app/src/core/games/valorant.ts index 4271780..ed7492c 100644 --- a/app/src/core/games/valorant.ts +++ b/app/src/core/games/valorant.ts @@ -514,7 +514,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse 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), + score: p.stats?.score ?? 0, // 총 전투 점수 (사이트가 라운드 수로 나눠 ACS 표시) rank: assets.val?.tiers[p.competitiveTier] ?? null, })); const selfTeamInfo = (md.teams || []).find((t: any) => t.teamId === selfTeam); diff --git a/app/test/core.test.ts b/app/test/core.test.ts index e866021..601a829 100644 --- a/app/test/core.test.ts +++ b/app/test/core.test.ts @@ -85,7 +85,7 @@ test('사전: 기본 사전 적재, 상황별 핫워드, 사이트 교정 학습 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.length > 20 && hv.length <= 40); 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); diff --git a/app/test/e2e-stt.test.ts b/app/test/e2e-stt.test.ts index 507994d..e24e01f 100644 --- a/app/test/e2e-stt.test.ts +++ b/app/test/e2e-stt.test.ts @@ -76,7 +76,7 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API', 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(); + const search = (await core.api.inject({ method: 'GET', url: '/api/timeline?q=' + encodeURIComponent('궁 빠졌어') })).json(); assert.deepEqual(search.items.map((i: any) => i.id), ['speech']); } finally { await core.stop(); diff --git a/app/test/fixtures/demo-matches.ts b/app/test/fixtures/demo-matches.ts new file mode 100644 index 0000000..630c524 --- /dev/null +++ b/app/test/fixtures/demo-matches.ts @@ -0,0 +1,200 @@ +// 시연·통합 테스트용 경기 데이터 생성기 (실제 API 응답 구조: 발로란트 match-details, 롤 LCU match-history + timeline) +// 결정적(seed 고정)이라 매번 같은 경기가 나온다. +let seed = 7; +const rnd = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646; +const pick = (a: T[]): T => a[Math.floor(rnd() * a.length)]; +const range = (a: number, b: number) => a + Math.floor(rnd() * (b - a + 1)); + +export const AGENT = { + jett: 'add6443a-41bd-e414-f6ad-e58d267f4e95', + sova: '320b2a48-4d9b-a075-30f1-1f93a9b638fa', + sage: '569fdd95-4d10-43ab-ca70-79becc718b46', + omen: '8e253930-4c05-31dd-1b6c-968525494517', + killjoy: '1e58de9c-4950-5125-93e9-a0aee9f98746', + raze: 'f94c3b30-42be-e959-889c-5aa313dba261', + reyna: 'a3bfb853-43b2-7238-a4f1-ad90e9e46bcc', +}; +const WEAPON = { + vandal: '9C82E19D-4575-0200-1A81-3EACF00CF872', + phantom: 'EE8E8D15-496B-07AC-E5F6-8FAE5D4C7B1A', + operator: 'A03B24D3-4319-996D-0F8C-94BBFBA1DFC7', + sheriff: 'E336C6B8-418D-9340-D77F-7A9E4CFE0702', + classic: '29A0CFAB-485B-F5D5-779A-B59F85E204A8', + spectre: '462080D1-4035-2937-7C09-27AA2A5C27A7', +}; +// 어센트 미니맵 위 플레이 가능한 지점 (1024px 기준 u,v) → 게임 좌표 +const ASCENT = { xMultiplier: 7e-5, yMultiplier: -7e-5, xScalarToAdd: 0.813895, yScalarToAdd: 0.573242 }; +const SPOTS = [ + [320, 150], [300, 190], [400, 140], [410, 300], [480, 130], [500, 250], [330, 290], [200, 350], [500, 500], [540, 520], + [420, 500], [300, 480], [310, 570], [180, 640], [160, 450], [100, 450], [280, 800], [240, 770], [300, 700], [420, 750], + [560, 740], [800, 580], [900, 580], [790, 420], [600, 270], [690, 400], [560, 450], +]; +function loc() { + const s = pick(SPOTS); + const u = (s[0] + range(-12, 12)) / 1024; + const v = (s[1] + range(-12, 12)) / 1024; + return { x: Math.round((v - ASCENT.yScalarToAdd) / ASCENT.yMultiplier), y: Math.round((u - ASCENT.xScalarToAdd) / ASCENT.xMultiplier) }; +} + +export const VAL_PLAYERS = [ + { subject: 'p-sh', gameName: '승한', tagLine: 'KR1', teamId: 'Blue', characterId: AGENT.jett }, + { subject: 'p-ms', gameName: '민수', tagLine: '0707', teamId: 'Blue', characterId: AGENT.sova }, + { subject: 'p-jw', gameName: '지우', tagLine: 'KR2', teamId: 'Blue', characterId: AGENT.sage }, + { subject: 'p-hw', gameName: '현우', tagLine: 'HW1', teamId: 'Blue', characterId: AGENT.omen }, + { subject: 'p-dk', gameName: 'Duck', tagLine: 'KR3', teamId: 'Blue', characterId: AGENT.killjoy }, + { subject: 'e-lm', gameName: 'Lumi', tagLine: 'KR1', teamId: 'Red', characterId: AGENT.raze }, + { subject: 'e-hr', gameName: 'Haru', tagLine: 'KR2', teamId: 'Red', characterId: AGENT.reyna }, + { subject: 'e-kw', gameName: 'Kiwi', tagLine: 'KR9', teamId: 'Red', characterId: AGENT.sova }, + { subject: 'e-nx', gameName: 'Nox', tagLine: '0420', teamId: 'Red', characterId: AGENT.killjoy }, + { subject: 'e-mt', gameName: 'Mint', tagLine: '7777', teamId: 'Red', characterId: AGENT.omen }, +]; + +/** 22라운드 13:9 어센트 경쟁전 */ +export function makeDemoValorant(gameStart: number) { + seed = 11; + const W = 'WWLWLWWLLWWLWWLWLLWLWW'; // 우리 팀 기준 + const blue = VAL_PLAYERS.filter((p) => p.teamId === 'Blue').map((p) => p.subject); + const red = VAL_PLAYERS.filter((p) => p.teamId === 'Red').map((p) => p.subject); + const stats: Record = {}; + for (const p of VAL_PLAYERS) stats[p.subject] = { kills: 0, deaths: 0, assists: 0, score: 0 }; + let t = 0; + const roundResults: any[] = []; + for (let i = 0; i < W.length; i++) { + const win = W[i] === 'W'; + const roundStart = t; + const combat = roundStart + (i === 0 || i === 12 ? 45000 : 30000); + const aliveB = new Set(blue); + const aliveR = new Set(red); + const kills: any[] = []; + let rt = range(8000, 20000); + const pistol = i === 0 || i === 12; + while (aliveB.size && aliveR.size) { + const blueKills = win ? rnd() < 0.62 : rnd() < 0.38; + const killer = pick([...(blueKills ? aliveB : aliveR)]); + const victim = pick([...(blueKills ? aliveR : aliveB)]); + (blueKills ? aliveR : aliveB).delete(victim); + const assistants = rnd() < 0.5 ? [pick([...(blueKills ? aliveB : aliveR)].filter((x) => x !== killer) || [])].filter(Boolean) : []; + kills.push({ + gameTime: combat + rt, + roundTime: rt, + killer, + victim, + victimLocation: loc(), + assistants, + playerLocations: [], + finishingDamage: { damageType: 'Weapon', damageItem: pistol ? pick([WEAPON.classic, WEAPON.sheriff]) : pick([WEAPON.vandal, WEAPON.vandal, WEAPON.phantom, WEAPON.operator, WEAPON.spectre]), isSecondaryFireMode: false }, + }); + stats[killer].kills++; + stats[victim].deaths++; + for (const a of assistants) stats[a].assists++; + rt += range(3000, 16000); + if ((win && !aliveR.size) || (!win && !aliveB.size)) break; + if (kills.length >= 8 && rnd() < 0.5) break; + } + const planted = rnd() < 0.55; + const result = !aliveB.size || !aliveR.size ? 'Eliminated' : planted ? (win ? 'Bomb defused' : 'Bomb detonated') : 'Round timer expired'; + const end = combat + Math.max(rt + 4000, planted ? 80000 : 60000); + const playerStats = VAL_PLAYERS.map((p) => ({ + subject: p.subject, + kills: kills.filter((k) => k.killer === p.subject), + score: kills.filter((k) => k.killer === p.subject).length * 200 + range(0, 150), + economy: { spent: pistol ? 800 : range(1500, 4700), remaining: range(0, 3000), loadoutValue: 0, weapon: pistol ? WEAPON.classic : pick([WEAPON.vandal, WEAPON.phantom]), armor: '' }, + })); + for (const ps of playerStats) stats[ps.subject].score += ps.score; + roundResults.push({ + roundNum: i, + roundResult: result, + winningTeam: win ? 'Blue' : 'Red', + plantRoundTime: planted ? range(35000, 60000) : undefined, + plantSite: planted ? pick(['A', 'B']) : undefined, + bombPlanter: planted ? pick(win ? red : red) : undefined, + defuseRoundTime: planted && win ? range(70000, 85000) : undefined, + bombDefuser: planted && win ? pick(blue) : undefined, + playerStats, + }); + t = end + 8000; + } + return { + matchInfo: { matchId: 'demo-ascent-01', mapId: '/Game/Maps/Ascent/Ascent', gameStartMillis: gameStart, gameLengthMillis: t, queueID: 'competitive', gameMode: '/Game/GameModes/Bomb/BombGameMode.BombGameMode_C', isCompleted: true }, + players: VAL_PLAYERS.map((p) => ({ ...p, competitiveTier: range(12, 18), stats: { ...stats[p.subject], roundsPlayed: W.length } })), + teams: [ + { teamId: 'Blue', won: true, roundsWon: [...W].filter((c) => c === 'W').length }, + { teamId: 'Red', won: false, roundsWon: [...W].filter((c) => c === 'L').length }, + ], + roundResults, + }; +} + +// ------------------------------------------------------------------ 롤 +const LOL = [ + { pid: 1, champ: 103, team: 100, puuid: 'l-sh', name: '승한', tag: 'KR1' }, // 아리 미드 + { pid: 2, champ: 64, team: 100, puuid: 'l-ms', name: '민수', tag: '0707' }, // 리 신 + { pid: 3, champ: 86, team: 100, puuid: 'l-hw', name: '현우', tag: 'HW1' }, // 가렌 + { pid: 4, champ: 81, team: 100, puuid: 'l-jw', name: '지우', tag: 'KR2' }, // 이즈리얼 + { pid: 5, champ: 412, team: 100, puuid: 'l-dk', name: 'Duck', tag: 'KR3' }, // 쓰레쉬 + { pid: 6, champ: 7, team: 200, puuid: 'r-1', name: 'Lumi', tag: 'KR1' }, // 르블랑 + { pid: 7, champ: 113, team: 200, puuid: 'r-2', name: 'Haru', tag: 'KR2' }, // 세주아니 + { pid: 8, champ: 122, team: 200, puuid: 'r-3', name: 'Kiwi', tag: 'KR9' }, // 다리우스 + { pid: 9, champ: 222, team: 200, puuid: 'r-4', name: 'Nox', tag: '0420' }, // 징크스 + { pid: 10, champ: 89, team: 200, puuid: 'r-5', name: 'Mint', tag: '7777' }, // 레오나 +]; +export function makeDemoLol() { + seed = 23; + const dur = 28 * 60; + const st: Record = {}; + for (const p of LOL) st[p.pid] = { kills: 0, deaths: 0, assists: 0 }; + const frames: any[] = []; + let ga = 0; + let gr = 0; + const dragons = ['FIRE_DRAGON', 'WATER_DRAGON', 'EARTH_DRAGON', 'FIRE_DRAGON']; + let di = 0; + for (let m = 0; m <= 28; m++) { + const events: any[] = []; + const inc = (team: number) => 300 + range(150, 420) + (team === 100 ? m * 12 : 0); + ga += m ? inc(100) * 5 : 2500; + gr += m ? inc(200) * 5 : 2500; + if (m >= 3) + for (let k = 0; k < range(0, 2); k++) { + const blueKill = rnd() < 0.58; + const killer = pick(LOL.filter((p) => (p.team === 100) === blueKill)); + const victim = pick(LOL.filter((p) => (p.team === 100) !== blueKill)); + const assists = rnd() < 0.6 ? [pick(LOL.filter((p) => p.team === killer.team && p !== killer)).pid] : []; + st[killer.pid].kills++; + st[victim.pid].deaths++; + for (const a of assists) st[a].assists++; + events.push({ type: 'CHAMPION_KILL', timestamp: m * 60000 + range(1000, 58000), killerId: killer.pid, victimId: victim.pid, assistingParticipantIds: assists, position: { x: range(1500, 13500), y: range(1500, 13500) } }); + if (blueKill) ga += 300; + else gr += 300; + } + if ([6, 12, 18, 24].includes(m)) events.push({ type: 'ELITE_MONSTER_KILL', timestamp: m * 60000 + 20000, killerId: m === 18 ? 7 : 2, monsterType: 'DRAGON', monsterSubType: dragons[di++], position: { x: 9866, y: 4414 } }); + if (m === 8) events.push({ type: 'ELITE_MONSTER_KILL', timestamp: m * 60000 + 30000, killerId: 2, monsterType: 'HORDE', position: { x: 5007, y: 10471 } }); + if (m === 21) events.push({ type: 'ELITE_MONSTER_KILL', timestamp: m * 60000 + 40000, killerId: 2, monsterType: 'BARON_NASHOR', position: { x: 5007, y: 10471 } }); + if ([10, 14, 16, 22, 25, 26].includes(m)) events.push({ type: 'BUILDING_KILL', timestamp: m * 60000 + 45000, killerId: 1, teamId: 200, buildingType: m === 26 ? 'INHIBITOR_BUILDING' : 'TOWER_BUILDING', position: { x: 8955 + m * 100, y: 8510 + m * 80 } }); + if ([13, 19].includes(m)) events.push({ type: 'BUILDING_KILL', timestamp: m * 60000 + 15000, killerId: 8, teamId: 100, buildingType: 'TOWER_BUILDING', position: { x: 5846, y: 6396 } }); + events.sort((a, b) => a.timestamp - b.timestamp); + const pf: Record = {}; + for (const p of LOL) pf[String(p.pid)] = { totalGold: Math.round((p.team === 100 ? ga : gr) / 5) }; + frames.push({ timestamp: m * 60000, participantFrames: pf, events }); + } + const items = [3031, 3089, 3157, 3020, 6655, 3135]; + return { + game: { + gameId: 7700123, + gameDuration: dur, + queueId: 420, + participants: LOL.map((p) => ({ + participantId: p.pid, + championId: p.champ, + teamId: p.team, + stats: { ...st[p.pid], totalMinionsKilled: range(30, 230), neutralMinionsKilled: p.pid === 2 || p.pid === 7 ? range(120, 180) : range(0, 15), goldEarned: Math.round((p.team === 100 ? ga : gr) / 5) + range(-800, 800), item0: pick(items), item1: pick(items), item2: pick(items), champLevel: range(13, 18), win: p.team === 100 }, + })), + participantIdentities: LOL.map((p) => ({ participantId: p.pid, player: { puuid: p.puuid, gameName: p.name, tagLine: p.tag } })), + teams: [ + { teamId: 100, win: 'Win' }, + { teamId: 200, win: 'Fail' }, + ], + }, + timeline: { frames }, + durationMs: dur * 1000, + }; +} diff --git a/docs/dev/screens/real-locked.png b/docs/dev/screens/real-locked.png new file mode 100644 index 0000000..b277dde Binary files /dev/null and b/docs/dev/screens/real-locked.png differ diff --git a/docs/dev/screens/real-match-lol.png b/docs/dev/screens/real-match-lol.png new file mode 100644 index 0000000..5d72c5d Binary files /dev/null and b/docs/dev/screens/real-match-lol.png differ diff --git a/docs/dev/screens/real-match-valorant.png b/docs/dev/screens/real-match-valorant.png new file mode 100644 index 0000000..675c0b0 Binary files /dev/null and b/docs/dev/screens/real-match-valorant.png differ diff --git a/docs/dev/screens/real-mobile.png b/docs/dev/screens/real-mobile.png new file mode 100644 index 0000000..419489b Binary files /dev/null and b/docs/dev/screens/real-mobile.png differ diff --git a/docs/dev/screens/real-timeline-playing.png b/docs/dev/screens/real-timeline-playing.png new file mode 100644 index 0000000..6220704 Binary files /dev/null and b/docs/dev/screens/real-timeline-playing.png differ diff --git a/docs/dev/screens/real-timeline.png b/docs/dev/screens/real-timeline.png new file mode 100644 index 0000000..bed4837 Binary files /dev/null and b/docs/dev/screens/real-timeline.png differ diff --git a/docs/dev/screens/real-user.png b/docs/dev/screens/real-user.png new file mode 100644 index 0000000..8fae959 Binary files /dev/null and b/docs/dev/screens/real-user.png differ diff --git a/docs/dev/test-results.md b/docs/dev/test-results.md index d470875..923a597 100644 --- a/docs/dev/test-results.md +++ b/docs/dev/test-results.md @@ -33,3 +33,15 @@ VOICE E2E PASS - `cd site/web && npm run typecheck && npm run build` — 오류 0. 가짜 서버로 18개 동작(무한 스크롤, 필터 URL, 검색, 재생·단어 강조, 이어듣기, 단축키, 교정, 잠금/해제, 경기 상세) 헤드리스 확인 - 실서버: https://gvr.tkrmagid.kr 배포. 등록 코드로 개발 서버의 코어를 등록 → `wss://gvr.tkrmagid.kr/device/ws` 로 연결·ping 확인 (`app/scripts/site-e2e.mts`) 후 테스트 기기는 등록 해제 - 화면: `site/web/screenshots/` (가짜 데이터), `docs/dev/live-login.png` (실서버 로그인 화면) + +## M3 발로란트 연동 (2026-10-15) + +- `app/test/games.test.ts` — 가짜 Riot 서버(실제 API 구조)로 presence 경기 시작 → 팀/전체 채팅 → 실시간 점수 변화 라운드 → 경기 종료 → match-details 적용(라운드 3, 킬 4, 스파이크, 실시간 라운드 교체, 주인 계정 자동 연결) +- `app/scripts/demo-stack.mts` — **전체 스택**: 실제 코어 + STT 워커 + 실제 사이트 서버 코드 + 중계 + 헤드리스 브라우저 + - 발로란트 22라운드(13:9 어센트) match-details 구조 데이터 + TTS 대화 17문장을 라운드 시간에 맞춰 넣고 STT → 경기 상세 화면 확인 + - 시간 표시 `R7 · 0:38` + 경기 경과, 라운드 띠, 미니맵 킬 위치(게임 좌표 → 지도 변환), 킬피드, 스코어보드(ACS), 라운드별 크레딧 + - 잠금: 게임 PC 연결을 끊으면 2.5초 안에 잠금 화면, 다시 연결하면 자동 해제 (`잠금 표시 true, 재연결 후 해제 true`) + - 화면: `docs/dev/screens/real-*.png` +- STT(개발 서버 CPU, small) 28문장 중 15문장 완전 일치. 나머지는 띄어쓰기·문장부호·붙은 단어 차이가 대부분 +- 발견·수정: 작은 모델이 말을 못 알아들으면 핫워드 목록을 그대로 읽는 문제("가렌 점멸 빠졌어" → "탑라이너 바텀 슈퍼미니언…") → 핫워드 40개로 줄이고, 결과가 핫워드 되풀이면 핫워드 없이 다시 변환 (`worker/tests/test_hotword_echo.py`) +- 발견·수정: ACS 가 12처럼 작게 나오던 문제 (API 는 총 전투 점수, 화면이 라운드 수로 나눔) diff --git a/worker/gvr_worker/stt.py b/worker/gvr_worker/stt.py index 559505e..ef5208a 100644 --- a/worker/gvr_worker/stt.py +++ b/worker/gvr_worker/stt.py @@ -153,22 +153,33 @@ class SttEngine: 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 + hotwords = hotwords if isinstance(hotwords, str) and hotwords.strip() else None + + def run(hw: str | None) -> list[Any]: + 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=hw, + initial_prompt=req.get("initial_prompt") or None, + condition_on_previous_text=False, + ) + return list(segments) + except Exception as e: # noqa: BLE001 + raise WorkerError("transcribe_failed", f"음성 변환 실패: {e}") from e + + segs = run(hotwords) + # 핫워드 되풀이 방지: Whisper 가 말을 못 알아들으면 프롬프트(핫워드 목록)를 그대로 읽어 버리는 경우가 있다. + # 결과가 핫워드로만 채워져 있으면 핫워드 없이 한 번 더 돌려 그 결과를 쓴다. + if hotwords and is_hotword_echo("".join(x.text for x in segs), hotwords): + log.info("핫워드 되풀이 감지 → 핫워드 없이 다시 변환") + segs = run(None) + result["hotword_retry"] = True words: list[dict[str, Any]] = [] for seg in segs: @@ -195,3 +206,32 @@ class SttEngine: text, out_words = corrector.correct_text(raw_text), [] result.update(text=text, words=out_words) return done() + + +def is_hotword_echo(text: str, hotwords: str) -> bool: + """결과 문장이 핫워드 목록을 되풀이한 것인지. + + - 단어 3개 이상이고 그중 60% 이상이 핫워드와 정확히 같거나 + - 핫워드 목록에 나온 순서대로 핫워드 3개 이상이 연달아 나오면 되풀이로 본다. + """ + toks = [t.strip(".,!?~") for t in text.split()] + toks = [t for t in toks if t] + if len(toks) < 3: + return False + hw = [h for h in hotwords.split() if h] + hwset = set(hw) + hits = sum(1 for t in toks if t in hwset) + if hits / len(toks) >= 0.6: + return True + pos = {h: i for i, h in enumerate(hw)} + run_len, prev = 0, -1 + for t in toks: + i = pos.get(t) + if i is not None and i > prev: + run_len += 1 + prev = i + if run_len >= 3: + return True + else: + run_len, prev = (1, i) if i is not None else (0, -1) + return False diff --git a/worker/tests/test_hotword_echo.py b/worker/tests/test_hotword_echo.py new file mode 100644 index 0000000..f43cd7e --- /dev/null +++ b/worker/tests/test_hotword_echo.py @@ -0,0 +1,17 @@ +from gvr_worker.stt import is_hotword_echo + +HW = "바론 드래곤 용 장로 전령 유충 억제기 포탑 탑라이너 바텀 슈퍼미니언 정글러 미드라이너 갱킹 백도어 텔" + + +def test_echo_detected_when_output_is_hotword_list(): + assert is_hotword_echo("탑라이너 바텀 슈퍼미니언 정글러 미드라이너 갱킹 백도어 텔", HW) + + +def test_echo_detected_ordered_run(): + assert is_hotword_echo("음 바론 드래곤 용 그래서", HW) + + +def test_normal_sentence_with_some_hotwords_is_kept(): + assert not is_hotword_echo("드래곤 가자 바텀으로 모여", HW) + assert not is_hotword_echo("바론 치자 시야 잡아줘", HW) + assert not is_hotword_echo("포탑 밀자", HW)