From 3a258c534e45d507db8e82c53eb7cf8290fbd321 Mon Sep 17 00:00:00 2001 From: kim Date: Sat, 17 Oct 2026 21:36:51 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9D=8C=EC=84=B1=20=EC=9D=B8=EC=8B=9D=20?= =?UTF-8?q?=EC=82=AC=ED=9B=84=20=EB=B3=B4=EC=A0=95:=20=EA=B3=A0=EC=9C=A0?= =?UTF-8?q?=EC=96=B4=20=EB=AA=85=EC=8B=9C=20=EA=B7=9C=EC=B9=99=20+=20?= =?UTF-8?q?=EC=9E=90=EB=AA=A8=20=ED=8E=B8=EC=A7=91=EA=B1=B0=EB=A6=AC=20?= =?UTF-8?q?=EA=B7=BC=EC=82=AC=20=EB=A7=A4=EC=B9=AD(stt-correct),=20?= =?UTF-8?q?=ED=86=B5=ED=99=94=20=EC=B5=9C=EC=A2=85=EB=AC=B8=20=EB=B3=B4?= =?UTF-8?q?=EC=A0=95=20API,=20=EC=9D=8C=EC=84=B1=20=EC=9E=85=EB=A0=A5=20?= =?UTF-8?q?=ED=84=B4=20=EC=95=88=EB=82=B4=EB=A5=BC=20=EC=8B=9C=EC=8A=A4?= =?UTF-8?q?=ED=85=9C=20=EC=BB=A8=ED=85=8D=EC=8A=A4=ED=8A=B8=EB=A1=9C=20?= =?UTF-8?q?=EC=A0=84=EB=8B=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- src/gateway/routes/routes-voice.ts | 12 +++ src/tools/stt-correct.ts | 134 +++++++++++++++++++++++++++++ src/tools/stt.ts | 15 ++++ tests/stt-correct.test.ts | 49 +++++++++++ web-ui/js/app/chat-sse.js | 7 +- web-ui/js/voice/voice-call.js | 32 +++++-- 6 files changed, 242 insertions(+), 7 deletions(-) create mode 100644 src/tools/stt-correct.ts create mode 100644 tests/stt-correct.test.ts diff --git a/src/gateway/routes/routes-voice.ts b/src/gateway/routes/routes-voice.ts index af378d4..7129db7 100644 --- a/src/gateway/routes/routes-voice.ts +++ b/src/gateway/routes/routes-voice.ts @@ -3,9 +3,21 @@ import path from 'path'; import fs from 'fs'; import { transcribeAudio } from '../../tools/stt.js'; import { getConfig } from '../../config/config'; +import { correctTranscript } from '../../tools/stt-correct.js'; export function registerVoiceRoutes(app: express.Application): void { +// 실시간 통화(WS가 엔진에 직접 붙음)는 서버를 거치지 않으므로, 브라우저가 최종 인식문을 여기서 보정받는다. +app.post('/api/voice/correct', express.json({ limit: '16kb' }), (req: express.Request, res: express.Response) => { + const text = String(req.body?.text ?? ''); + try { + const fixed = correctTranscript(text); + if (fixed !== text) console.log(`[stt] corrected (call): "${text.slice(0, 60)}" → "${fixed.slice(0, 60)}"`); + res.json({ success: true, text: fixed }); + } + catch { res.json({ success: true, text }); } +}); + app.post('/api/voice/stt', async (req: express.Request, res: express.Response) => { const contentType = String(req.headers['content-type'] || 'audio/webm'); const fmt = contentType.includes('ogg') ? 'ogg' diff --git a/src/tools/stt-correct.ts b/src/tools/stt-correct.ts new file mode 100644 index 0000000..c6ce7fb --- /dev/null +++ b/src/tools/stt-correct.ts @@ -0,0 +1,134 @@ +/** + * stt-correct.ts — 음성 인식(Whisper) 결과의 사후 보정 + * + * Whisper medium은 일반 한국어는 잘 받아 적지만 우리 집 고유어(클로서버·지서버·옥토서버·홈클로·시어엔진…)를 + * 비슷한 소리의 흔한 말로 잘못 적는다("크로 서버", "지 서버", "클로써버"). 이름이 틀리면 LLM이 그 대상을 못 찾는다. + * 모델을 키우기 전에, 값싸고 결정적인 두 단계로 보정한다. + * 1) 명시 규칙: 자주 틀리는 형태를 정규식으로 (config.voice.corrections로 추가 가능) + * 2) 용어 사전 근사 매칭: 띄어쓰기를 무시하고 자모 편집거리 1 이내면 표준 표기로 치환 + * + * 보수적으로 설계했다 — 잘못 고치는 것이 못 고치는 것보다 나쁘다. 근사 매칭은 자모 길이 8 이상인 용어에만, + * 거리 1까지만, 그리고 이미 사전 표기와 정확히 같은 단어는 건드리지 않는다. + */ +import { getConfig } from '../config/config'; + +export interface SttCorrectionConfig { + /** 표준 표기 목록(띄어쓰기 포함 가능: "라즈베리 파이") */ + vocabulary: string[]; + /** 명시 규칙. pattern은 정규식 문자열 */ + rules: Array<{ pattern: string; to: string }>; +} + +export const DEFAULT_VOCABULARY = [ + '클로서버', '지서버', '옥토서버', '홈클로', '시어엔진', '트루나스', '홈어시스턴트', + '라즈베리 파이', '기상청', '에어코리아', '카카오맵', '탐정앱', '작업실', '오픈스캐드', + '프리게이트', '네스트', '젬마', '제미나이', '오픈소스', '올라마', +]; + +export const DEFAULT_RULES: Array<{ pattern: string; to: string }> = [ + { pattern: '(?:크로|클로|클로우)\\s*(?:서버|써버|서바)', to: '클로서버' }, + { pattern: '(?:지|G|g|쥐|제이)\\s*(?:서버|써버)', to: '지서버' }, + { pattern: '(?:옥토|옥터|악토)\\s*(?:서버|써버)', to: '옥토서버' }, + { pattern: '(?:시어|씨어|시얼)\\s*엔진', to: '시어엔진' }, + { pattern: '홈\\s*(?:크로|클로)', to: '홈클로' }, + { pattern: '트루\\s*(?:나스|내스)', to: '트루나스' }, + { pattern: '라즈베리\\s*(?:파이|화이|피이)', to: '라즈베리 파이' }, +]; + +export function getSttCorrectionConfig(): SttCorrectionConfig { + let user: any = {}; + try { user = (getConfig().getConfig() as any)?.voice?.corrections || {}; } catch { /* 설정 없음 */ } + const extraVocab = Array.isArray(user.vocabulary) ? user.vocabulary.map(String).filter(Boolean) : []; + const extraRules = Array.isArray(user.rules) ? user.rules.filter((r: any) => r?.pattern && r?.to) : []; + return { + vocabulary: [...new Set([...DEFAULT_VOCABULARY, ...extraVocab])], + rules: [...DEFAULT_RULES, ...extraRules.map((r: any) => ({ pattern: String(r.pattern), to: String(r.to) }))], + }; +} + +// ── 한글 자모 분해 ────────────────────────────────────────────────────────── +const CHO = 'ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ'; +const JUNG = 'ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ'; +const JONG = ['', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ']; + +export function toJamo(s: string): string[] { + const out: string[] = []; + for (const ch of s) { + const c = ch.charCodeAt(0); + if (c >= 0xac00 && c <= 0xd7a3) { + const i = c - 0xac00; + out.push(CHO[Math.floor(i / 588)], JUNG[Math.floor((i % 588) / 28)]); + const j = JONG[i % 28]; + if (j) out.push(j); + } else { + out.push(ch); + } + } + return out; +} + +export function jamoDistance(a: string[], b: string[]): number { + const dp: number[] = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i++) { + let prev = dp[0]; + dp[0] = i; + for (let j = 1; j <= b.length; j++) { + const tmp = dp[j]; + dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); + prev = tmp; + } + } + return dp[b.length]; +} + +const strip = (s: string) => s.replace(/\s+/g, ''); + +/** 공백으로 나눈 토큰 1~3개 묶음을 사전 용어와 비교해 치환 */ +function fuzzyVocabulary(text: string, vocabulary: string[]): string { + const terms = vocabulary.map(v => ({ canon: v, key: strip(v), jamo: toJamo(strip(v)) })).filter(t => t.jamo.length >= 8); + if (!terms.length) return text; + const tokens = text.split(/(\s+)/); // 공백도 토큰으로 보존 + const words = tokens.map((t, i) => ({ t, i })).filter(x => !/^\s+$/.test(x.t) && x.t !== ''); + const out = [...tokens]; + for (let w = 0; w < words.length; w++) { + for (let span = Math.min(3, words.length - w); span >= 1; span--) { + const slice = words.slice(w, w + span); + // 조사가 붙은 어절은 끝의 한 글자를 떼고도 비교한다("클로서버가" → "클로서버" + "가") + const joined = tokens.slice(slice[0].i, slice[slice.length - 1].i + 1).join(''); // 사이 공백 포함 원문 그대로 + const candidates = [{ core: joined, tail: '' }]; + if (joined.length >= 4) candidates.push({ core: joined.slice(0, -1), tail: joined.slice(-1) }); + let replaced = false; + for (const cand of candidates) { + const coreKey = strip(cand.core); + for (const term of terms) { + if (coreKey === term.key) { // 이미 표준(띄어쓰기만 다를 수 있음) → 표준 표기로 정리 + if (cand.core !== term.canon) { applyReplace(out, slice, term.canon + cand.tail); replaced = true; } + else replaced = true; + break; + } + if (Math.abs(coreKey.length - term.key.length) > 1) continue; + if (jamoDistance(toJamo(coreKey), term.jamo) <= 1) { applyReplace(out, slice, term.canon + cand.tail); replaced = true; break; } + } + if (replaced) break; + } + if (replaced) { w += span - 1; break; } + } + } + return out.join(''); +} + +function applyReplace(out: string[], slice: Array<{ t: string; i: number }>, replacement: string): void { + out[slice[0].i] = replacement; + for (let k = 1; k < slice.length; k++) { // 첫 토큰 이후 토큰과 그 사이 공백 제거 + for (let idx = slice[k - 1].i + 1; idx <= slice[k].i; idx++) out[idx] = ''; + } +} + +export function correctTranscript(text: string, cfg: SttCorrectionConfig = getSttCorrectionConfig()): string { + let t = String(text || ''); + if (!t.trim()) return t; + for (const r of cfg.rules) { + try { t = t.replace(new RegExp(r.pattern, 'g'), r.to); } catch { /* 잘못된 정규식은 건너뜀 */ } + } + return fuzzyVocabulary(t, cfg.vocabulary).replace(/\s{2,}/g, ' ').trim(); +} diff --git a/src/tools/stt.ts b/src/tools/stt.ts index a92c8fa..1788c73 100644 --- a/src/tools/stt.ts +++ b/src/tools/stt.ts @@ -1,3 +1,4 @@ +import { correctTranscript } from './stt-correct.js'; import { spawn } from 'child_process'; import path from 'path'; import fs from 'fs'; @@ -57,10 +58,24 @@ async function convertAudioToWav( } } +/** 인식 결과에 사후 보정(고유어 표기 정리)을 적용한다 — stt-correct.ts 참고. */ export async function transcribeAudio( audioBuffer: Buffer, sourceFormat: string = 'ogg', languageOverride?: string +): Promise<{ text: string; language?: string }> { + const raw = await transcribeAudioRaw(audioBuffer, sourceFormat, languageOverride); + try { + const corrected = correctTranscript(raw.text); + if (corrected !== raw.text) console.log(`[stt] corrected: "${raw.text.slice(0, 60)}" → "${corrected.slice(0, 60)}"`); + return { ...raw, text: corrected }; + } catch { return raw; } +} + +async function transcribeAudioRaw( + audioBuffer: Buffer, + sourceFormat: string = 'ogg', + languageOverride?: string ): Promise<{ text: string; language?: string }> { const cfg = getConfig().getConfig() as any; const provider = cfg?.voice?.stt?.provider; diff --git a/tests/stt-correct.test.ts b/tests/stt-correct.test.ts new file mode 100644 index 0000000..d8fca5c --- /dev/null +++ b/tests/stt-correct.test.ts @@ -0,0 +1,49 @@ +/** + * stt-correct — 음성 인식 사후 보정. 보수성(오탐 방지)이 핵심이라 "고치지 않아야 할 문장"을 더 많이 둔다. + */ +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { correctTranscript, jamoDistance, toJamo, DEFAULT_VOCABULARY, DEFAULT_RULES } from '../src/tools/stt-correct'; + +const cfg = { vocabulary: DEFAULT_VOCABULARY, rules: DEFAULT_RULES }; +const fix = (s: string) => correctTranscript(s, cfg); + +describe('명시 규칙·근사 매칭으로 고쳐야 하는 것', () => { + test('띄어쓴/비슷한 소리의 서버 이름', () => { + assert.equal(fix('크로 서버 상태 알려줘'), '클로서버 상태 알려줘'); + assert.equal(fix('지 서버 깨워줘'), '지서버 깨워줘'); + assert.equal(fix('옥터 써버에서 프린터 확인해'), '옥토서버에서 프린터 확인해'); + }); + test('조사가 붙어도 고친다', () => { + assert.equal(fix('클로써버가 느려'), '클로서버가 느려'); + assert.equal(fix('크로서버에서 돌려줘'), '클로서버에서 돌려줘'); + }); + test('자모 거리 1 이내의 오인식(사전 근사 매칭)', () => { + assert.equal(fix('홈 어시스턴트 켜줘'), '홈어시스턴트 켜줘'); + assert.equal(fix('트로나스 상태'), '트루나스 상태'); + }); + test('라즈베리 파이 표기 통일', () => { + assert.equal(fix('라즈베리파이 가져와'), '라즈베리 파이 가져와'); + }); +}); + +describe('고치면 안 되는 것(오탐 방지)', () => { + test('일반 문장은 그대로', () => { + for (const s of ['오늘 서울 날씨 알려줘', '서버가 느려졌어', '컴퓨터를 켜 줘', '지금 몇 시야?', '옥수수 사 와']) assert.equal(fix(s), s); + }); + test('빈 문자열·공백', () => { + assert.equal(fix(''), ''); + assert.equal(fix(' '), ' '); + }); + test('이미 표준 표기면 그대로', () => { + assert.equal(fix('클로서버 재시작해줘'), '클로서버 재시작해줘'); + }); +}); + +describe('자모 거리', () => { + test('치환·삽입 1', () => { + assert.equal(jamoDistance(toJamo('클로서버'), toJamo('크로서버')), 1); + assert.equal(jamoDistance(toJamo('클로서버'), toJamo('클로써버')), 1); + assert.ok(jamoDistance(toJamo('클로서버'), toJamo('서버')) > 1); + }); +}); diff --git a/web-ui/js/app/chat-sse.js b/web-ui/js/app/chat-sse.js index a8b21c7..30d8599 100644 --- a/web-ui/js/app/chat-sse.js +++ b/web-ui/js/app/chat-sse.js @@ -1,3 +1,6 @@ +// 음성 통화 턴에 붙이는 안내(시스템 프롬프트 쪽 skillContext로 전달). 인식 오류를 문맥으로 해석하고, 모호하면 되묻게 한다. +var VOICE_INPUT_HINT = 'VOICE INPUT: the user message below came from speech recognition (Korean Whisper) and may contain sound-alike or spacing errors, especially proper nouns (클로서버, 지서버, 옥토서버, 홈클로, 시어엔진, 라즈베리 파이, 기상청). Interpret by context. If a critical word (device/server name, number, or the target of an action with side effects) is ambiguous, ask a one-line confirmation instead of guessing. Keep the reply short and speakable — it will be read aloud: no tables, no emoji, no URLs unless asked.'; + // chat-sse.js — sendChat (SSE chat dispatch), extracted from app.js. // Loaded BEFORE app.js so the bare sendChat() references in app.js (chat-input Enter, // handleSendStop, pptx flows) resolve at call time. All dependencies remain globals @@ -142,6 +145,8 @@ async function sendChat(queuedMessage = null) { // Use SSE fetch — stream steps live as they arrive currentAbortController = new AbortController(); + const voiceTurn = window._voiceInputTurn === true; // 음성 통화에서 막 들어온 턴인지 + window._voiceInputTurn = false; const res = await fetch('/api/chat', { method: 'POST', headers: authHeaders({ @@ -149,7 +154,7 @@ async function sendChat(queuedMessage = null) { 'Accept': 'text/event-stream', }), signal: currentAbortController.signal, - body: JSON.stringify({ message: fullMessage, history: historyForAPI, useTools: useAgentMode, sessionId: agentSessionId, pinnedMessages: confirmedPins.length > 0 ? confirmedPins : undefined }) + body: JSON.stringify({ message: fullMessage, history: historyForAPI, useTools: useAgentMode, sessionId: agentSessionId, pinnedMessages: confirmedPins.length > 0 ? confirmedPins : undefined, skillContext: voiceTurn ? VOICE_INPUT_HINT : undefined }) }); if (!res.ok) { diff --git a/web-ui/js/voice/voice-call.js b/web-ui/js/voice/voice-call.js index a869bb0..947add0 100644 --- a/web-ui/js/voice/voice-call.js +++ b/web-ui/js/voice/voice-call.js @@ -241,6 +241,22 @@ } } + async function correctSttText(text) { + try { + const ctl = new AbortController(); + const timer = setTimeout(() => ctl.abort(), 800); + const r = await fetch('/api/voice/correct', { + method: 'POST', + headers: Object.assign({ 'Content-Type': 'application/json' }, (typeof authHeaders === 'function' ? authHeaders() : {})), + body: JSON.stringify({ text }), + signal: ctl.signal, + }); + clearTimeout(timer); + const d = await r.json(); + return (d && d.success && typeof d.text === 'string' && d.text.trim()) ? d.text : text; + } catch { return text; } + } + function handleWsMessage(e) { if (e.data instanceof ArrayBuffer) { if (playerNode) playerNode.port.postMessage({ type: 'push', pcm: new Int16Array(e.data) }, [e.data]); @@ -259,13 +275,17 @@ const text = (msg.text || '').trim(); if (!text) { state = 'listening'; setStatus('듣는 중…'); break; } spokenUpTo = 0; pendingTts = ''; spokenKeys.clear(); - const input = document.getElementById('chat-input'); - if (input) { - input.value = text; - input.dispatchEvent(new Event('input')); - } setStatus('생각 중…'); - setTimeout(() => (window._appSendFn || handleSendStop)(), 30); + // 사후 보정(고유어 표기 정리) — 서버 /api/voice/correct. 실패·지연 시 원문 그대로 보낸다(통화가 막히면 안 됨). + correctSttText(text).then((fixed) => { + const input = document.getElementById('chat-input'); + if (input) { + input.value = fixed; + input.dispatchEvent(new Event('input')); + } + window._voiceInputTurn = true; // chat-sse가 이 턴에 "음성 인식 입력" 안내를 붙인다 + setTimeout(() => (window._appSendFn || handleSendStop)(), 30); + }); break; }