import { spawn } from 'node:child_process'; import fs from 'node:fs'; import https from 'node:https'; import path from 'node:path'; import type { Core } from '../core/index.js'; import { logger } from '../core/util/log.js'; import type { FinetuneStatus } from './api-types.js'; import { finetuneScriptsDir } from './paths.js'; const log = logger('finetune'); const PY_EMBED = 'https://www.python.org/ftp/python/3.11.9/python-3.11.9-embed-amd64.zip'; const GET_PIP = 'https://bootstrap.pypa.io/get-pip.py'; /** * 파인튜닝 (M8, 보고서 5-5). 학습 도구(torch·transformers·peft)는 exe 에 넣지 않고 처음 쓸 때 * GVR-Data/finetune-env 에 내려받는다 (Windows: 임베디드 파이썬 3.11 + pip, 약 3GB). * 게임이 실행 중이면 시작하지 않고, 학습 중 게임이 켜지면 중지 파일을 만들어 바로 멈춘다. */ export class Finetuner { status: FinetuneStatus; private nightlyTimer: NodeJS.Timeout | null = null; private watch: NodeJS.Timeout | null = null; constructor( private core: Core, private onChange: () => void, ) { const last = core.store.meta('finetune_last'); this.status = { toolsInstalled: !!this.python(), installing: false, running: false, stage: null, step: null, total: null, samples: core.store.trainingSamples().length, lastResult: last ? JSON.parse(last) : null, activeModel: core.settings.get().finetune.activeModel, previousModel: core.settings.get().finetune.previousModel, log: [], }; } private envDir(): string { return path.join(this.core.paths().dataDir, 'finetune-env'); } /** 학습용 파이썬 */ python(): string | null { if (process.env.GVR_FINETUNE_PYTHON && fs.existsSync(process.env.GVR_FINETUNE_PYTHON)) return process.env.GVR_FINETUNE_PYTHON; const p = process.platform === 'win32' ? path.join(this.envDir(), 'python.exe') : path.join(this.envDir(), 'bin', 'python'); return fs.existsSync(p) && fs.existsSync(path.join(this.envDir(), '.gvr-ready')) ? p : null; } refresh(): FinetuneStatus { this.status.toolsInstalled = !!this.python(); this.status.samples = this.core.store.trainingSamples().length; this.status.activeModel = this.core.settings.get().finetune.activeModel; this.status.previousModel = this.core.settings.get().finetune.previousModel; return this.status; } private push(line: string): void { this.status.log.push(`${new Date().toLocaleTimeString('ko-KR', { hour12: false })} ${line}`); if (this.status.log.length > 200) this.status.log.splice(0, this.status.log.length - 200); log.info(line); this.onChange(); } private inGame(): boolean { const g = this.core.games.status(); return g.valorant.inMatch || g.lol.inMatch; } // ------------------------------------------------------------------ 학습 도구 설치 async install(): Promise { if (this.status.installing) return; if (process.platform !== 'win32') throw new Error('학습 도구 자동 설치는 Windows 에서만 지원합니다 (개발 환경은 GVR_FINETUNE_PYTHON 사용)'); this.status.installing = true; this.onChange(); const dir = this.envDir(); try { fs.mkdirSync(dir, { recursive: true }); const zip = path.join(dir, 'python-embed.zip'); this.push('임베디드 파이썬 내려받는 중'); await download(PY_EMBED, zip); await run('powershell.exe', ['-NoProfile', '-Command', `Expand-Archive -Force -Path '${zip}' -DestinationPath '${dir}'`], (l) => this.push(l)); fs.rmSync(zip, { force: true }); // site-packages 와 pip 를 쓰려면 ._pth 에서 import site 를 켠다 for (const f of fs.readdirSync(dir).filter((x) => x.endsWith('._pth'))) { const p = path.join(dir, f); fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replace('#import site', 'import site') + '\nLib\\site-packages\n'); } const getPip = path.join(dir, 'get-pip.py'); await download(GET_PIP, getPip); const py = path.join(dir, 'python.exe'); this.push('pip 설치'); await run(py, [getPip, '--no-warn-script-location'], (l) => this.push(l)); this.push('PyTorch (CUDA 12.8) 설치 - 약 2.5GB, 시간이 걸립니다'); await run(py, ['-m', 'pip', 'install', '--no-warn-script-location', 'torch', '--index-url', 'https://download.pytorch.org/whl/cu128'], (l) => this.push(l)); this.push('학습 라이브러리 설치'); await run(py, ['-m', 'pip', 'install', '--no-warn-script-location', '-r', path.join(finetuneScriptsDir(), 'requirements.txt')], (l) => this.push(l)); fs.writeFileSync(path.join(dir, '.gvr-ready'), new Date().toISOString()); this.push('학습 도구 설치 완료'); } finally { this.status.installing = false; this.refresh(); this.onChange(); } } // ------------------------------------------------------------------ 학습 async start(opts: { maxSteps?: number; base?: string; synthCount?: number; exportAlways?: boolean } = {}): Promise { if (this.status.running) throw new Error('이미 학습 중입니다'); const py = this.python(); if (!py) throw new Error('학습 도구가 설치되지 않았습니다'); if (this.inGame()) throw new Error('게임 중에는 학습을 시작하지 않습니다'); const data = this.core.paths().dataDir; const stopFile = path.join(data, 'finetune.stop'); fs.rmSync(stopFile, { force: true }); const work = path.join(data, 'finetune', new Date().toISOString().replace(/[:.]/g, '-')); fs.mkdirSync(work, { recursive: true }); // 입력: 사용자가 고친 문장 + 음성 조각, 사전 단어, 합성용 문장 const samples = this.core.store.trainingSamples().filter((s) => fs.existsSync(s.audio_path)); fs.writeFileSync(path.join(work, 'corrections.jsonl'), samples.map((s) => JSON.stringify({ audio: s.audio_path, text: s.text })).join('\n')); const words = [...new Set(this.core.dict.candidates('valorant').concat(this.core.dict.candidates('lol'), this.core.dict.candidates('none')))]; fs.writeFileSync(path.join(work, 'words.txt'), words.join('\n')); fs.writeFileSync(path.join(work, 'sentences.txt'), makeSentences(this.core).join('\n')); this.status = { ...this.status, running: true, stage: '준비', step: null, total: null }; this.push(`학습 시작: 교정 문장 ${samples.length}개, 사전 ${words.length}단어`); // 학습 중 게임이 켜지면 중지 파일 this.watch = setInterval(() => { if (this.inGame() && !fs.existsSync(stopFile)) { fs.writeFileSync(stopFile, 'game'); this.push('게임이 시작되어 학습을 멈춥니다'); } }, 3000); const s = this.core.settings.get(); const base = opts.base || (s.stt.realtimeModel.includes('turbo') || s.stt.realtimeModel.includes('-ft-') ? 'openai/whisper-large-v3-turbo' : `openai/whisper-${s.stt.realtimeModel}`); try { const res = await this.core.worker.request( 'train', { python: py, args: { base, sentences: path.join(work, 'sentences.txt'), dictionary: path.join(work, 'words.txt'), user_corrections: path.join(work, 'corrections.jsonl'), stop_file: stopFile, work, max_steps: opts.maxSteps || undefined, synth_count: opts.synthCount || undefined, export_always: opts.exportAlways || undefined, }, }, 0, (ev) => { if (ev.event === 'progress') { this.status.stage = ev.stage ?? this.status.stage; this.status.step = ev.step ?? null; this.status.total = ev.total ?? null; this.onChange(); } }, ); const result = { cer_before: res.cer_before, cer_after: res.cer_after, adopt: !!res.adopt, model: res.model_name ?? res.model ?? null, at: Date.now() }; this.status.lastResult = result; this.core.store.setMeta('finetune_last', JSON.stringify(result)); this.push(`학습 끝: 오류율 ${(res.cer_before * 100).toFixed(1)}% → ${(res.cer_after * 100).toFixed(1)}% ${res.adopt ? '(개선 → 새 모델 적용)' : '(개선 없음 → 기존 모델 유지)'}${res.stopped ? ' · 중간에 멈춤' : ''}`); if (res.adopt && result.model) await this.adopt(result.model); } catch (e: any) { this.push(`학습 실패: ${e.message}`); throw e; } finally { if (this.watch) clearInterval(this.watch); this.watch = null; this.status.running = false; this.status.stage = null; this.refresh(); this.onChange(); } } stop(): void { fs.writeFileSync(path.join(this.core.paths().dataDir, 'finetune.stop'), 'user'); this.push('학습 중지 요청'); } private async adopt(model: string): Promise { const s = this.core.settings.get(); this.core.settings.update({ stt: { realtimeModel: model }, finetune: { activeModel: model, previousModel: s.stt.realtimeModel } }); await this.core.stt.load('realtime', model); } async rollback(): Promise { const prev = this.core.settings.get().finetune.previousModel; if (!prev) throw new Error('되돌릴 이전 모델이 없습니다'); const cur = this.core.settings.get().stt.realtimeModel; this.core.settings.update({ stt: { realtimeModel: prev }, finetune: { activeModel: null, previousModel: cur } }); await this.core.stt.load('realtime', prev); this.push(`이전 모델로 되돌림: ${prev}`); } /** 매일 새벽 4시 30분 자동 학습 (설정이 켜져 있고, 교정 문장이 20개 이상이고, 게임 중이 아닐 때) */ scheduleNightly(): void { if (this.nightlyTimer) clearTimeout(this.nightlyTimer); const now = new Date(); const next = new Date(now); next.setHours(4, 30, 0, 0); if (next <= now) next.setDate(next.getDate() + 1); this.nightlyTimer = setTimeout(async () => { const s = this.core.settings.get(); if (s.finetune.schedule === 'nightly' && this.python() && !this.inGame() && this.core.store.trainingSamples().length >= 20) { await this.start().catch(() => undefined); } this.scheduleNightly(); }, next.getTime() - now.getTime()); } dispose(): void { if (this.nightlyTimer) clearTimeout(this.nightlyTimer); if (this.watch) clearInterval(this.watch); } } /** 합성 음성용 문장: 사전 단어를 실제로 쓰는 말투 틀에 넣는다 */ export function makeSentences(core: Pick): string[] { const val = core.dict.candidates('valorant'); const lol = core.dict.candidates('lol'); const pick = (a: string[], i: number) => a[(i * 7919) % a.length]; const T_VAL = ['{w} 궁 빠졌어', '{w} 쪽으로 로테 하자', '나 {w} 살게', '{w} 조심해 거기 있어', '{w} 봤어 하나 체력 낮아', '이번 라운드 {w} 쓰자']; const T_LOL = ['{w} 점멸 빠졌어', '{w} 치자 다 모여', '{w} 갱 온다 조심', '{w} 궁 있어 한타 열자', '{w} 와드 박아 줘', '{w} 잡으면 바로 귀환']; const out: string[] = []; for (let i = 0; i < 150 && val.length; i++) out.push(T_VAL[i % T_VAL.length].replace('{w}', pick(val, i))); for (let i = 0; i < 150 && lol.length; i++) out.push(T_LOL[i % T_LOL.length].replace('{w}', pick(lol, i))); return out; } function download(url: string, dest: string, redirects = 5): Promise { return new Promise((resolve, reject) => { https .get(url, (res) => { if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && redirects > 0) { res.resume(); return void download(res.headers.location, dest, redirects - 1).then(resolve, reject); } if (res.statusCode !== 200) return reject(new Error(`다운로드 실패 ${res.statusCode}: ${url}`)); const f = fs.createWriteStream(dest); res.pipe(f); f.on('finish', () => f.close(() => resolve())); f.on('error', reject); }) .on('error', reject); }); } function run(cmd: string, args: string[], onLine: (l: string) => void): Promise { return new Promise((resolve, reject) => { const p = spawn(cmd, args, { windowsHide: true }); let last = 0; const handle = (d: Buffer) => { for (const l of d.toString().split(/\r?\n/)) { // pip 진행 표시가 너무 많아서 2초에 한 줄만 if (l.trim() && Date.now() - last > 2000) { last = Date.now(); onLine(l.trim().slice(0, 200)); } } }; p.stdout.on('data', handle); p.stderr.on('data', handle); p.on('error', reject); p.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`${path.basename(cmd)} 종료 코드 ${code}`)))); }); }