Files
game_voice_recorder/app/test/core.test.ts
EJClaw 5222b3ee72 M3: 발로란트 연동 - 전체 스택 시연·테스트, 핫워드 되풀이 방지
- scripts/demo-stack.mts: 코어+STT+사이트 서버+중계+헤드리스 브라우저 전체 스택 (22라운드 어센트, TTS 대화, 잠금/해제)
- test/fixtures/demo-matches.ts: match-details·LCU 구조 시연 데이터
- 워커: 결과가 핫워드 목록 되풀이면 핫워드 없이 다시 변환, 핫워드 40개
- ACS: API 는 총 전투 점수

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 01:41:02 +09:00

186 lines
9.1 KiB
TypeScript

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 <= 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);
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();
});