fix(meeting): stop learned vocabulary from rewriting ordinary Korean

The first cut replaced any Hangul word within one jamo of a learned term.
Measured against the real local corpus (three stored meeting transcripts)
it changed 286 of 3,005 words: 하면 became 라면, 이제 became 이게, 매일 became
메일. Most of what the app learns from typing is ordinary grammar, so
distance alone cannot separate a misheard word from a correct one.

Deterministic correction now covers only dictionary pronunciations and the
Latin identifiers the user types, preserving their casing. Korean terms
still bias recognition through the prompt hint and guide the polish
prompt. Re-measured on the same transcripts: 0 of 3,005 words changed.
Hangul-layout typing artifacts (dkssudgktpdy) are dropped from the hint.
This commit is contained in:
Yun Chan 2026-11-06 13:40:09 +09:00
parent a21de78303
commit 72e9b7c18b
7 changed files with 116 additions and 101 deletions

View file

@ -90,33 +90,45 @@ describe('replaceDictionaryTerms', () => {
describe('correctLearnedTerms', () => {
const glossary = buildTranscriptGlossary({
phrases: phrases(['회의록 정리해줘', 6], ['전사 교정', 4]),
phrases: phrases(['VSCode 설정 열기', 6], ['D3RO Voice 녹음', 4]),
})
it('1자모 차이 나는 전사 어절을 학습 어절로 되돌린다', () => {
const result = correctLearnedTerms('회이록 정리해줘', glossary)
it('학습한 식별자와 한 글자 다른 전사 어절을 되돌린다', () => {
const result = correctLearnedTerms('VSCod 설정 열기', glossary)
expect(result.text).toBe('회의록 정리해줘')
expect(result.corrections).toEqual([{ from: '회이록', to: '회의록', source: 'learned' }])
expect(result.text).toBe('VSCode 설정 열기')
expect(result.corrections).toEqual([{ from: 'VSCod', to: 'VSCode', source: 'learned' }])
})
it('조사는 붙인 채로 어절만 고친다', () => {
expect(correctLearnedTerms('회이록은 좋다', glossary).text).toBe('회의록은 좋다')
})
it('이미 맞게 적힌 식별자는 건드리지 않는다', () => {
const result = correctLearnedTerms('VSCode 설정 열기', glossary)
it('사용자가 실제로 쓴 어절은 건드리지 않는다', () => {
const result = correctLearnedTerms('회의록 정리해줘', glossary)
expect(result.text).toBe('회의록 정리해줘')
expect(result.text).toBe('VSCode 설정 열기')
expect(result.corrections).toEqual([])
})
it('한글 어절은 1자모만 달라도 고치지 않는다', () => {
// 실사용 코퍼스 측정: 한글까지 고치면 정상 문장이 대량으로 망가졌다(하면→라면, 이제→이게 …).
const korean = buildTranscriptGlossary({
phrases: phrases(['회의록 정리해줘', 6], ['라면 먹고 싶다', 5]),
})
expect(correctLearnedTerms('회이록 정리해줘', korean).text).toBe('회이록 정리해줘')
expect(correctLearnedTerms('하면 좋겠다', korean).text).toBe('하면 좋겠다')
})
it('후보가 둘 이상이면(동률) 고치지 않는다', () => {
const tied = buildTranscriptGlossary({
phrases: phrases(['정리해', 4], ['정리히', 4]),
phrases: phrases(['vscode 사용', 4], ['vscodf 사용', 4]),
})
expect(correctLearnedTerms('정리하', tied).text).toBe('정리하')
expect(correctLearnedTerms('vscodd', tied).text).toBe('vscodd')
})
it('너무 짧은 식별자·한 글자 어절은 대상이 아니다', () => {
const shortTerms = buildTranscriptGlossary({ phrases: phrases(['api 서버', 9]) })
expect(correctLearnedTerms('ap 서버', shortTerms).text).toBe('ap 서버')
})
it('어휘가 없으면 원문을 그대로 돌려준다', () => {
@ -124,15 +136,6 @@ describe('correctLearnedTerms', () => {
expect(result).toEqual({ text: '아무 말이나 적는다', corrections: [] })
})
it('사전 정본 표기가 학습 어절보다 우선한다', () => {
const withDictionary = buildTranscriptGlossary({
dictionary: [{ word: '회의록', pronunciation: null }],
phrases: phrases(['회의녹 정리', 9]),
})
expect(correctLearnedTerms('회이록 정리', withDictionary).text).toBe('회의록 정리')
})
})
describe('LLM 교열 참고 블록', () => {

View file

@ -12,7 +12,7 @@
//
// 순수 함수만 둔다. DB·Electron 을 모르므로 데스크톱 서비스가 소스를 주입한다.
import { decomposeHangul, editDistance, tokenizeWords } from './typo-correction'
import { editDistance, latinToHangul, tokenizeWords } from './typo-correction'
/** 사용자 사전 한 항목 */
export interface GlossaryDictionaryEntry {
@ -59,15 +59,7 @@ const STOP_WORDS: ReadonlySet<string> = new Set([
'이렇게', '그렇게', '저렇게', '여기', '거기', '저기',
])
/** 토큰에서 떼어 낼 수 있는 조사 (긴 것부터) */
const JOSA_SUFFIXES: readonly string[] = [
'이라는', '이라고', '이라도', '에서는', '에게는', '에서도', '으로는', '으로써',
'에서는', '부터', '까지', '에게', '한테', '에서', '으로', '라고', '라는',
'이나', '라도', '이랑', '하고', '이고', '이든', '처럼', '보다', '만큼',
'에는', '에도', '께서', '이란', '이라',
'은', '는', '이', '가', '을', '를', '에', '의', '로', '도', '와', '과', '만', '들',
]
/** 학습 어휘를 STT 힌트·LLM 교열·식별자 교정에 쓰기 위한 묶음. */
export interface TranscriptGlossary {
/** 사전 정본 단어 (원표기) */
terms: readonly string[]
@ -75,6 +67,8 @@ export interface TranscriptGlossary {
dictionary: readonly { word: string; variants: readonly string[] }[]
/** 소문자 어절 → 빈도 (교정 후보) */
vocabulary: ReadonlyMap<string, number>
/** 소문자 어절 → 처음 본 표기 (VSCode 같은 대소문자 보존) */
canonical: ReadonlyMap<string, string>
/** 사용자가 실제로 쓰는 표현 (문체 참고) */
examples: readonly string[]
/** STT initial_prompt 힌트 (없으면 빈 문자열) */
@ -96,6 +90,7 @@ const EMPTY_GLOSSARY: TranscriptGlossary = {
terms: [],
dictionary: [],
vocabulary: new Map<string, number>(),
canonical: new Map<string, string>(),
examples: [],
promptHint: '',
}
@ -144,6 +139,7 @@ export function buildTranscriptGlossary(input: {
const dictionary: Array<{ word: string; variants: readonly string[] }> = []
const terms: string[] = []
const vocabulary = new Map<string, number>()
const canonical = new Map<string, string>()
const seen = new Set<string>()
for (const entry of (input.dictionary ?? []).slice(0, limits.dictionaryEntries)) {
@ -156,10 +152,13 @@ export function buildTranscriptGlossary(input: {
terms.push(word)
// 사전 정본은 어떤 학습 어절보다 우선 후보가 되도록 큰 가중치를 준다.
bump(vocabulary, key, 1000)
canonical.set(key, word)
}
const examples: string[] = []
const phraseTokens = new Map<string, number>()
/** 같은 뜻의 한글 표기가 코퍼스에 있는 영문 토큰(한영 자판 오타 산물) — 힌트·교정에서 뺀다. */
const hangulObserved = new Set<string>()
for (const phrase of (input.phrases ?? []).slice(0, limits.phrases)) {
const text = phrase.text?.replace(/\s+/gu, ' ').trim()
if (!text) continue
@ -175,7 +174,21 @@ export function buildTranscriptGlossary(input: {
for (const token of tokenizeWords(text)) {
const word = token.text
if (!isLearnableToken(word)) continue
bump(phraseTokens, word.toLowerCase(), weight)
if (/^[가-힣]+$/u.test(word)) hangulObserved.add(word)
const key = word.toLowerCase()
bump(phraseTokens, key, weight)
if (!canonical.has(key)) canonical.set(key, word)
}
}
// 한영 자판 오타 산물( 같은)은 같은 뜻의 한글 표기가 코퍼스에 있으므로 뺀다.
// 그대로 두면 STT 힌트가 의미 없는 라틴 문자열로 편향되고, 식별자 교정 후보로도 쓰인다.
for (const word of [...phraseTokens.keys()]) {
if (!/^[a-z]+$/u.test(word)) continue
const converted = latinToHangul(word)
if (converted.complete && hangulObserved.has(converted.text)) {
phraseTokens.delete(word)
canonical.delete(word)
}
}
@ -211,9 +224,9 @@ export function buildTranscriptGlossary(input: {
const promptHint = joined ? `용어: ${joined}.` : ''
if (vocabulary.size === 0 && terms.length === 0 && examples.length === 0) {
return { ...EMPTY_GLOSSARY, vocabulary: new Map() }
return { ...EMPTY_GLOSSARY, vocabulary: new Map(), canonical: new Map() }
}
return { terms, dictionary, vocabulary, examples, promptHint }
return { terms, dictionary, vocabulary, canonical, examples, promptHint }
}
/** 글로서리에 아무 정보도 없으면 true */
@ -287,8 +300,8 @@ export function replaceDictionaryTerms(
interface VocabularyCandidate {
word: string
count: number
jamo: readonly string[]
script: 'hangul' | 'latin'
lower: string
chars: readonly string[]
}
interface VocabularyIndex {
@ -303,11 +316,16 @@ interface VocabularyIndex {
*/
const vocabularyIndexCache = new WeakMap<TranscriptGlossary, VocabularyIndex>()
function scriptOf(value: string): 'hangul' | 'latin' | null {
if (/^[가-힣]+$/u.test(value)) return 'hangul'
if (/^[A-Za-z]+$/u.test(value)) return 'latin'
return null
}
/**
* 결정적 교정 대상은 ASCII 식별자(제품명·약어·코드)뿐이다.
*
* 한글 어절을 「학습 어휘와 1자모 다르면 교체」로 고치는 방식은 실사용 DB 코퍼스로 측정했을 때
* 정상 문장을 대량으로 망쳤다(회의 전사 3,005어절 중 286개 변경: 하면→라면, 이제→이게, 매일→메일,
* 정보→정도, 일단→일반 …). 사용자가 실제로 쓰는 어휘에는 일반 명사·부사·어미가 대부분이라
* 1자모 거리만으로는 「오인식」과 「정상 단어」를 구분할 수 없다. 한글 용어는 STT 힌트와 LLM 교열에만
* 쓰고, 결정적으로는 고치지 않는다(정밀도 우선).
*/
const IDENTIFIER_TOKEN = /^[A-Za-z][A-Za-z0-9]{3,}$/u
function buildVocabularyIndex(glossary: TranscriptGlossary): VocabularyIndex {
const cached = vocabularyIndexCache.get(glossary)
@ -321,40 +339,37 @@ function buildVocabularyIndexUncached(glossary: TranscriptGlossary): VocabularyI
const byLength = new Map<number, VocabularyCandidate[]>()
const known = new Set<string>()
for (const [word, count] of glossary.vocabulary) {
const script = scriptOf(word)
if (!script) continue
if (!IDENTIFIER_TOKEN.test(word)) continue
known.add(word)
const candidate: VocabularyCandidate = {
word,
word: glossary.canonical.get(word) ?? word,
count,
jamo: decomposeHangul(word),
script,
lower: word.toLowerCase(),
chars: Array.from(word.toLowerCase()),
}
const bucket = byLength.get(candidate.jamo.length)
const bucket = byLength.get(candidate.chars.length)
if (bucket) bucket.push(candidate)
else byLength.set(candidate.jamo.length, [candidate])
else byLength.set(candidate.chars.length, [candidate])
}
return { byLength, known }
}
/**
* 학습 어절에서 1자모 차이 나는 유일한 후보를 찾는다.
* 학습 어휘에서 1글자 차이 나는 유일한 후보를 찾는다.
* 동률이면(어느 쪽이 맞는지 알 수 없으면) 고치지 않는다.
*/
function bestCandidate(token: string, index: VocabularyIndex): VocabularyCandidate | null {
const script = scriptOf(token)
if (!script) return null
const jamo = decomposeHangul(token)
const lower = token.toLowerCase()
const chars = Array.from(lower)
let best: VocabularyCandidate | null = null
let bestCount = 0
let ties = 0
for (const length of [jamo.length - 1, jamo.length, jamo.length + 1]) {
for (const length of [chars.length - 1, chars.length, chars.length + 1]) {
const bucket = index.byLength.get(length)
if (!bucket) continue
for (const candidate of bucket) {
if (candidate.script !== script) continue
if (candidate.jamo.length === jamo.length && candidate.word === token.toLowerCase()) continue
if (editDistance(jamo, candidate.jamo) > 1) continue
if (candidate.lower === lower) continue
if (editDistance(chars, candidate.chars) > 1) continue
if (candidate.count > bestCount) {
best = candidate
bestCount = candidate.count
@ -367,27 +382,9 @@ function bestCandidate(token: string, index: VocabularyIndex): VocabularyCandida
return ties === 0 ? best : null
}
interface TokenAttempt {
/** 비교할 어절 (조사를 떼어 낸 형태일 수 있다) */
text: string
}
function tokenAttempts(token: string): TokenAttempt[] {
const attempts: TokenAttempt[] = [{ text: token }]
for (const josa of JOSA_SUFFIXES) {
if (token.length - josa.length < 2) continue
if (!token.endsWith(josa)) continue
const stem = token.slice(0, token.length - josa.length)
if (!/^[가-힣A-Za-z0-9]+$/u.test(stem)) continue
attempts.push({ text: stem })
break
}
return attempts
}
/**
* 학습 어휘로 어절을 되돌린다. 띄어쓰기·문장부호·조사는 그대로 두고 어절만 바꾼다.
* 사용자가 실제로 쓴 어절(어휘에 있음)은 절대 건드리지 않는다.
* 학습 어휘로 ASCII 식별자 어절을 되돌린다 (예: `vscod` → `VSCode`).
* 한글 어절·띄어쓰기·문장부호는 건드리지 않는다.
*/
export function correctLearnedTerms(
text: string,
@ -397,26 +394,20 @@ export function correctLearnedTerms(
if (!trimmed || glossary.vocabulary.size === 0) return { text: trimmed, corrections: [] }
const index = buildVocabularyIndex(glossary)
if (index.byLength.size === 0) return { text: trimmed, corrections: [] }
const corrections: TranscriptCorrectionEntry[] = []
let out = ''
let cursor = 0
for (const token of tokenizeWords(trimmed)) {
let replaced: { value: string; prefixLength: number } | null = null
for (const attempt of tokenAttempts(token.text)) {
if (index.known.has(attempt.text.toLowerCase())) continue
if (attempt.text.length < 2) continue
const candidate = bestCandidate(attempt.text, index)
if (!candidate) continue
replaced = { value: candidate.word, prefixLength: attempt.text.length }
break
}
if (!replaced) continue
const original = token.text.slice(0, replaced.prefixLength)
if (original === replaced.value) continue
corrections.push({ from: original, to: replaced.value, source: 'learned' })
out += trimmed.slice(cursor, token.start) + replaced.value
cursor = token.start + replaced.prefixLength
if (!IDENTIFIER_TOKEN.test(token.text)) continue
if (index.known.has(token.text.toLowerCase())) continue
const candidate = bestCandidate(token.text, index)
if (!candidate) continue
corrections.push({ from: token.text, to: candidate.word, source: 'learned' })
out += trimmed.slice(cursor, token.start) + candidate.word
cursor = token.end
}
if (corrections.length === 0) return { text: trimmed, corrections: [] }