138 lines
8.9 KiB
TypeScript
138 lines
8.9 KiB
TypeScript
// 실제 STT 워커(CPU, tiny)와 코어를 붙여 "발화 저장 → 대기열 → STT → DB → 실시간 이벤트 → API" 를 확인한다.
|
|
// 워커 venv(worker/.venv)와 HF 캐시의 tiny 모델이 있어야 한다. 없으면 건너뛴다.
|
|
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';
|
|
|
|
const root = path.resolve(import.meta.dirname, '..', '..');
|
|
const py = path.join(root, 'worker', '.venv', 'bin', 'python');
|
|
const hfTiny = path.join(os.homedir(), '.cache/huggingface/hub/models--Systran--faster-whisper-tiny/snapshots');
|
|
const skip = !fs.existsSync(py) || !fs.existsSync(hfTiny);
|
|
|
|
test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API', { skip, timeout: 180000 }, async () => {
|
|
const { startCore } = await import('../src/core/index.ts');
|
|
const dataDir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-e2e-'));
|
|
const models = path.join(dataDir, 'models');
|
|
fs.mkdirSync(models, { recursive: true });
|
|
fs.symlinkSync(path.join(hfTiny, fs.readdirSync(hfTiny)[0]), path.join(models, 'tiny'));
|
|
fs.writeFileSync(
|
|
path.join(dataDir, 'settings.json'),
|
|
JSON.stringify({ stt: { realtimeModel: 'tiny', preciseModel: 'tiny', device: 'cpu', computeType: 'int8' }, games: { valorant: false, lol: false } }),
|
|
);
|
|
const core = await startCore({
|
|
dataDir,
|
|
resourcesDir: path.join(root, 'app', 'resources'),
|
|
worker: { cmd: py, args: ['-m', 'gvr_worker'], cwd: path.join(root, 'worker') },
|
|
version: 'test',
|
|
});
|
|
const live: any[] = [];
|
|
core.bus.on('live', (e) => live.push(e));
|
|
try {
|
|
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}: ${JSON.stringify(core.stt.status)}`);
|
|
await new Promise((r) => setTimeout(r, 100));
|
|
}
|
|
};
|
|
await wait(() => core.stt.status.slots.realtime.state === 'loaded', 60000, 'model load');
|
|
core.store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
|
const fx = path.join(root, 'worker', 'tests', 'fixtures');
|
|
const items: [string, string][] = [
|
|
['speech', 'speech_ko.ogg'],
|
|
['quiet', 'speech_ko_quiet.ogg'],
|
|
['keys', 'keyboard_clicks.ogg'],
|
|
];
|
|
const t0 = Date.now();
|
|
for (const [id, f] of items) {
|
|
const dst = path.join(core.paths().audio, 'test', `${id}.ogg`);
|
|
fs.mkdirSync(path.dirname(dst), { recursive: true });
|
|
fs.copyFileSync(path.join(fx, f), dst);
|
|
core.store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: t0, ended_at: t0 + 3000, audio_path: dst, match_id: null });
|
|
core.stt.enqueue(id, 'realtime');
|
|
}
|
|
await wait(() => items.every(([id]) => core.store.getUtterance(id)!.status !== 'pending'), 120000, 'transcribe');
|
|
const sp = core.store.getUtterance('speech')!;
|
|
console.log('speech →', sp.text, '| raw:', sp.raw_text, '| gain', sp.gain_db);
|
|
assert.ok(['realtime', 'precise'].includes(sp.status), sp.status);
|
|
assert.ok(sp.text && sp.text.includes('레이즈'), sp.text ?? '');
|
|
assert.ok(JSON.parse(sp.words).length >= 3);
|
|
const q = core.store.getUtterance('quiet')!;
|
|
assert.ok(q.gain_db > 15, `quiet gain ${q.gain_db}`);
|
|
const k = core.store.getUtterance('keys')!;
|
|
assert.equal(k.noise, 1);
|
|
// 잡음: 파일을 지우고 사이트에 보이지 않는다
|
|
assert.equal(k.audio_deleted, 1);
|
|
assert.ok(!fs.existsSync(k.audio_path!));
|
|
assert.ok(live.filter((e) => e.type === 'utterance.updated').length >= 3);
|
|
// 기록 API (사이트가 중계로 부르는 것과 같은 경로)
|
|
const res = await core.api.inject({ method: 'GET', url: '/api/timeline?limit=10' });
|
|
const page = res.json();
|
|
assert.deepEqual(page.items.map((i: any) => i.id).sort(), ['quiet', 'speech']);
|
|
// 우클릭 → 자세한 정보: 원본 ogg 이름 · 경로
|
|
const info = (await core.api.inject({ method: 'GET', url: '/api/utterances/speech/info' })).json();
|
|
// 변환이 끝나면 녹음 파일 이름을 날짜 · 시각 · 말한 사람 · 경기 밖 · 발화 ID 로 바꾼다
|
|
assert.match(info.fileName, /^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_하늘_경기밖_speech\.ogg$/);
|
|
const sp2 = core.store.getUtterance('speech')!;
|
|
assert.equal(info.path, sp2.audio_path);
|
|
assert.ok(fs.existsSync(sp2.audio_path!));
|
|
assert.equal(info.folder, path.dirname(sp2.audio_path!));
|
|
assert.ok(info.sizeBytes > 1000);
|
|
assert.equal(info.deleted, null);
|
|
assert.equal((await core.api.inject({ method: 'GET', url: '/api/utterances/keys/info' })).json().deleted, 'noise');
|
|
const audio = await core.api.inject({ method: 'GET', url: '/api/audio/speech', headers: { range: 'bytes=0-99' } });
|
|
assert.equal(audio.statusCode, 206);
|
|
assert.equal(audio.rawPayload.length, 100);
|
|
// 사이트 교정 → 사전·학습 데이터
|
|
const patched = await core.api.inject({ method: 'PATCH', url: '/api/utterances/speech', payload: { text: '레이즈 궁 빠졌어 B 사이트 로테 하자' } });
|
|
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('궁 빠졌어') })).json();
|
|
assert.deepEqual(search.items.map((i: any) => i.id), ['speech']);
|
|
// 기록 묶음 API: 목록 → zip → 지우기 → 받아오기
|
|
const bl = (await core.api.inject({ method: 'GET', url: '/api/bundles' })).json().bundles;
|
|
assert.equal(bl.length, 1);
|
|
assert.equal(bl[0].label, '게임 밖 대화');
|
|
const ex = await core.api.inject({ method: 'GET', url: `/api/bundles/export?ids=${bl[0].id}` });
|
|
assert.equal(ex.headers['content-type'], 'application/zip');
|
|
assert.match(String(ex.headers['content-disposition']), /attachment; filename="gvr-talk-\d{8}-\d{4}\.zip"/);
|
|
// 사이트 중계로 온 요청은 사이트 서버가 붙인 역할이 관리자여야 한다
|
|
const user = encodeURIComponent(JSON.stringify({ id: 'm1', name: 'x', avatar: null }));
|
|
assert.equal((await core.api.inject({ method: 'POST', url: '/api/bundles/delete', headers: { 'x-gvr-user': user, 'x-gvr-role': 'member' }, payload: { ids: [bl[0].id] } })).statusCode, 403);
|
|
assert.equal((await core.api.inject({ method: 'POST', url: '/api/bundles/delete', headers: { 'x-gvr-user': user }, payload: { ids: [bl[0].id] } })).statusCode, 403);
|
|
const del = (await core.api.inject({ method: 'POST', url: '/api/bundles/delete', payload: { ids: [bl[0].id] } })).json();
|
|
assert.equal(del.utterances, 3);
|
|
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 0);
|
|
const bad = await core.api.inject({ method: 'POST', url: '/api/bundles/import', headers: { 'content-type': 'application/zip' }, payload: Buffer.from('PK nope') });
|
|
assert.equal(bad.statusCode, 400);
|
|
assert.match(bad.json().message, /^받아오기 실패/);
|
|
const imp = (await core.api.inject({ method: 'POST', url: '/api/bundles/import', headers: { 'content-type': 'application/zip' }, payload: ex.rawPayload })).json();
|
|
assert.equal(imp.added.utterances, 2, '잡음(keys)은 내보내지 않는다');
|
|
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 2);
|
|
assert.ok(live.some((e) => e.type === 'records.changed'));
|
|
// 우클릭 → 삭제 → "잡음이라 삭제" (v1.4.0): 인식된 문장을 배우고, 같은 녹음이 다시 들어오면 잡음으로 숨긴다
|
|
const heard = core.store.getUtterance('speech')!.raw_text!;
|
|
const nd = await core.api.inject({ method: 'POST', url: '/api/utterances/speech/delete', headers: { 'x-gvr-user': encodeURIComponent(JSON.stringify({ id: 'u1', name: '하늘', avatar: null })), 'x-gvr-role': 'member' }, payload: { noise: true } });
|
|
assert.deepEqual(nd.json(), { ok: true, learned: heard });
|
|
assert.equal(core.store.getUtterance('speech'), undefined);
|
|
const again = path.join(core.paths().audio, 'test', 'again.ogg');
|
|
fs.copyFileSync(path.join(fx, 'speech_ko.ogg'), again);
|
|
core.store.insertUtterance({ id: 'again', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 3000, audio_path: again, match_id: null });
|
|
core.stt.enqueue('again', 'realtime');
|
|
await wait(() => core.store.getUtterance('again')!.status !== 'pending', 60000, 'transcribe again');
|
|
const ag = core.store.getUtterance('again')!;
|
|
console.log('again →', ag.noise, ag.noise_reason, '| raw:', ag.raw_text);
|
|
assert.equal(ag.noise, 1);
|
|
assert.equal(ag.noise_reason, 'learned');
|
|
assert.equal(ag.audio_deleted, 1);
|
|
assert.ok(!fs.existsSync(again));
|
|
assert.equal(core.store.listNoisePhrases()[0].hits, 1);
|
|
assert.ok(!(await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.some((i: any) => i.id === 'again'));
|
|
} finally {
|
|
await core.stop();
|
|
}
|
|
});
|