feat(meeting): correct transcripts with vocabulary learned from typing
Meeting and caption transcription never used what the app had already learned: speech recognition ran with a fixed Korean prompt, the refine prompt had no glossary, refined lines stopped inside the caption service, and the saved transcript was a raw join of segments. Names and jargon the user types every day were therefore re-mangled on every recording. The learned corpus (user dictionary plus personal phrases) now feeds one glossary that biases recognition, fixes mistyped words deterministically right after each line is finalized, and is handed to the local model when it polishes a line. Refined lines also reach the meeting transcript and screen through a new segment-updated event. Corrections never touch words the user actually wrote, refuse ties between equally likely candidates, and keep particles intact.
This commit is contained in:
parent
d631042836
commit
9c2b6a9782
21 changed files with 1134 additions and 61 deletions
|
|
@ -382,6 +382,7 @@ export const IPC_CHANNELS = {
|
|||
// Main → Renderer events
|
||||
STATE_CHANGED: 'meetingMode:stateChanged',
|
||||
SEGMENT: 'meetingMode:segment',
|
||||
SEGMENT_UPDATED: 'meetingMode:segmentUpdated',
|
||||
PROCESSING_PROGRESS: 'meetingMode:processingProgress',
|
||||
SESSION_COMPLETED: 'meetingMode:sessionCompleted',
|
||||
DOC_GENERATING_PROGRESS: 'meetingMode:docGeneratingProgress',
|
||||
|
|
|
|||
452
packages/core/src/transcript-correction.ts
Normal file
452
packages/core/src/transcript-correction.ts
Normal file
|
|
@ -0,0 +1,452 @@
|
|||
// packages/core/src/transcript-correction.ts
|
||||
// 학습한 사용자 어휘(사전 + 개인 문구)를 전사 교열에 쓰는 정본.
|
||||
//
|
||||
// 왜 필요한가:
|
||||
// - 사용자가 키보드로 친 문장은 개인 그래프(personal_phrases)에 쌓이지만, 그 어휘는 입력 제안에만
|
||||
// 쓰이고 회의록·자막 전사에는 한 번도 닿지 않았다. 그래서 Whisper 가 같은 이름·용어를 매번
|
||||
// 다르게 받아 적어도 앱이 배운 것을 활용하지 못했다.
|
||||
// - 이 모듈은 그 어휘를 3가지 형태로 바꾼다.
|
||||
// 1) promptHint : STT initial_prompt 에 넣는 용어 힌트 (인식 단계에서 미리 편향)
|
||||
// 2) vocabulary : 전사된 어절을 학습 어휘로 되돌리는 결정적 교정 (LLM 없이 0ms)
|
||||
// 3) promptSection: LLM 교열 프롬프트에 넣는 용어·문체 참고 블록
|
||||
//
|
||||
// 순수 함수만 둔다. DB·Electron 을 모르므로 데스크톱 서비스가 소스를 주입한다.
|
||||
|
||||
import { decomposeHangul, editDistance, tokenizeWords } from './typo-correction'
|
||||
|
||||
/** 사용자 사전 한 항목 */
|
||||
export interface GlossaryDictionaryEntry {
|
||||
word: string
|
||||
/** 발음·오인식 변형 (쉼표·슬래시·세미콜론 구분) */
|
||||
pronunciation?: string | null
|
||||
}
|
||||
|
||||
/** 개인 그래프에서 배운 문구 한 건 */
|
||||
export interface GlossaryPhrase {
|
||||
text: string
|
||||
count: number
|
||||
}
|
||||
|
||||
export const TRANSCRIPT_GLOSSARY_LIMITS = {
|
||||
/** 사전 항목 상한 */
|
||||
dictionaryEntries: 300,
|
||||
/** 학습 문구 상한 */
|
||||
phrases: 400,
|
||||
/** STT 힌트에 넣는 용어 수 */
|
||||
promptTerms: 40,
|
||||
/** STT 힌트 최대 길이 (자) */
|
||||
promptChars: 240,
|
||||
/** 교정 어휘 상한 */
|
||||
vocabularyTerms: 500,
|
||||
/** 학습 어절을 교정 후보로 인정하는 최소 빈도 */
|
||||
minLearnedCount: 3,
|
||||
/** LLM 교열 프롬프트에 보여 줄 사용자 표현 수 */
|
||||
refineExamples: 8,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* 힌트·교정 어휘에서 빼는 흔한 기능어.
|
||||
* 전사 편향만 만들고 실제 오인식 교정에는 도움이 되지 않는다.
|
||||
*/
|
||||
const STOP_WORDS: ReadonlySet<string> = new Set([
|
||||
'그리고', '그래서', '그런데', '그러면', '그러니까', '하지만', '그치만', '근데',
|
||||
'저는', '제가', '저희', '우리', '너는', '니가', '네가',
|
||||
'이거', '그거', '저거', '이건', '그건', '저건', '이런', '그런', '저런',
|
||||
'지금', '이제', '아직', '다시', '일단', '먼저', '나중에',
|
||||
'정말', '진짜', '너무', '많이', '조금', '약간', '좀더', '아주',
|
||||
'하는', '해서', '하면', '하고', '해요', '합니다', '입니다', '있어', '없어',
|
||||
'있습니다', '없습니다', '같아', '같은', '것은', '것을', '수가', '수도',
|
||||
'이렇게', '그렇게', '저렇게', '여기', '거기', '저기',
|
||||
])
|
||||
|
||||
/** 토큰에서 떼어 낼 수 있는 조사 (긴 것부터) */
|
||||
const JOSA_SUFFIXES: readonly string[] = [
|
||||
'이라는', '이라고', '이라도', '에서는', '에게는', '에서도', '으로는', '으로써',
|
||||
'에서는', '부터', '까지', '에게', '한테', '에서', '으로', '라고', '라는',
|
||||
'이나', '라도', '이랑', '하고', '이고', '이든', '처럼', '보다', '만큼',
|
||||
'에는', '에도', '께서', '이란', '이라',
|
||||
'은', '는', '이', '가', '을', '를', '에', '의', '로', '도', '와', '과', '만', '들',
|
||||
]
|
||||
|
||||
export interface TranscriptGlossary {
|
||||
/** 사전 정본 단어 (원표기) */
|
||||
terms: readonly string[]
|
||||
/** 사전 정본 단어 + 발음 변형 */
|
||||
dictionary: readonly { word: string; variants: readonly string[] }[]
|
||||
/** 소문자 어절 → 빈도 (교정 후보) */
|
||||
vocabulary: ReadonlyMap<string, number>
|
||||
/** 사용자가 실제로 쓰는 표현 (문체 참고) */
|
||||
examples: readonly string[]
|
||||
/** STT initial_prompt 힌트 (없으면 빈 문자열) */
|
||||
promptHint: string
|
||||
}
|
||||
|
||||
export interface TranscriptCorrectionEntry {
|
||||
from: string
|
||||
to: string
|
||||
source: 'dictionary' | 'learned'
|
||||
}
|
||||
|
||||
export interface CorrectedTranscript {
|
||||
text: string
|
||||
corrections: readonly TranscriptCorrectionEntry[]
|
||||
}
|
||||
|
||||
const EMPTY_GLOSSARY: TranscriptGlossary = {
|
||||
terms: [],
|
||||
dictionary: [],
|
||||
vocabulary: new Map<string, number>(),
|
||||
examples: [],
|
||||
promptHint: '',
|
||||
}
|
||||
|
||||
/** 사전 항목의 발음/변형 문자열을 개별 토큰으로 나눈다 (정본 표기는 제외). */
|
||||
export function splitGlossaryVariants(pronunciation: string | null | undefined, canonical: string): string[] {
|
||||
const raw = typeof pronunciation === 'string' ? pronunciation.trim() : ''
|
||||
if (!raw) return []
|
||||
const canonicalLower = canonical.toLowerCase()
|
||||
const out: string[] = []
|
||||
for (const part of raw.split(/[,/;]+/u)) {
|
||||
const value = part.trim()
|
||||
if (!value) continue
|
||||
if (value.toLowerCase() === canonicalLower) continue
|
||||
if (out.includes(value)) continue
|
||||
out.push(value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function bump(map: Map<string, number>, key: string, amount: number): void {
|
||||
map.set(key, (map.get(key) ?? 0) + amount)
|
||||
}
|
||||
|
||||
function topEntries(map: ReadonlyMap<string, number>, limit: number): Array<[string, number]> {
|
||||
return [...map.entries()]
|
||||
.sort((a, b) => (b[1] - a[1] !== 0 ? b[1] - a[1] : a[0].localeCompare(b[0])))
|
||||
.slice(0, Math.max(0, limit))
|
||||
}
|
||||
|
||||
function isLearnableToken(word: string): boolean {
|
||||
if (word.length < 2) return false
|
||||
if (!/^[가-힣A-Za-z0-9]+$/u.test(word)) return false
|
||||
return !STOP_WORDS.has(word)
|
||||
}
|
||||
|
||||
/**
|
||||
* 사전 + 학습 문구에서 전사 교열용 글로서리를 만든다.
|
||||
* 사전 단어는 사용자가 명시한 정본이므로 학습 어절보다 항상 우선한다.
|
||||
*/
|
||||
export function buildTranscriptGlossary(input: {
|
||||
dictionary?: readonly GlossaryDictionaryEntry[]
|
||||
phrases?: readonly GlossaryPhrase[]
|
||||
}): TranscriptGlossary {
|
||||
const limits = TRANSCRIPT_GLOSSARY_LIMITS
|
||||
const dictionary: Array<{ word: string; variants: readonly string[] }> = []
|
||||
const terms: string[] = []
|
||||
const vocabulary = new Map<string, number>()
|
||||
const seen = new Set<string>()
|
||||
|
||||
for (const entry of (input.dictionary ?? []).slice(0, limits.dictionaryEntries)) {
|
||||
const word = entry.word?.trim()
|
||||
if (!word) continue
|
||||
const key = word.toLowerCase()
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
dictionary.push({ word, variants: splitGlossaryVariants(entry.pronunciation, word) })
|
||||
terms.push(word)
|
||||
// 사전 정본은 어떤 학습 어절보다 우선 후보가 되도록 큰 가중치를 준다.
|
||||
bump(vocabulary, key, 1000)
|
||||
}
|
||||
|
||||
const examples: string[] = []
|
||||
const phraseTokens = new Map<string, number>()
|
||||
for (const phrase of (input.phrases ?? []).slice(0, limits.phrases)) {
|
||||
const text = phrase.text?.replace(/\s+/gu, ' ').trim()
|
||||
if (!text) continue
|
||||
if (
|
||||
examples.length < limits.refineExamples &&
|
||||
text.length >= 4 &&
|
||||
text.length <= 80 &&
|
||||
!examples.includes(text)
|
||||
) {
|
||||
examples.push(text)
|
||||
}
|
||||
const weight = Math.max(1, phrase.count)
|
||||
for (const token of tokenizeWords(text)) {
|
||||
const word = token.text
|
||||
if (!isLearnableToken(word)) continue
|
||||
bump(phraseTokens, word.toLowerCase(), weight)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [word, count] of topEntries(phraseTokens, limits.vocabularyTerms)) {
|
||||
if (count < limits.minLearnedCount) break
|
||||
if (vocabulary.has(word)) continue
|
||||
if (!isLearnableToken(word)) continue
|
||||
vocabulary.set(word, count)
|
||||
}
|
||||
|
||||
// 힌트 용어: 사전 정본 먼저, 그 다음 학습 빈도순.
|
||||
const hintTerms: string[] = []
|
||||
const pushed = new Set<string>()
|
||||
const pushHint = (word: string): void => {
|
||||
const key = word.toLowerCase()
|
||||
if (pushed.has(key)) return
|
||||
if (hintTerms.length >= limits.promptTerms) return
|
||||
pushed.add(key)
|
||||
hintTerms.push(word)
|
||||
}
|
||||
for (const word of terms) pushHint(word)
|
||||
for (const [word] of topEntries(phraseTokens, limits.promptTerms)) {
|
||||
if (!isLearnableToken(word)) continue
|
||||
pushHint(word)
|
||||
}
|
||||
|
||||
let joined = ''
|
||||
for (const word of hintTerms) {
|
||||
const next = joined ? `${joined}, ${word}` : word
|
||||
if (next.length > limits.promptChars) break
|
||||
joined = next
|
||||
}
|
||||
const promptHint = joined ? `용어: ${joined}.` : ''
|
||||
|
||||
if (vocabulary.size === 0 && terms.length === 0 && examples.length === 0) {
|
||||
return { ...EMPTY_GLOSSARY, vocabulary: new Map() }
|
||||
}
|
||||
return { terms, dictionary, vocabulary, examples, promptHint }
|
||||
}
|
||||
|
||||
/** 글로서리에 아무 정보도 없으면 true */
|
||||
export function isGlossaryEmpty(glossary: TranscriptGlossary): boolean {
|
||||
return glossary.dictionary.length === 0 && glossary.examples.length === 0 && glossary.vocabulary.size === 0
|
||||
}
|
||||
|
||||
/** STT initial_prompt 에 글로서리 힌트를 덧붙인다. */
|
||||
export function appendGlossaryHint(base: string, glossary: TranscriptGlossary): string {
|
||||
const prefix = base.trim()
|
||||
if (!glossary.promptHint) return prefix
|
||||
return prefix ? `${prefix} ${glossary.promptHint}` : glossary.promptHint
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
|
||||
}
|
||||
|
||||
function isAsciiWordChar(char: string | undefined): boolean {
|
||||
return Boolean(char && /[A-Za-z0-9]/u.test(char))
|
||||
}
|
||||
|
||||
function buildTokenRegex(token: string): RegExp {
|
||||
const escaped = escapeRegExp(token)
|
||||
const prefix = isAsciiWordChar(token[0]) ? '(?<![A-Za-z0-9])' : ''
|
||||
const suffix = isAsciiWordChar(token[token.length - 1]) ? '(?![A-Za-z0-9])' : ''
|
||||
return new RegExp(`${prefix}${escaped}${suffix}`, 'giu')
|
||||
}
|
||||
|
||||
/**
|
||||
* 사전 발음/변형 표기를 정본 표기로 바꾼다.
|
||||
* `matched` 에는 실제로 치환된 정본 단어(원표기), `changes` 에는 어절 단위 치환 내역이 담긴다.
|
||||
*/
|
||||
export function replaceDictionaryTerms(
|
||||
text: string,
|
||||
entries: readonly GlossaryDictionaryEntry[],
|
||||
): { text: string; matched: string[]; changes: TranscriptCorrectionEntry[] } {
|
||||
if (!text || text.trim().length === 0 || entries.length === 0) {
|
||||
return { text, matched: [], changes: [] }
|
||||
}
|
||||
let current = text
|
||||
const matched: string[] = []
|
||||
const changes: TranscriptCorrectionEntry[] = []
|
||||
for (const entry of entries) {
|
||||
const canonicalWord = entry.word?.trim()
|
||||
if (!canonicalWord) continue
|
||||
let hit = false
|
||||
const variants = splitGlossaryVariants(entry.pronunciation, canonicalWord).sort(
|
||||
(a, b) => b.length - a.length,
|
||||
)
|
||||
for (const variant of variants) {
|
||||
const regex = buildTokenRegex(variant)
|
||||
let found = false
|
||||
for (const match of current.matchAll(regex)) {
|
||||
const from = match[0]
|
||||
if (from === canonicalWord) continue
|
||||
if (changes.some((change) => change.from === from && change.to === canonicalWord)) continue
|
||||
changes.push({ from, to: canonicalWord, source: 'dictionary' })
|
||||
found = true
|
||||
}
|
||||
if (!found) continue
|
||||
hit = true
|
||||
current = current.replace(buildTokenRegex(variant), canonicalWord)
|
||||
}
|
||||
if (buildTokenRegex(canonicalWord).test(current)) hit = true
|
||||
if (hit && !matched.includes(canonicalWord)) matched.push(canonicalWord)
|
||||
}
|
||||
return { text: current, matched, changes }
|
||||
}
|
||||
|
||||
interface VocabularyCandidate {
|
||||
word: string
|
||||
count: number
|
||||
jamo: readonly string[]
|
||||
script: 'hangul' | 'latin'
|
||||
}
|
||||
|
||||
interface VocabularyIndex {
|
||||
byLength: Map<number, VocabularyCandidate[]>
|
||||
/** 소문자 정본 표기 — 이미 맞게 적힌 단어는 건드리지 않는다 */
|
||||
known: Set<string>
|
||||
}
|
||||
|
||||
/**
|
||||
* 어휘 인덱스 메모 — 글로서리는 15초 캐시로 재사용되므로 한 번 만들어 두고 계속 쓴다.
|
||||
* WeakMap 이라 글로서리가 버려지면 인덱스도 함께 사라진다.
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
function buildVocabularyIndex(glossary: TranscriptGlossary): VocabularyIndex {
|
||||
const cached = vocabularyIndexCache.get(glossary)
|
||||
if (cached) return cached
|
||||
const built = buildVocabularyIndexUncached(glossary)
|
||||
vocabularyIndexCache.set(glossary, built)
|
||||
return built
|
||||
}
|
||||
|
||||
function buildVocabularyIndexUncached(glossary: TranscriptGlossary): VocabularyIndex {
|
||||
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
|
||||
known.add(word)
|
||||
const candidate: VocabularyCandidate = {
|
||||
word,
|
||||
count,
|
||||
jamo: decomposeHangul(word),
|
||||
script,
|
||||
}
|
||||
const bucket = byLength.get(candidate.jamo.length)
|
||||
if (bucket) bucket.push(candidate)
|
||||
else byLength.set(candidate.jamo.length, [candidate])
|
||||
}
|
||||
return { byLength, known }
|
||||
}
|
||||
|
||||
/**
|
||||
* 학습 어절에서 1자모 차이 나는 유일한 후보를 찾는다.
|
||||
* 동률이면(어느 쪽이 맞는지 알 수 없으면) 고치지 않는다.
|
||||
*/
|
||||
function bestCandidate(token: string, index: VocabularyIndex): VocabularyCandidate | null {
|
||||
const script = scriptOf(token)
|
||||
if (!script) return null
|
||||
const jamo = decomposeHangul(token)
|
||||
let best: VocabularyCandidate | null = null
|
||||
let bestCount = 0
|
||||
let ties = 0
|
||||
for (const length of [jamo.length - 1, jamo.length, jamo.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.count > bestCount) {
|
||||
best = candidate
|
||||
bestCount = candidate.count
|
||||
ties = 0
|
||||
} else if (candidate.count === bestCount) {
|
||||
ties += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 학습 어휘로 어절을 되돌린다. 띄어쓰기·문장부호·조사는 그대로 두고 어절만 바꾼다.
|
||||
* 사용자가 실제로 쓴 어절(어휘에 있음)은 절대 건드리지 않는다.
|
||||
*/
|
||||
export function correctLearnedTerms(
|
||||
text: string,
|
||||
glossary: TranscriptGlossary,
|
||||
): CorrectedTranscript {
|
||||
const trimmed = text
|
||||
if (!trimmed || glossary.vocabulary.size === 0) return { text: trimmed, corrections: [] }
|
||||
|
||||
const index = buildVocabularyIndex(glossary)
|
||||
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 (corrections.length === 0) return { text: trimmed, corrections: [] }
|
||||
return { text: out + trimmed.slice(cursor), corrections }
|
||||
}
|
||||
|
||||
/**
|
||||
* LLM 교열 프롬프트에 넣는 참고 블록. 정보가 없으면 빈 문자열.
|
||||
*
|
||||
* 용어는 "이 표기를 그대로 쓰라"는 지시로, 예시는 "문체·용어 참고"로만 쓴다.
|
||||
* 예시 문장을 그대로 베끼게 하면 전사가 아니게 되므로 지시문에 명시한다.
|
||||
*/
|
||||
export function buildGlossaryPromptSection(glossary: TranscriptGlossary): string {
|
||||
if (isGlossaryEmpty(glossary)) return ''
|
||||
const parts: string[] = []
|
||||
if (glossary.dictionary.length > 0) {
|
||||
parts.push('[사용자 용어 — 이 표기를 그대로 쓰세요]')
|
||||
for (const entry of glossary.dictionary.slice(0, 30)) {
|
||||
parts.push(
|
||||
entry.variants.length > 0
|
||||
? `- ${entry.word} (다르게 들리면: ${entry.variants.join(', ')})`
|
||||
: `- ${entry.word}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (glossary.examples.length > 0) {
|
||||
parts.push('', '[사용자가 실제로 쓰는 표현 — 말투·용어만 참고하고 문장을 그대로 베끼지 마세요]')
|
||||
for (const example of glossary.examples.slice(0, TRANSCRIPT_GLOSSARY_LIMITS.refineExamples)) {
|
||||
parts.push(`- ${example}`)
|
||||
}
|
||||
}
|
||||
return parts.join('\n')
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue