diff --git a/app/src/core/games/lol.ts b/app/src/core/games/lol.ts index 0bc1bfc..0baafae 100644 --- a/app/src/core/games/lol.ts +++ b/app/src/core/games/lol.ts @@ -87,6 +87,10 @@ export class LolAdapter implements GameAdapter { status() { return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined }; } + /** 롤은 경기 중에만 (클라이언트 화면은 가볍다) */ + gameRunning(): boolean { + return !!this.live && !this.live.ended; + } liveGame(): LiveGame { const enabled = this.host.settings().games.lol; diff --git a/app/src/core/games/manager.ts b/app/src/core/games/manager.ts index b2449b2..a0a5e7d 100644 --- a/app/src/core/games/manager.ts +++ b/app/src/core/games/manager.ts @@ -73,6 +73,7 @@ export class GameManager implements AdapterHost { private watchLive(): void { if (this.liveTimer) return; this.liveTimer = setInterval(() => { + void this.stt.setGameActive(this.adapters.some((a) => this.settings().games[a.game] && a.gameRunning())); const live = this.live(); const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest)); if (key === this.lastLive) return; diff --git a/app/src/core/games/types.ts b/app/src/core/games/types.ts index 57328e4..ecc1faa 100644 --- a/app/src/core/games/types.ts +++ b/app/src/core/games/types.ts @@ -39,6 +39,8 @@ export interface GameAdapter { start(): void; stop(): void; status(): { connected: boolean; inMatch: boolean; detail?: string }; + /** 게임이 켜져 있어 GPU 를 쓰고 있는가 (발로란트: 게임 실행 중 · 롤: 경기 중) */ + gameRunning(): boolean; /** 지금 게임 상태 (자세히) */ liveGame(): LiveGame; } diff --git a/app/src/core/games/valorant.ts b/app/src/core/games/valorant.ts index 31af413..2d8bf2e 100644 --- a/app/src/core/games/valorant.ts +++ b/app/src/core/games/valorant.ts @@ -91,6 +91,10 @@ export class ValorantAdapter implements GameAdapter { status() { return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined }; } + /** 발로란트는 메뉴에서도 게임 화면을 그린다: 게임이 켜져 있으면(내 발로란트 상태가 있으면) 켜짐 */ + gameRunning(): boolean { + return !!this.match || (!!this.auth && !!this.presence); + } liveGame(): LiveGame { const p = this.presence; @@ -206,9 +210,10 @@ export class ValorantAdapter implements GameAdapter { if (a) { await this.pollPresence(a); if (this.match) await this.pollChat(a); - } else if (this.match) { + } else { + this.presence = null; // 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다 - this.endMatch(); + if (this.match) this.endMatch(); } await this.pollDetails(); this.lastErr = ''; diff --git a/app/src/core/settings.ts b/app/src/core/settings.ts index 26d4284..21eeddf 100644 --- a/app/src/core/settings.ts +++ b/app/src/core/settings.ts @@ -33,6 +33,8 @@ export interface Settings { modelsDir: string | null; reprocessAfterMatch: boolean; gameVramReserveMb: number; + /** 게임이 켜져 있는 동안 GPU 를 아낀다: 실시간 모델만 가볍게(빔 1) · 쉬어 가며, 정밀 모델 변환은 게임을 끈 뒤로 (v1.9.0) */ + gameSaver: boolean; }; audio: { targetLufs: number; @@ -111,6 +113,7 @@ export function defaultSettings(): Settings { modelsDir: null, reprocessAfterMatch: true, gameVramReserveMb: 3072, + gameSaver: true, }, audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 }, dictionary: { diff --git a/app/src/core/stt/pipeline.ts b/app/src/core/stt/pipeline.ts index 17f5e74..4ea39c8 100644 --- a/app/src/core/stt/pipeline.ts +++ b/app/src/core/stt/pipeline.ts @@ -100,6 +100,12 @@ export class SttPipeline { return c ? Number(c) : null; } private inMatch = false; + /** 게임(발로란트 · 롤 경기)이 켜져 있다 (GameManager 가 2초마다 알려 줌) */ + private gameActive = false; + /** 게임 중 GPU 아끼기: 켜져 있고 게임 중일 때 */ + private saving(): boolean { + return this.gameActive && this.settings().stt.gameSaver !== false; + } /** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */ private bothFit = true; status: SttStatus = { @@ -143,10 +149,46 @@ export class SttPipeline { this.bothFit = false; } await this.load('realtime', s.realtimeModel); - if (this.bothFit && !this.inMatch) await this.load('precise', s.preciseModel); + if (this.bothFit && !this.inMatch && !this.saving()) await this.load('precise', s.preciseModel); this.pump(); } + /** + * 게임이 켜지고 꺼질 때 (v1.9.0). 게임 중 GPU 아끼기가 켜져 있으면 + * 켜질 때 정밀 모델을 내리고(정밀 변환은 대기열에서 기다림), 꺼지면 다시 올려 밀린 정밀 변환을 한다. + */ + async setGameActive(on: boolean): Promise { + if (this.gameActive === on) return; + this.gameActive = on; + const s = this.settings().stt; + if (on) { + if (s.gameSaver === false) return; + log.info('게임 켜짐: GPU 아끼기 (실시간 모델만 가볍게, 정밀 변환은 게임을 끈 뒤)'); + if (this.status.slots.precise.state === 'loaded') await this.unload('precise'); + return; + } + if (s.gameSaver !== false || this.queue.some((j) => j.slot === 'precise')) log.info('게임 꺼짐: 밀린 정밀 변환 시작'); + if (this.status.worker !== 'ready') return; // 워커가 켜지면 prepareModels 가 이어서 한다 + const wantPrecise = this.queue.some((j) => j.slot === 'precise') || this.bothFit; + if (wantPrecise) await this.load('precise', s.preciseModel); + if (this.gameActive) return; // 올리는 동안 게임이 다시 켜짐 + // 정밀 모델이 없으면(설치 안 됨 · 실패) 기다리던 정밀 변환은 버린다 (실시간 결과가 그대로 남음) + if (this.status.slots.precise.state !== 'loaded') this.dropPrecise(); + else if (!this.bothFit && !this.queue.some((j) => j.slot === 'precise')) await this.unload('precise'); + this.pump(); + } + + private dropPrecise(): void { + const before = this.queue.length; + this.queue = this.queue.filter((j) => { + if (j.slot !== 'precise') return true; + this.queued.delete(`precise:${j.id}`); + return false; + }); + this.status.queue = this.queue.length; + if (before !== this.queue.length) log.info(`정밀 모델이 없어 정밀 변환 ${before - this.queue.length}개를 건너뜀`); + } + private async installed(): Promise> { try { const r = await this.worker.request('models', {}, 30000); @@ -223,6 +265,13 @@ export class SttPipeline { this.inMatch = false; const s = this.settings().stt; if (!s.reprocessAfterMatch || s.preciseModel === s.realtimeModel) return; + if (this.saving()) { + // 게임(발로란트 메뉴 등)이 아직 켜져 있으면 정밀 변환은 대기열에서 게임이 꺼질 때까지 기다린다 + const rows = this.store.realtimeUtterancesInRange(from, to); + log.info(`경기 종료: ${rows.length}개 발화의 정밀 변환은 게임을 끈 뒤에`); + for (const r of rows) this.enqueue(r.id, 'precise', 10); + return; + } if (this.status.slots.precise.state !== 'loaded') await this.load('precise', s.preciseModel); if (this.status.slots.precise.state !== 'loaded') return; const rows = this.store.realtimeUtterancesInRange(from, to); @@ -232,6 +281,11 @@ export class SttPipeline { private pickSlot(job: Job): Slot | null { const { realtime, precise } = this.status.slots; + if (this.saving()) { + // 게임 중: 정밀 변환은 기다리고, 새 발화는 실시간 모델로만 + if (job.slot === 'precise') return null; + return realtime.state === 'loaded' ? 'realtime' : null; + } if (job.slot === 'precise') return precise.state === 'loaded' ? 'precise' : null; // 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로 if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise'; @@ -255,6 +309,7 @@ export class SttPipeline { this.busy = true; this.processing = job.id; this.status.processing = job.id; + const t0 = Date.now(); this.run(job, this.pickSlot(job)!) .catch((e) => log.error('STT 작업 오류', e)) .finally(() => { @@ -267,7 +322,9 @@ export class SttPipeline { } catch (e) { log.warn('변환 뒤 처리 실패', e); } - setImmediate(() => this.pump()); + // 게임 중에는 변환한 만큼(최대 3초) 쉬고 다음 발화로: 여러 명이 연달아 말해도 GPU 를 계속 붙잡지 않는다 + if (this.saving()) setTimeout(() => this.pump(), Math.min(Date.now() - t0, 3000)); + else setImmediate(() => this.pump()); }); } @@ -324,6 +381,8 @@ export class SttPipeline { target_lufs: s.audio.targetLufs, noise_sensitivity: s.audio.noiseSensitivity, denoise: s.audio.denoise, + // 게임 중에는 빔 1 (빔 3 보다 가볍다. 경기 뒤 정밀 모델이 다시 변환한다) + ...(this.saving() && slot === 'realtime' ? { beam_size: 1 } : {}), }, 5 * 60000, ); diff --git a/app/src/main/main.ts b/app/src/main/main.ts index 763b303..b15faad 100644 --- a/app/src/main/main.ts +++ b/app/src/main/main.ts @@ -23,6 +23,8 @@ const opt = (name: string) => argv.find((a) => a.startsWith(`--${name}=`))?.spli const SMOKE = flag('smoke'); app.setAppUserModelId('kr.tkrmagid.gvr'); +// 설정 창은 글자 · 버튼뿐이라 GPU 로 그릴 필요가 없다. 게임 · 브라우저와 GPU 를 나눠 쓰지 않게 끈다 (v1.9.0) +app.disableHardwareAcceleration(); if (!SMOKE && !app.requestSingleInstanceLock()) { app.quit(); process.exit(0); diff --git a/app/src/renderer/mock-gvr.ts b/app/src/renderer/mock-gvr.ts index 4c7eefe..56b4328 100644 --- a/app/src/renderer/mock-gvr.ts +++ b/app/src/renderer/mock-gvr.ts @@ -35,6 +35,7 @@ function defaults(): Settings { modelsDir: null, reprocessAfterMatch: true, gameVramReserveMb: 3072, + gameSaver: true, }, audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 }, dictionary: { diff --git a/app/src/renderer/tabs/SttTab.tsx b/app/src/renderer/tabs/SttTab.tsx index 2417246..01ecc09 100644 --- a/app/src/renderer/tabs/SttTab.tsx +++ b/app/src/renderer/tabs/SttTab.tsx @@ -184,6 +184,12 @@ export function SttTab() {
⚠ RTX 50 시리즈(Blackwell)에서 int8 계열은 cuBLAS 오류 사례가 있습니다. 문제가 생기면 float16으로 돌려 주세요.
)} save({ stt: { reprocessAfterMatch: v } })} /> + save({ stt: { gameSaver: v } })} + /> save({ stt: { gameVramReserveMb: n } })} /> diff --git a/app/test/game-saver.test.ts b/app/test/game-saver.test.ts new file mode 100644 index 0000000..ef2aad0 --- /dev/null +++ b/app/test/game-saver.test.ts @@ -0,0 +1,103 @@ +// v1.9.0: 게임 중 GPU 아끼기 (발로란트 + 브라우저 + 겜녹이를 같이 켜면 GPU 가 100% 가까이 차던 것) +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { Store } from '../src/core/db/db.ts'; +import { Timeline } from '../src/core/timeline.ts'; +import { Bus } from '../src/core/util/events.ts'; +import { SttPipeline } from '../src/core/stt/pipeline.ts'; + +function setup(gameSaver = true) { + const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-saver-')); + const store = new Store(path.join(dir, 'db.sqlite')); + store.upsertUser({ id: 'u1', name: '하늘', avatar: null }); + const t0 = Date.now() - 600000; + store.upsertMatch({ id: 'm1', game: 'valorant', started_at: t0, status: 'live' }); + const mk = (id: string, at = Date.now()) => { + const f = path.join(dir, 'audio', `${id}.ogg`); + fs.mkdirSync(path.dirname(f), { recursive: true }); + fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)])); + store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: at, ended_at: at + 1000, audio_path: f, match_id: 'm1' }); + }; + const reqs: any[] = []; + const ops: string[] = []; + const worker: any = Object.assign(new EventEmitter(), { + ready: true, + request: async (op: string, req: any) => { + if (op === 'gpu_info') return { gpus: [{ vram_total_mb: 16303 }] }; // 두 모델을 같이 올릴 수 있는 카드 + if (op === 'models') return { models: [{ name: 'rt', installed: true }, { name: 'pr', installed: true }] }; + if (op === 'load' || op === 'unload') { + ops.push(`${op}:${req.slot}`); + return {}; + } + reqs.push(req); + await new Promise((r) => setTimeout(r, 40)); + return { text: '말', raw_text: '말', words: [], noise: false, noise_reason: null, confidence: 0.5, lufs: -30, gain_db: 0, speech_ratio: 1, duration_s: 1, model: req.slot, elapsed_ms: 40 }; + }, + }); + const settings: any = () => ({ + stt: { realtimeModel: 'rt', preciseModel: 'pr', device: 'cuda', computeType: 'float16', gameVramReserveMb: 3072, reprocessAfterMatch: true, gameSaver }, + audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false }, + }); + const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] }; + const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings); + stt.status.worker = 'ready'; + const wait = async (fn: () => boolean, ms = 5000) => { + const t = Date.now(); + while (!fn()) { + if (Date.now() - t > ms) throw new Error('timeout'); + await new Promise((r) => setTimeout(r, 10)); + } + }; + return { store, stt, mk, reqs, ops, wait, t0 }; +} + +test('게임 중: 정밀 모델을 내리고, 새 발화는 실시간 모델 · 빔 1 로만, 발화 사이에 쉰다', async () => { + const s = setup(); + await s.stt.prepareModels(); + assert.equal(s.stt.status.slots.precise.state, 'loaded', '게임 밖에서는 두 모델 모두'); + await s.stt.setGameActive(true); + assert.equal(s.stt.status.slots.precise.state, 'empty', '게임이 켜지면 정밀 모델을 내린다'); + s.mk('a1'); + s.mk('a2'); + s.stt.enqueue('a1', 'realtime'); + s.stt.enqueue('a2', 'realtime'); + const t = Date.now(); + await s.wait(() => s.reqs.length === 2 && !s.stt.status.processing); + assert.ok(Date.now() - t >= 75, '두 번째 발화 전에 앞 변환만큼 쉰다'); + assert.deepEqual(s.reqs.map((r) => [r.slot, r.beam_size]), [['realtime', 1], ['realtime', 1]]); +}); + +test('경기가 끝나도 게임(메뉴)이 켜져 있으면 정밀 변환은 기다리고, 게임을 끄면 정밀 모델을 올려 한다', async () => { + const s = setup(); + await s.stt.prepareModels(); + await s.stt.setGameActive(true); + await s.stt.onMatchStart(); + s.mk('b1', s.t0 + 1000); + s.stt.enqueue('b1', 'realtime'); + await s.wait(() => s.store.getUtterance('b1')!.status === 'realtime'); + await s.stt.onMatchEnd(s.t0, Date.now()); + await new Promise((r) => setTimeout(r, 100)); + assert.equal(s.reqs.length, 1, '게임이 켜져 있는 동안 정밀 변환 안 함'); + assert.equal(s.stt.status.queue, 1); + assert.equal(s.stt.status.slots.precise.state, 'empty'); + await s.stt.setGameActive(false); + await s.wait(() => s.store.getUtterance('b1')!.status === 'precise'); + assert.equal(s.reqs[1].slot, 'precise'); + assert.equal(s.reqs[1].beam_size, undefined, '게임 밖에서는 기본 빔'); +}); + +test('게임 중 GPU 아끼기를 끄면 예전처럼 (정밀 모델 유지 · 기본 빔)', async () => { + const s = setup(false); + await s.stt.prepareModels(); + await s.stt.setGameActive(true); + assert.equal(s.stt.status.slots.precise.state, 'loaded'); + await s.stt.onMatchStart(); + s.mk('c1'); + s.stt.enqueue('c1', 'realtime'); + await s.wait(() => s.reqs.length === 1); + assert.equal(s.reqs[0].beam_size, undefined); +}); diff --git a/worker/gvr_worker/stt.py b/worker/gvr_worker/stt.py index e4b0745..260dfec 100644 --- a/worker/gvr_worker/stt.py +++ b/worker/gvr_worker/stt.py @@ -152,6 +152,10 @@ class SttEngine: if noise.judge_vad(speech_ratio, speech_s, sensitivity): return done("vad") + # 앱이 게임 중에는 빔 1(가장 가벼움)을 보낸다. 없으면 슬롯 기본값 + beam = req.get("beam_size") + beam = int(beam) if isinstance(beam, (int, float)) and 1 <= int(beam) <= 10 else BEAM.get(slot, 5) + hotwords = req.get("hotwords") or None hotwords = hotwords if isinstance(hotwords, str) and hotwords.strip() else None @@ -161,7 +165,7 @@ class SttEngine: prep.audio, language="ko", task="transcribe", - beam_size=BEAM.get(slot, 5), + beam_size=beam, word_timestamps=True, vad_filter=True, vad_parameters={"min_silence_duration_ms": VAD_MIN_SILENCE_MS},