diff --git a/src/gateway/routes/settings.ts b/src/gateway/routes/settings.ts index 09dfd82..b25be4e 100644 --- a/src/gateway/routes/settings.ts +++ b/src/gateway/routes/settings.ts @@ -4,6 +4,7 @@ import path from 'path'; import { getConfig, ConfigManager } from '../../config/config.js'; import { resetProvider } from '../../providers/factory.js'; import { readUsageRows, summarize } from '../../providers/cost-estimate.js'; +import { STT_MODELS, isSttModelDownloaded, sttDownloadState, startSttDownload } from '../../tools/stt-models.js'; import { isEngineReady } from '../../tools/voice-engine-client.js'; import { buildSttHotwords } from '../../tools/stt-correct.js'; import { getClaudeSearchConfig, getClaudeSearchUsage } from '../../tools/claude-search.js'; @@ -486,6 +487,8 @@ export function registerSettingsRoutes(app: Express): void { ttsSpeed: Math.min(1.4, Math.max(0.8, Number(e.ttsSpeed) || 1.15)), ttsVoice: voice, designedRefExists: voice !== 'clone' && fs.existsSync(designedRefPath(voice)), + sttModel: e.sttModel || 'medium', + sttModels: STT_MODELS.map((m) => ({ ...m, downloaded: isSttModelDownloaded(m.id), download: sttDownloadState(m.id) })), info: { online: (() => { try { return isEngineReady(); } catch { return false; } })(), port: e.port || 8765, @@ -512,10 +515,26 @@ export function registerSettingsRoutes(app: Express): void { if (!v || v.length > 120) { res.status(400).json({ success: false, error: 'ttsVoice must be 1..120 chars' }); return; } engine.ttsVoice = v; } + if (b.sttModel !== undefined) { + const id = String(b.sttModel); + if (!STT_MODELS.some((m) => m.id === id)) { res.status(400).json({ success: false, error: 'unknown sttModel' }); return; } + if (!isSttModelDownloaded(id)) { res.status(400).json({ success: false, error: '아직 내려받지 않은 모델입니다. 먼저 "받기"를 하세요.' }); return; } + engine.sttModel = id; + } cm.updateConfig({ voice: { ...(current.voice || {}), engine } } as any); res.json({ success: true, restartRequired: true, ttsSpeed: engine.ttsSpeed, ttsVoice: engine.ttsVoice }); }); + // 인식 모델 내려받기(사용자가 화면에서 버튼을 눌렀을 때만). 진행은 GET /api/settings/voice-engine 의 sttModels[].download 로 본다. + app.post('/api/settings/voice-engine/stt-download', (req, res) => { + const id = String(req.body?.model || ''); + if (!STT_MODELS.some((m) => m.id === id)) { res.status(400).json({ success: false, error: 'unknown model' }); return; } + if (isSttModelDownloaded(id)) { res.json({ success: true, already: true }); return; } + const venv = path.join(cm.getConfigDir(), 'voice-venv', 'bin', 'python'); + if (!fs.existsSync(venv)) { res.status(500).json({ success: false, error: 'voice venv not found' }); return; } + res.json({ success: true, started: startSttDownload(id, venv) }); + }); + // 저장된 기준 음성을 지워 다음 시작 때 새로 뽑게 한다(생성물이라 지워도 안전) app.post('/api/settings/voice-engine/reroll', (req, res) => { const voice = String(req.body?.voice || (cm.getConfig() as any).voice?.engine?.ttsVoice || 'clone'); diff --git a/src/tools/stt-models.ts b/src/tools/stt-models.ts new file mode 100644 index 0000000..579d1fd --- /dev/null +++ b/src/tools/stt-models.ts @@ -0,0 +1,48 @@ +/** + * stt-models.ts — 음성 인식(faster-whisper) 모델 목록·다운로드 상태. + * 엔진은 voice.engine.sttModel 이름으로 모델을 연다. 안 받아진 모델을 고르면 엔진 시작 때 내려받느라 한참 멈추므로, + * 설정 화면에서는 받아진 모델만 고를 수 있게 하고 받기는 사용자가 버튼으로 따로 한다. + */ +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { spawn } from 'child_process'; + +export interface SttModelInfo { id: string; repo: string; sizeGB: number; note: string } + +export const STT_MODELS: SttModelInfo[] = [ + { id: 'medium', repo: 'Systran/faster-whisper-medium', sizeGB: 1.5, note: '가볍고 빠름, 정확도 낮음' }, + { id: 'large-v3-turbo', repo: 'mobiuslabsgmbh/faster-whisper-large-v3-turbo', sizeGB: 1.6, note: '현재 기본 — 큰 모델에 가까운 정확도, 빠름' }, + { id: 'large-v3', repo: 'Systran/faster-whisper-large-v3', sizeGB: 3.1, note: '실험용 — 가장 정확하지만 느리고 GPU 메모리를 더 씀' }, +]; + +const hubDir = () => path.join(process.env.HF_HOME || path.join(os.homedir(), '.cache', 'huggingface'), 'hub'); + +export function isSttModelDownloaded(id: string): boolean { + const m = STT_MODELS.find((x) => x.id === id); + if (!m) return false; + const snaps = path.join(hubDir(), 'models--' + m.repo.replace('/', '--'), 'snapshots'); + try { + return fs.readdirSync(snaps).some((rev) => fs.existsSync(path.join(snaps, rev, 'model.bin'))); + } catch { return false; } +} + +const downloads = new Map(); + +export function sttDownloadState(id: string) { return downloads.get(id) || null; } + +/** 백그라운드로 내려받는다(이미 받는 중이면 무시). 받는 도중 서버가 꺼지면 다음에 이어 받는다(HF 캐시가 이어받기 지원). */ +export function startSttDownload(id: string, venvPython: string): boolean { + const m = STT_MODELS.find((x) => x.id === id); + if (!m || downloads.get(id)?.state === 'running') return false; + downloads.set(id, { state: 'running', startedAt: Date.now() }); + const child = spawn(venvPython, ['-I', '-c', 'import sys; from huggingface_hub import snapshot_download; snapshot_download(sys.argv[1])', m.repo], { stdio: ['ignore', 'ignore', 'pipe'] }); + let err = ''; + child.stderr?.on('data', (d: Buffer) => { err = (err + d.toString('utf8')).slice(-400); }); + child.on('close', (code) => { + downloads.set(id, code === 0 && isSttModelDownloaded(id) + ? { state: 'done', startedAt: downloads.get(id)?.startedAt || Date.now() } + : { state: 'failed', error: err.trim().split('\n').pop() || `exit ${code}`, startedAt: downloads.get(id)?.startedAt || Date.now() }); + }); + return true; +} diff --git a/web-ui/html/index.html b/web-ui/html/index.html index 064c3d0..cafea9a 100644 --- a/web-ui/html/index.html +++ b/web-ui/html/index.html @@ -1892,6 +1892,17 @@
저장한 뒤 서버를 재시작하면 적용됩니다. 속도는 0.8~1.4배(1.5배 이상은 숫자·단위가 빠지는 것을 확인했습니다). 기본 외의 목소리는 처음 한 번 만든 기준 음성을 저장해 계속 같은 음색으로 읽습니다. 마음에 안 들면 "목소리 다시 뽑기" 후 재시작하세요.
+ +
+
음성 인식 모델 (STT)
+
불러오는 중…
+
+ + +
+
내려받은 모델만 고를 수 있습니다. 받기는 버튼을 눌렀을 때만 시작하고 몇 분 걸립니다. 선택을 저장한 뒤 서버를 재시작하면 적용됩니다. 큰 모델은 GPU 메모리를 더 쓰고 인식이 느려질 수 있어서, 써 보고 나아지지 않으면 large-v3-turbo로 되돌리세요.
+
+
현재 사용 중
diff --git a/web-ui/js/app/settings-provider.js b/web-ui/js/app/settings-provider.js index cfe62c6..75bcf33 100644 --- a/web-ui/js/app/settings-provider.js +++ b/web-ui/js/app/settings-provider.js @@ -1248,6 +1248,7 @@ async function loadVoiceEngine() { document.getElementById('ve-speed-val').textContent = Number(r.ttsSpeed).toFixed(2) + '배'; veVoiceChanged(); renderVoiceEngineInfo(r); + renderSttModels(r); if (st) st.textContent = r.ttsVoice === 'clone' ? '' : (r.designedRefExists ? '기준 음성 저장됨' : '기준 음성은 다음 시작 때 만들어집니다'); } catch (e) { if (st) st.textContent = '불러오기 실패: ' + e.message; } } @@ -1267,6 +1268,45 @@ function renderVoiceEngineInfo(r) { ].join(''); } +let _sttPoll = null; +function renderSttModels(r) { + const box = document.getElementById('ve-stt-models'); + if (!box) return; + const cur = r.sttModel; + let running = false; + box.innerHTML = (r.sttModels || []).map((m) => { + const d = m.download; + if (d && d.state === 'running') running = true; + let tail; + if (m.downloaded) tail = '받아짐'; + else if (d && d.state === 'running') tail = '받는 중… (' + m.sizeGB + 'GB)'; + else tail = '' + (d && d.state === 'failed' ? ' 실패: ' + (d.error || '') + '' : ''); + return ''; + }).join(''); + clearTimeout(_sttPoll); + if (running) _sttPoll = setTimeout(loadVoiceEngine, 4000); +} + +async function downloadSttModel(id) { + const st = document.getElementById('ve-stt-status'); + if (!confirm(id + ' 모델을 내려받습니다. 계속할까요?')) return; + try { + await api('/api/settings/voice-engine/stt-download', { method: 'POST', body: JSON.stringify({ model: id }) }); + if (st) st.textContent = '내려받기를 시작했습니다'; + loadVoiceEngine(); + } catch (e) { if (st) st.textContent = '실패: ' + e.message; } +} + +async function saveSttModel() { + const st = document.getElementById('ve-stt-status'); + const pick = document.querySelector('input[name="ve-stt"]:checked'); + if (!pick) { if (st) st.textContent = '모델을 고르세요'; return; } + try { + await api('/api/settings/voice-engine', { method: 'POST', body: JSON.stringify({ sttModel: pick.value }) }); + if (st) st.textContent = '저장됨 — 서버를 재시작하면 적용됩니다'; + } catch (e) { if (st) st.textContent = '저장 실패: ' + e.message; } +} + async function saveVoiceEngine() { const st = document.getElementById('ve-status'); const sel = document.getElementById('ve-voice').value;