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:
Yun Chan 2026-11-05 21:58:28 +09:00
parent d631042836
commit 9c2b6a9782
21 changed files with 1134 additions and 61 deletions

View file

@ -14,6 +14,7 @@ import { getLocalLLMService } from './LocalLLMService'
import { getHistoryService } from './HistoryService'
import { configGet } from './ConfigService'
import { buildCaptionRefinePrompt } from './llm-prompts'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { StreamingCaptionTrack, type CaptionTranscription } from './caption/StreamingCaptionTrack'
import { CaptionAudioSources } from './caption/CaptionAudioSources'
import { acceptCaptionRefinement } from '@d3ro/core/caption-streaming'
@ -97,6 +98,8 @@ const DEFAULT_START_OPTIONS: ResolvedStartOptions = {
interface CaptionServiceEvents {
'state-changed': (state: CaptionState) => void
'segment': (segment: CaptionSegment) => void
/** 다듬기(학습 어휘 교정·LLM 교열)로 확정 줄의 텍스트가 바뀌었다 */
'segment-updated': (update: { id: string; text: string }) => void
'delta': (data: { text: string; isFinal: boolean }) => void
'session-saved': (summary: CaptionSessionResult) => void
/**
@ -211,7 +214,8 @@ class CaptionService extends EventEmitter {
this._segments = []
this._refineQueue = []
this._sessionLanguage = null
// 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지
// 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지.
// 학습 어휘 힌트는 _transcribe 가 매 인식마다 덧붙인다(트랙 문맥에 섞이면 중복된다).
const lang = configGet('sttLanguage') as string | undefined
const initialContext = lang === 'ko' ? '다음은 한국어 대화입니다.' : ''
@ -467,7 +471,8 @@ class CaptionService extends EventEmitter {
const language = configured === 'auto' ? (this._sessionLanguage ?? 'auto') : configured
const result = await getLocalSTTService().transcribe(audio, {
language,
initialPrompt: opts.initialPrompt,
// 학습 어휘 힌트는 매 인식마다 붙인다 — rolling context 가 잘려도 용어 편향이 유지된다.
initialPrompt: getTranscriptGlossaryService().sttHint(opts.initialPrompt),
vadFilter: true,
partial: opts.partial,
modelId: this._captionModelId ?? undefined,
@ -493,7 +498,14 @@ class CaptionService extends EventEmitter {
this._sendToMainWindow(IPC_CHANNELS.CAPTION.DELTA, delta)
}
private _emitFinal(text: string, source: 'mic' | 'system'): void {
private _emitFinal(rawText: string, source: 'mic' | 'system'): void {
// 학습 어휘(사전 + 개인 문구)로 먼저 되돌린다 — LLM 이 꺼져 있어도 용어는 고쳐진다.
const corrected = getTranscriptGlossaryService().correct(rawText)
const text = corrected.text.trim()
if (!text) return
if (corrected.corrections.length > 0) {
logger.info(`자막 학습 어휘 교정 ${corrected.corrections.length}건 (${source})`)
}
const segment: CaptionSegment = {
id: crypto.randomUUID(),
text,
@ -534,7 +546,12 @@ class CaptionService extends EventEmitter {
const index = this._segments.findIndex((item) => item.id === segment.id)
if (index === -1) return
const previous = this._segments.slice(Math.max(0, index - 2), index).map((item) => item.text)
const { systemPrompt, text } = buildCaptionRefinePrompt({ text: segment.text, previous })
const glossary = getTranscriptGlossaryService().promptSection()
const { systemPrompt, text } = buildCaptionRefinePrompt({
text: segment.text,
previous,
...(glossary ? { glossary } : {}),
})
try {
const result = await getLocalLLMService().generate(text, {
systemPrompt,
@ -544,17 +561,24 @@ class CaptionService extends EventEmitter {
})
const refined = acceptCaptionRefinement(segment.text, result.text)
if (!refined) return
const current = this._segments.find((item) => item.id === segment.id)
if (!current) return
current.text = refined
const update = { id: segment.id, text: refined }
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
// 모델이 용어를 다른 표기로 되돌렸을 수 있다 — 정본 표기를 마지막에 다시 강제한다.
this._replaceSegmentText(segment.id, getTranscriptGlossaryService().correct(refined).text)
} catch (err) {
logger.debug(`자막 다듬기 건너뜀: ${err instanceof Error ? err.message : String(err)}`)
}
}
/** 확정 줄 텍스트를 바꾸고 오버레이·메인 창·회의 모드에 알린다. */
private _replaceSegmentText(segmentId: string, text: string): void {
const current = this._segments.find((item) => item.id === segmentId)
if (!current || current.text === text) return
current.text = text
const update = { id: segmentId, text }
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
this.emit('segment-updated', update)
}
// ── 내부: 세션 저장 ──
private _saveSession(persist: boolean): CaptionSessionResult | null {

View file

@ -9,6 +9,7 @@ import { getDatabase } from '../db'
import { dictionary } from '../db/schema'
import type { Dictionary, NewDictionary } from '../db/schema'
import { getLogger } from './LoggerService'
import { invalidateTranscriptGlossary } from './TranscriptGlossaryService'
import { getCloudSyncService } from './CloudSyncService'
import { getMainWindow } from '../windows/WindowManager'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
@ -114,6 +115,8 @@ class DictionaryService {
throw err
}
logger.info(`Dictionary entry added: "${word}"`)
// 학습 어휘 캐시(전사 교열·STT 힌트)는 즉시 무효화한다 — 방금 추가한 단어가 바로 쓰여야 한다.
invalidateTranscriptGlossary()
// Phase 3.3: 자동 push (fire-and-forget)
void getCloudSyncService().pushOne('dictionary', id)
return this._toEntry(entry as Dictionary)
@ -150,6 +153,7 @@ class DictionaryService {
}
const updated = db.select().from(dictionary).where(eq(dictionary.id, params.id)).get()
invalidateTranscriptGlossary()
// Phase 3.3: 자동 push (fire-and-forget)
void getCloudSyncService().pushOne('dictionary', params.id)
return updated ? this._toEntry(updated) : null
@ -158,7 +162,10 @@ class DictionaryService {
delete(id: string): boolean {
const db = getDatabase()
const result = db.delete(dictionary).where(eq(dictionary.id, id)).run()
if (result.changes > 0) getCloudSyncService().pushDelete('dictionary', id)
if (result.changes > 0) {
invalidateTranscriptGlossary()
getCloudSyncService().pushDelete('dictionary', id)
}
return result.changes > 0
}
@ -449,6 +456,7 @@ class DictionaryService {
logger.info(
`Dictionary import: ${outcome.imported} imported, ${outcome.skipped} skipped, ${outcome.errors} errors`
)
if (outcome.imported > 0) invalidateTranscriptGlossary()
return outcome
}

View file

@ -35,6 +35,7 @@ import type {
} from '@d3ro/core/types'
import { collapseRepeatedSegments, collapseRepeats, isDegenerateTranscript } from './file-transcription/repetition'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { SUPPORTED_MEDIA_EXTENSION_SET } from './file-transcription/media-formats'
const logger = getLogger('FileTranscriptionService')
@ -178,7 +179,8 @@ class FileTranscriptionService extends EventEmitter {
let result = await sttService.transcribe(chunkBuffer, {
language: lang,
initialPrompt: previousContext || undefined,
// 학습 어휘 힌트를 매 조각에 붙인다 — 앞 문맥이 없어도 고유명사 표기가 유지된다.
initialPrompt: getTranscriptGlossaryService().sttHint(previousContext) || undefined,
vadFilter: true,
})
// 인식 중에 취소됐으면 결과를 버린다(STT 호출 자체는 끊을 수 없다)
@ -187,12 +189,17 @@ class FileTranscriptionService extends EventEmitter {
// 앞 조각 힌트 때문에 반복 루프에 빠졌으면 힌트 없이 한 번 다시 듣는다
if (previousContext && isDegenerateTranscript(result.text ?? '')) {
logger.warn(`청크 ${i + 1}/${totalChunks}: 반복 루프 감지 — 앞 문맥 없이 다시 전사`)
result = await sttService.transcribe(chunkBuffer, { language: lang, vadFilter: true })
result = await sttService.transcribe(chunkBuffer, {
language: lang,
initialPrompt: getTranscriptGlossaryService().sttHint('') || undefined,
vadFilter: true,
})
throwIfCancelled()
}
const rawText = result.text?.trim() ?? ''
const chunkText = collapseRepeats(rawText)
// 학습 어휘(사전 + 개인 문구)로 잘못 들은 어절을 되돌린다.
const chunkText = getTranscriptGlossaryService().correct(collapseRepeats(rawText)).text
if (chunkText.length > 0) {
allTexts.push(chunkText)
// 반복으로 망가진 결과는 다음 조각의 힌트로 넘기지 않는다 — 넘기면 반복이 다음 조각으로 번졌다
@ -200,7 +207,7 @@ class FileTranscriptionService extends EventEmitter {
for (const seg of collapseRepeatedSegments(result.segments)) {
allSegments.push({
text: seg.text,
text: getTranscriptGlossaryService().correct(seg.text).text,
start: seg.start + startSec,
end: seg.end + startSec,
confidence: seg.confidence,

View file

@ -57,6 +57,7 @@ import {
} from '@d3ro/core/meeting-transcript'
import { markdownToDocx } from '@d3ro/core/utils/markdown-to-docx'
import { getFileTranscriptionService } from './FileTranscriptionService'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { buildImportedMeetingTranscript } from './meeting/imported-recording'
import type {
MeetingModeState,
@ -371,6 +372,11 @@ class MeetingModeService extends EventEmitter {
captionService.on('segment', listener)
return () => { captionService.off('segment', listener) }
},
// 다듬기(학습 어휘·LLM 교열)로 바뀐 줄도 받아야 회의록 전사가 원문에 머물지 않는다.
onSegmentUpdated: (listener) => {
captionService.on('segment-updated', listener)
return () => { captionService.off('segment-updated', listener) }
},
// 회의가 소유한 세션만 멈춘다. 다른 소유자면 false(요약 없음).
stop: () => captionService.stop('meeting'),
},
@ -385,6 +391,10 @@ class MeetingModeService extends EventEmitter {
this.emit('segment', segment)
this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.SEGMENT, segment)
},
onSegmentUpdated: (update) => {
this.emit('segment-updated', update)
this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.SEGMENT_UPDATED, update)
},
onStopError: (err) => {
logger.error(`자막 정지 실패 — 지금까지의 전사로 저장한다: ${err instanceof Error ? err.message : String(err)}`)
},
@ -1419,10 +1429,14 @@ class MeetingModeService extends EventEmitter {
if (!transcript) throw new D3ROError(ErrorCode.MeetingPolishFailed, '전사 텍스트가 없습니다')
const llm = await this._resolveMeetingLlm()
// 사용자가 학습시킨 용어·표현을 교열 지시에 넘긴다 — 예전엔 일반 프롬프트만 받아
// 고유명사·사내 용어가 매번 다르게 교정됐다.
const glossary = getTranscriptGlossaryService().promptSection()
const polished = await this._rewriteTranscriptInChunks(
llm,
transcript,
'다음 음성 전사 텍스트를 다듬어주세요. 필러 단어(음, 어, 그, 아, 뭐 등), 말 바꾸기(A 아니 A가 아니라 B → B), 불필요한 어절·의미 중복을 제거하고 문장 구조를 자연스럽게 교정하되, 화자의 원래 말투(반말/존댓말)와 의미·내용은 절대 변경하지 마세요. 타임스탬프 형식 [MM:SS]과 화자 표기([화자 N] 등)는 그대로 유지하세요.',
'다음 음성 전사 텍스트를 다듬어주세요. 필러 단어(음, 어, 그, 아, 뭐 등), 말 바꾸기(A 아니 A가 아니라 B → B), 불필요한 어절·의미 중복을 제거하고 문장 구조를 자연스럽게 교정하되, 화자의 원래 말투(반말/존댓말)와 의미·내용은 절대 변경하지 마세요. 타임스탬프 형식 [MM:SS]과 화자 표기([화자 N] 등)는 그대로 유지하세요.' +
(glossary ? `\n\n${glossary}` : ''),
ErrorCode.MeetingPolishFailed,
)

View file

@ -0,0 +1,184 @@
// src/main/services/TranscriptGlossaryService.ts
// 전사 교열용 학습 어휘 창구(싱글톤).
//
// 왜 필요한가:
// - 사용자가 키보드로 친 문장은 개인 그래프(personal_phrases)와 사전(dictionary)에 쌓이지만,
// 회의록·자막 전사에는 그 어휘가 한 번도 쓰이지 않았다. 자막은 `다음은 한국어 대화입니다.`라는
// 고정 힌트로 인식됐고, 확정된 줄은 용어 사전 없이 일반 프롬프트로만 다듬어졌다.
// - 이 서비스는 그 어휘를 한 곳에서 모아 STT 힌트·결정적 교정·LLM 교열 참고 블록으로 공급한다.
// 교정 규칙 자체는 core `transcript-correction` 이 정본이고, 여기서는 소스 수집과 캐시만 맡는다.
//
// 소스는 주입 가능하다(테스트는 DB 없이 가짜 소스).
import { desc } from 'drizzle-orm'
import { getLogger } from './LoggerService'
import { getDatabase } from '../db'
import { dictionary, personalPhrases } from '../db/schema'
import {
appendGlossaryHint,
buildGlossaryPromptSection,
buildTranscriptGlossary,
correctLearnedTerms,
isGlossaryEmpty,
replaceDictionaryTerms,
type CorrectedTranscript,
type GlossaryDictionaryEntry,
type GlossaryPhrase,
type TranscriptCorrectionEntry,
type TranscriptGlossary,
} from '@d3ro/core/transcript-correction'
const logger = getLogger('TranscriptGlossaryService')
/** 학습 어휘 캐시 수명. 사전/학습은 회의 중에도 늘 수 있으므로 짧게 둔다. */
const GLOSSARY_TTL_MS = 15_000
export interface TranscriptGlossarySources {
/** 사용자 사전 (정본 단어 + 발음 변형) */
listDictionary(): readonly GlossaryDictionaryEntry[]
/** 개인 그래프에서 배운 문구 (빈도 포함) */
listPhrases(): readonly GlossaryPhrase[]
now?: () => number
}
interface CachedGlossary {
glossary: TranscriptGlossary
at: number
}
export class TranscriptGlossaryService {
private _cache: CachedGlossary | null = null
private readonly _now: () => number
constructor(
private readonly _sources: TranscriptGlossarySources,
private readonly _ttlMs: number = GLOSSARY_TTL_MS,
) {
this._now = _sources.now ?? Date.now
}
/** 현재 글로서리 (TTL 캐시). 소스가 실패하면 빈 글로서리 — 전사는 계속돼야 한다. */
get(): TranscriptGlossary {
const now = this._now()
if (this._cache && now - this._cache.at < this._ttlMs) return this._cache.glossary
let glossary: TranscriptGlossary
try {
glossary = buildTranscriptGlossary({
dictionary: this._sources.listDictionary(),
phrases: this._sources.listPhrases(),
})
} catch (err) {
logger.warn(`학습 어휘 수집 실패 — 이번 전사는 어휘 없이 진행: ${err instanceof Error ? err.message : String(err)}`)
glossary = buildTranscriptGlossary({})
}
this._cache = { glossary, at: now }
return glossary
}
/** 사전·학습이 바뀌었을 때 호출한다. */
invalidate(): void {
this._cache = null
}
/** STT initial_prompt 에 학습 어휘 힌트를 덧붙인다. */
sttHint(base: string): string {
return appendGlossaryHint(base, this.get())
}
/** LLM 교열 프롬프트에 넣는 용어·문체 참고 블록 (없으면 빈 문자열). */
promptSection(): string {
return buildGlossaryPromptSection(this.get())
}
/**
* 학습 어휘 기반 결정적 교정 (LLM 없이 즉시).
* 1) 사전 발음 변형 → 정본 표기
* 2) 학습 어절과 1자모 차이 나는 전사 어절 → 학습 어절
* 사용자가 실제로 쓴 어절은 건드리지 않는다(core 규칙).
*/
correct(text: string): CorrectedTranscript {
if (!text || text.trim().length === 0) return { text, corrections: [] }
const glossary = this.get()
if (isGlossaryEmpty(glossary)) return { text, corrections: [] }
const corrections: TranscriptCorrectionEntry[] = []
let current = text
if (glossary.dictionary.length > 0) {
const dictionaryPass = replaceDictionaryTerms(
current,
glossary.dictionary.map((entry) => ({ word: entry.word, pronunciation: entry.variants.join(',') })),
)
current = dictionaryPass.text
corrections.push(...dictionaryPass.changes)
}
const learned = correctLearnedTerms(current, glossary)
if (learned.corrections.length > 0) corrections.push(...learned.corrections)
return { text: learned.text, corrections }
}
/**
* 학습 어절만 교정한다. 사전 치환을 호출자가 사용 횟수 집계와 함께 처리하는 경로
* (받아쓰기)에서 쓴다.
*/
correctLearned(text: string): CorrectedTranscript {
if (!text || text.trim().length === 0) return { text, corrections: [] }
const glossary = this.get()
if (isGlossaryEmpty(glossary)) return { text, corrections: [] }
return correctLearnedTerms(text, glossary)
}
}
let instance: TranscriptGlossaryService | null = null
/** DB 기반 기본 소스. DB 가 아직 없으면 빈 어휘를 돌려준다(전사를 막지 않는다). */
function defaultSources(): TranscriptGlossarySources {
return {
listDictionary: () => {
try {
return getDatabase()
.select({ word: dictionary.word, pronunciation: dictionary.pronunciation })
.from(dictionary)
.orderBy(desc(dictionary.usageCount))
.limit(300)
.all()
} catch {
return []
}
},
listPhrases: () => {
try {
return getDatabase()
.select({ text: personalPhrases.phrase, count: personalPhrases.count })
.from(personalPhrases)
.orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt))
.limit(400)
.all()
} catch {
return []
}
},
}
}
export function initTranscriptGlossaryService(
sources: TranscriptGlossarySources = defaultSources(),
ttlMs?: number,
): TranscriptGlossaryService {
instance = new TranscriptGlossaryService(sources, ttlMs)
return instance
}
export function getTranscriptGlossaryService(): TranscriptGlossaryService {
if (!instance) instance = initTranscriptGlossaryService()
return instance
}
/** 사전·학습이 바뀌었을 때 호출한다(아직 만들지 않았으면 아무 것도 하지 않는다). */
export function invalidateTranscriptGlossary(): void {
instance?.invalidate()
}
export function resetTranscriptGlossaryServiceForTests(): void {
instance = null
}

View file

@ -27,6 +27,7 @@ import { configGet } from './ConfigService'
import { getTextInsertService } from './TextInsertService'
import { getLocalLLMService } from './LocalLLMService'
import { getLlmGateway } from './llm/LlmGateway'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { cleanDictatedText } from '@d3ro/core/dictation-cleaner'
@ -907,13 +908,12 @@ class VoiceModeService extends EventEmitter {
const stt = getSTTManager()
const language = configGet('sttLanguage')
// Dictionary → STT initialPrompt 주입 (Speakly 패턴)
// 사전 + 학습 어휘 → STT initial_prompt 주입 (사용자가 학습시킨 용어를 인식 단계에서 미리 편향)
let initialPrompt: string | undefined
try {
const { getDictionaryService } = await import('./DictionaryService')
initialPrompt = getDictionaryService().getPromptHints() || undefined
initialPrompt = getTranscriptGlossaryService().sttHint('') || undefined
} catch {
// DictionaryService 미초기화 시 무시
// 학습 어휘 소스 미준비 시 무시
}
// 사이드카는 요청을 직렬 처리하므로, 진행 중인 미리보기 요청이 최종 전사를
@ -950,6 +950,8 @@ class VoiceModeService extends EventEmitter {
} catch {
// DictionaryService 미초기화 시 무시
}
// 사전에 없는 개인 어휘(학습한 어절)로 남은 오인식을 되돌린다.
rawText = getTranscriptGlossaryService().correctLearned(rawText).text
if (this._session) {
this._session.transcription = rawText

View file

@ -529,6 +529,8 @@ const CAPTION_REFINE_SYSTEM_PROMPT = `실시간 음성 인식으로 받아 적
규칙:
- 띄어쓰기, 문장부호, 앞 문맥으로 볼 때 명백하게 잘못 들은 단어만 고치세요.
- [사용자 용어] 가 있으면 전사에 나온 비슷한 표기를 그 용어로 바꾸세요(고유명사·제품명·사내 용어).
- [사용자가 실제로 쓰는 표현] 은 말투·용어 참고용입니다. 그 문장을 그대로 옮기거나 문장을 새로 쓰지 마세요.
- 뜻을 바꾸거나, 요약하거나, 말을 더하거나 빼지 마세요.
- 원문과 같은 언어, 같은 말투(존댓말/반말, 구어체)를 유지하세요.
- 고친 문장 한 줄만 출력하세요. 설명, 따옴표, 번호를 붙이지 마세요.
@ -537,8 +539,12 @@ const CAPTION_REFINE_SYSTEM_PROMPT = `실시간 음성 인식으로 받아 적
export function buildCaptionRefinePrompt(input: {
text: string
previous: readonly string[]
/** 학습 어휘 참고 블록 (`buildGlossaryPromptSection` 결과) */
glossary?: string
}): { systemPrompt: string; text: string } {
const sections: string[] = []
const glossary = input.glossary?.trim()
if (glossary) sections.push(glossary, '')
const previous = input.previous.filter((line) => line.trim().length > 0).slice(-2)
if (previous.length > 0) sections.push('[앞 문맥]', ...previous, '')
sections.push('[다듬을 자막]', input.text.trim())

View file

@ -16,6 +16,8 @@ import type { CaptionSegment, MeetingMemo } from '@d3ro/core/types'
export interface RecordingCaptionPort {
/** 확정 세그먼트 구독 — 해지 함수를 돌려준다 */
onSegment(listener: (segment: CaptionSegment) => void): () => void
/** 다듬기(학습 어휘·LLM 교열)로 확정 세그먼트 텍스트가 바뀌었을 때 (선택) */
onSegmentUpdated?(listener: (update: { id: string; text: string }) => void): () => void
/** 이 녹음이 소유한 자막 세션을 멈춘다(마지막 문장 flush 포함). 세그먼트 요약을 돌려줄 수 있다. */
stop(): Promise<{ segments: CaptionSegment[] } | null | false>
}
@ -31,6 +33,8 @@ export interface MeetingRecordingSessionPorts {
now?: () => number
/** 세그먼트가 이 녹음에 추가될 때(구독으로 받은 것만) */
onSegment?: (segment: CaptionSegment) => void
/** 세그먼트 텍스트가 다듬어졌을 때 — 화면·기록이 원문에 머물지 않게 알린다 */
onSegmentUpdated?: (update: { id: string; text: string }) => void
/** 자막 정지 실패 — 정지는 계속 진행된다(스냅샷은 그때까지의 세그먼트로 만든다) */
onStopError?: (error: unknown) => void
}
@ -54,6 +58,7 @@ export class MeetingRecordingSession {
private _audio: Buffer[] = []
private _lastRms = 0
private _unsubscribeSegment: (() => void) | null = null
private _unsubscribeSegmentUpdated: (() => void) | null = null
private _unsubscribeAudio: (() => void) | null = null
private _stopPromise: Promise<RecordingSnapshot> | null = null
private _snapshot: RecordingSnapshot | null = null
@ -74,6 +79,13 @@ export class MeetingRecordingSession {
this._segments.push(segment)
this._ports.onSegment?.(segment)
})
this._unsubscribeSegmentUpdated =
this._ports.caption.onSegmentUpdated?.((update) => {
const target = this._segments.find((segment) => segment.id === update.id)
if (!target || target.text === update.text) return
target.text = update.text
this._ports.onSegmentUpdated?.(update)
}) ?? null
}
/** 오디오 구독을 건다(파일 저장·레벨 표시용). */
@ -89,6 +101,8 @@ export class MeetingRecordingSession {
detach(): void {
this._unsubscribeSegment?.()
this._unsubscribeSegment = null
this._unsubscribeSegmentUpdated?.()
this._unsubscribeSegmentUpdated = null
this._unsubscribeAudio?.()
this._unsubscribeAudio = null
}
@ -158,6 +172,8 @@ export class MeetingRecordingSession {
} finally {
this._unsubscribeSegment?.()
this._unsubscribeSegment = null
this._unsubscribeSegmentUpdated?.()
this._unsubscribeSegmentUpdated = null
}
// 구독 밖에서 확정된 세그먼트가 있으면 요약에서 보충한다
if (summary) {

View file

@ -793,6 +793,9 @@ const electronAPI = {
on(IPC_CHANNELS.MEETING_MODE.STATE_CHANGED, cb),
onSegment: (cb: (e: CaptionSegment) => void): Unsubscribe =>
on(IPC_CHANNELS.MEETING_MODE.SEGMENT, cb),
/** 다듬기(학습 어휘·LLM 교열)로 바뀐 확정 줄 — 화면이 원문에 머물지 않게 갱신한다 */
onSegmentUpdated: (cb: (e: { id: string; text: string }) => void): Unsubscribe =>
on(IPC_CHANNELS.MEETING_MODE.SEGMENT_UPDATED, cb),
onProcessingProgress: (cb: (e: MeetingProcessingProgress) => void): Unsubscribe =>
on(IPC_CHANNELS.MEETING_MODE.PROCESSING_PROGRESS, cb),
onSessionCompleted: (cb: (e: MeetingSessionDetail) => void): Unsubscribe =>

View file

@ -187,6 +187,11 @@ export function MeetingModePage(): React.ReactElement {
}, 50)
})
// 다듬기(학습 어휘·LLM 교열)로 확정 줄이 바뀌면 화면도 그 문장으로 바꾼다.
const unsubSegmentUpdated = window.electronAPI.meetingMode.onSegmentUpdated((update) => {
setSegments((prev) => replaceSegmentText(prev, update.id, update.text))
})
const unsubProgress = window.electronAPI.meetingMode.onProcessingProgress((p) => {
setProgress(p)
})
@ -213,6 +218,7 @@ export function MeetingModePage(): React.ReactElement {
return () => {
unsubState()
unsubSegment()
unsubSegmentUpdated()
unsubProgress()
unsubCompleted()
unsubError()

View file

@ -0,0 +1,155 @@
// tests/main/services/transcript-glossary.test.ts
// 학습한 어휘(사용자 사전 + 개인 문구)가 전사 교열에 실제로 쓰이는지 검증한다.
// 예전에는 자막이 고정 힌트로만 인식되고, 전사된 줄은 용어 사전 없이 다듬어져
// 사용자가 키보드로 배운 표기가 회의록에 반영되지 않았다.
import { describe, expect, it } from 'vitest'
import { useRedHarness } from '../../red/harness'
import {
getTranscriptGlossaryService,
TranscriptGlossaryService,
} from '../../../src/main/services/TranscriptGlossaryService'
import { getDictionaryService } from '../../../src/main/services/DictionaryService'
import { getPersonalGraphService } from '../../../src/main/services/PersonalGraphService'
import { MeetingRecordingSession } from '../../../src/main/services/meeting/MeetingRecordingSession'
import type { CaptionSegment } from '@d3ro/core/types'
useRedHarness()
/** 같은 문장을 n 번 친 것으로 개인 그래프에 남긴다(count 누적). */
function learnPhrase(text: string, times: number): void {
for (let i = 0; i < times; i += 1) {
getPersonalGraphService().indexText(text, { source: 'typed', appName: 'notepad.exe' })
}
}
describe('학습한 어휘가 전사 교정에 쓰인다', () => {
it('키보드로 배운 어절과 한 글자 다른 전사 어절을 되돌린다', () => {
learnPhrase('회의록 정리해줘', 5)
const result = getTranscriptGlossaryService().correct('회이록 정리해줘')
expect(result.text).toBe('회의록 정리해줘')
expect(result.corrections).toEqual([{ from: '회이록', to: '회의록', source: 'learned' }])
})
it('사용자 사전의 발음 표기를 정본 표기로 바꾼다', () => {
getDictionaryService().add({ word: 'D3RO', pronunciation: '디에로' })
const result = getTranscriptGlossaryService().correct('디에로 보이스 좋네요')
expect(result.text).toBe('D3RO 보이스 좋네요')
})
it('STT 힌트에 사전 단어와 학습 어절이 함께 들어간다', () => {
getDictionaryService().add({ word: 'Whisper' })
learnPhrase('녹음 파일 올려줘', 4)
const hint = getTranscriptGlossaryService().sttHint('다음은 한국어 대화입니다.')
expect(hint.startsWith('다음은 한국어 대화입니다.')).toBe(true)
expect(hint).toContain('Whisper')
expect(hint).toContain('녹음')
})
it('한 번만 쓴 어절은 학습 어휘로 쓰지 않는다', () => {
learnPhrase('회의록 정리해줘', 1)
const result = getTranscriptGlossaryService().correct('회이록 정리해줘')
expect(result.text).toBe('회이록 정리해줘')
})
it('사전에 단어를 추가하면 캐시를 기다리지 않고 바로 반영된다', () => {
expect(getTranscriptGlossaryService().sttHint('')).not.toContain('Supabase')
getDictionaryService().add({ word: 'Supabase', pronunciation: '수파베이스' })
expect(getTranscriptGlossaryService().sttHint('')).toContain('Supabase')
})
it('LLM 교열 프롬프트에 사용자 용어 블록을 넣는다', () => {
getDictionaryService().add({ word: 'D3RO', pronunciation: '디에로' })
learnPhrase('오늘 회의는 세 시에 시작합니다', 3)
const section = getTranscriptGlossaryService().promptSection()
expect(section).toContain('[사용자 용어')
expect(section).toContain('D3RO')
expect(section).toContain('오늘 회의는 세 시에 시작합니다')
})
})
describe('글로서리 캐시', () => {
it('캐시가 살아 있으면 소스를 다시 읽지 않고, 무효화하면 다시 읽는다', () => {
let dictionaryReads = 0
let now = 1_000
const service = new TranscriptGlossaryService(
{
listDictionary: () => {
dictionaryReads += 1
return [{ word: 'D3RO', pronunciation: null }]
},
listPhrases: () => [{ text: '회의록 정리해줘', count: 5 }],
now: () => now,
},
1_000,
)
service.get()
service.get()
expect(dictionaryReads).toBe(1)
now += 1_500
service.get()
expect(dictionaryReads).toBe(2)
service.invalidate()
service.get()
expect(dictionaryReads).toBe(3)
})
it('소스가 실패해도 빈 어휘로 진행한다', () => {
const service = new TranscriptGlossaryService({
listDictionary: () => {
throw new Error('db down')
},
listPhrases: () => [{ text: '회의록', count: 5 }],
})
expect(service.get().promptHint).toBe('')
expect(service.correct('회이록').text).toBe('회이록')
})
})
describe('회의 세션이 다듬어진 줄을 받는다', () => {
it('자막이 알린 수정 문장이 회의 세그먼트에 반영된다', () => {
const segmentListeners = new Set<(segment: CaptionSegment) => void>()
const updateListeners = new Set<(update: { id: string; text: string }) => void>()
const updates: Array<{ id: string; text: string }> = []
const session = new MeetingRecordingSession('session-1', 0, {
caption: {
onSegment: (listener) => {
segmentListeners.add(listener)
return () => segmentListeners.delete(listener)
},
onSegmentUpdated: (listener) => {
updateListeners.add(listener)
return () => updateListeners.delete(listener)
},
stop: async () => null,
},
audio: { onChunk: () => () => undefined },
onSegmentUpdated: (update) => updates.push(update),
now: () => 1_000,
})
session.attachCaption()
const segment: CaptionSegment = { id: 'seg-1', text: '회이록 정리해줘', timestamp: 500, isFinal: true }
for (const listener of segmentListeners) listener(segment)
for (const listener of updateListeners) listener({ id: 'seg-1', text: '회의록 정리해줘' })
expect(session.segments[0].text).toBe('회의록 정리해줘')
expect(updates).toEqual([{ id: 'seg-1', text: '회의록 정리해줘' }])
})
})

View file

@ -36,6 +36,7 @@ import {
LocalSTTService,
resetLocalSTTServiceForTests,
} from '../../src/main/services/LocalSTTService'
import { resetTranscriptGlossaryServiceForTests } from '../../src/main/services/TranscriptGlossaryService'
import { D3ROError, ErrorCode, type IPCResult } from '@d3ro/core/errors'
import type { NewHistory } from '../../src/main/db/schema'
@ -102,6 +103,7 @@ export function resetAllSingletons(): void {
resetMeetingSummaryServiceForTests()
resetLocalLLMServiceForTests()
resetLocalSTTServiceForTests()
resetTranscriptGlossaryServiceForTests()
}
export function useRedHarness(): void {