fix(file-transcription): stop a Whisper repetition loop from spreading to every following chunk
Each 30-second chunk received the previous chunk's text as initial_prompt, so once one chunk looped on a word the loop became the next chunk's hint and the rest of the file was the same word. A looping chunk is now re-transcribed without the hint, looped text is never carried forward, and runs of 4+ identical phrases or segments are collapsed to one.
This commit is contained in:
parent
a14bb52b7f
commit
45d8b1ddb1
4 changed files with 236 additions and 6 deletions
|
|
@ -34,6 +34,8 @@ import type {
|
|||
FileTranscriptionStateInfo,
|
||||
} from '@d3ro/core/types'
|
||||
|
||||
import { collapseRepeatedSegments, collapseRepeats, isDegenerateTranscript } from './file-transcription/repetition'
|
||||
|
||||
const logger = getLogger('FileTranscriptionService')
|
||||
|
||||
/** 청크 길이 (초) */
|
||||
|
|
@ -172,7 +174,7 @@ class FileTranscriptionService extends EventEmitter {
|
|||
const sttService = getSTTManager()
|
||||
const lang = language ?? (configGet('sttLanguage') as string | undefined) ?? 'auto'
|
||||
|
||||
const result = await sttService.transcribe(chunkBuffer, {
|
||||
let result = await sttService.transcribe(chunkBuffer, {
|
||||
language: lang,
|
||||
initialPrompt: previousContext || undefined,
|
||||
vadFilter: true,
|
||||
|
|
@ -180,11 +182,21 @@ class FileTranscriptionService extends EventEmitter {
|
|||
// 인식 중에 취소됐으면 결과를 버린다(STT 호출 자체는 끊을 수 없다)
|
||||
throwIfCancelled()
|
||||
|
||||
if (result.text && result.text.trim().length > 0) {
|
||||
allTexts.push(result.text.trim())
|
||||
previousContext = result.text.trim().slice(-CONTEXT_WINDOW_SIZE)
|
||||
// 앞 조각 힌트 때문에 반복 루프에 빠졌으면 힌트 없이 한 번 다시 듣는다
|
||||
if (previousContext && isDegenerateTranscript(result.text ?? '')) {
|
||||
logger.warn(`청크 ${i + 1}/${totalChunks}: 반복 루프 감지 — 앞 문맥 없이 다시 전사`)
|
||||
result = await sttService.transcribe(chunkBuffer, { language: lang, vadFilter: true })
|
||||
throwIfCancelled()
|
||||
}
|
||||
|
||||
for (const seg of result.segments) {
|
||||
const rawText = result.text?.trim() ?? ''
|
||||
const chunkText = collapseRepeats(rawText)
|
||||
if (chunkText.length > 0) {
|
||||
allTexts.push(chunkText)
|
||||
// 반복으로 망가진 결과는 다음 조각의 힌트로 넘기지 않는다 — 넘기면 반복이 다음 조각으로 번졌다
|
||||
previousContext = isDegenerateTranscript(rawText) ? '' : chunkText.slice(-CONTEXT_WINDOW_SIZE)
|
||||
|
||||
for (const seg of collapseRepeatedSegments(result.segments)) {
|
||||
allSegments.push({
|
||||
text: seg.text,
|
||||
start: seg.start + startSec,
|
||||
|
|
@ -192,6 +204,8 @@ class FileTranscriptionService extends EventEmitter {
|
|||
confidence: seg.confidence,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
previousContext = ''
|
||||
}
|
||||
|
||||
const progress: FileTranscriptionProgress = {
|
||||
|
|
@ -199,7 +213,7 @@ class FileTranscriptionService extends EventEmitter {
|
|||
currentChunk: i + 1,
|
||||
totalChunks,
|
||||
percent: Math.round(((i + 1) / totalChunks) * 100),
|
||||
currentText: result.text?.trim() ?? '',
|
||||
currentText: chunkText,
|
||||
}
|
||||
if (this._job === job) this._progress = progress
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,66 @@
|
|||
// src/main/services/file-transcription/repetition.ts
|
||||
// Whisper 반복 루프(같은 단어·구절을 수십 번 되풀이) 감지와 정리 — 순수 함수.
|
||||
//
|
||||
// 파일 전사는 30초 조각마다 앞 조각 결과를 다음 조각의 initial_prompt 로 넘긴다. 한 조각이 반복으로
|
||||
// 망가지면 그 반복이 다음 조각의 힌트가 돼 더 심하게 반복하고, 초반 몇 조각 뒤로는 같은 단어만 남았다.
|
||||
|
||||
/** 이 횟수 이상 연속으로 되풀이된 구절만 반복 루프로 본다("네 네 네" 같은 실제 말은 남긴다). */
|
||||
const MIN_LOOP_REPEATS = 4
|
||||
/** 반복 단위로 볼 구절의 최대 길이(자) */
|
||||
const MAX_UNIT_CHARS = 40
|
||||
/** 정리 뒤 이 비율 미만으로 줄면 그 결과는 반복 루프로 망가진 것이다. */
|
||||
const DEGENERATE_RATIO = 0.5
|
||||
|
||||
// 같은 구절(1~40자)이 공백·문장부호를 사이에 두고 4번 이상 이어진 구간
|
||||
const LOOP_PATTERN = new RegExp(
|
||||
`(\\S(?:.{0,${MAX_UNIT_CHARS - 1}}?\\S)?)(?:[\\s,.!?…·]*\\1){${MIN_LOOP_REPEATS - 1},}`,
|
||||
'gu',
|
||||
)
|
||||
|
||||
/** 연속 반복 구간을 한 번으로 줄인다. */
|
||||
export function collapseRepeats(text: string): string {
|
||||
let current = text
|
||||
// 짧은 단위가 긴 단위 안에 숨어 있을 수 있어 바뀌지 않을 때까지(최대 3회) 반복한다.
|
||||
for (let pass = 0; pass < 3; pass += 1) {
|
||||
const next = current.replace(LOOP_PATTERN, '$1')
|
||||
if (next === current) break
|
||||
current = next
|
||||
}
|
||||
return current.replace(/\s{2,}/gu, ' ').trim()
|
||||
}
|
||||
|
||||
/** 반복 루프로 망가진 결과인가 — 정리하면 절반 넘게 사라지는 경우. */
|
||||
export function isDegenerateTranscript(text: string): boolean {
|
||||
const trimmed = text.trim()
|
||||
if (trimmed.length === 0) return false
|
||||
return collapseRepeats(trimmed).length < trimmed.length * DEGENERATE_RATIO
|
||||
}
|
||||
|
||||
export interface TimedSegment {
|
||||
text: string
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 구간 목록 정리: 각 구간의 반복을 줄이고, 같은 문장이 연속 구간으로 되풀이되면 하나로 합친다.
|
||||
* (루프는 같은 문장의 구간을 수십 개 만들기도 한다 — 합칠 때 끝 시각은 마지막 구간을 따른다.)
|
||||
*/
|
||||
export function collapseRepeatedSegments<T extends TimedSegment>(segments: readonly T[]): T[] {
|
||||
const result: T[] = []
|
||||
for (const segment of segments) {
|
||||
const text = collapseRepeats(segment.text)
|
||||
if (text.length === 0) continue
|
||||
const previous = result[result.length - 1]
|
||||
if (previous && normalizeForCompare(previous.text) === normalizeForCompare(text)) {
|
||||
result[result.length - 1] = { ...previous, end: segment.end }
|
||||
continue
|
||||
}
|
||||
result.push({ ...segment, text })
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function normalizeForCompare(text: string): string {
|
||||
return text.replace(/[\s,.!?…·]+/gu, '').toLowerCase()
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
// 파일 전사: 한 조각이 반복 루프에 빠져도 그 반복이 다음 조각으로 번지지 않는다.
|
||||
// (앞 조각 결과를 다음 조각 initial_prompt 로 넘겨, 초반 뒤로는 같은 단어만 되풀이되던 버그)
|
||||
|
||||
import { EventEmitter } from 'events'
|
||||
import fs from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const LOOP = Array(20).fill('감사합니다').join(' ')
|
||||
|
||||
const hoisted = vi.hoisted(() => ({
|
||||
spawn: vi.fn(),
|
||||
transcribe: vi.fn(),
|
||||
}))
|
||||
vi.mock('child_process', () => ({ spawn: hoisted.spawn }))
|
||||
vi.mock('../../../src/main/utils/paths', () => ({ getFfmpegPath: () => '/bundled/ffmpeg.exe' }))
|
||||
vi.mock('../../../src/main/services/RuntimeProvisioner', () => ({ getRuntimeProvisioner: () => ({ ensure: vi.fn() }) }))
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
|
||||
}))
|
||||
vi.mock('../../../src/main/services/ConfigService', () => ({ configGet: vi.fn(() => undefined) }))
|
||||
vi.mock('../../../src/main/services/stt/STTManager', () => ({
|
||||
getSTTManager: () => ({ transcribe: hoisted.transcribe }),
|
||||
}))
|
||||
vi.mock('../../../src/main/services/HistoryService', () => ({ getHistoryService: () => ({ create: vi.fn() }) }))
|
||||
vi.mock('../../../src/main/services/LicenseService', () => ({
|
||||
getLicenseService: () => ({ canUse: () => ({ allowed: true }), promptUpgrade: vi.fn() }),
|
||||
}))
|
||||
vi.mock('../../../src/main/windows/WindowManager', () => ({ getMainWindow: () => null }))
|
||||
|
||||
function fakeSpawn(_command: string, args: string[]): EventEmitter {
|
||||
const proc = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
exitCode: null as number | null,
|
||||
killed: false,
|
||||
kill: () => true,
|
||||
})
|
||||
queueMicrotask(() => {
|
||||
// 90초 = 30초 조각 3개
|
||||
if (args.includes('null')) proc.stderr.emit('data', Buffer.from('Duration: 00:01:30.00'))
|
||||
if (args.includes('pipe:1')) proc.stdout.emit('data', Buffer.from('pcm'))
|
||||
proc.exitCode = 0
|
||||
proc.emit('close', 0)
|
||||
})
|
||||
return proc
|
||||
}
|
||||
|
||||
describe('FileTranscriptionService 반복 루프', () => {
|
||||
let inputFile: string
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
hoisted.spawn.mockImplementation(fakeSpawn)
|
||||
inputFile = path.join(os.tmpdir(), `d3ro-ft-loop-${Date.now()}.mp3`)
|
||||
fs.writeFileSync(inputFile, 'x')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
fs.rmSync(inputFile, { force: true })
|
||||
})
|
||||
|
||||
it('힌트 때문에 반복하면 힌트 없이 다시 전사하고, 반복은 다음 조각 힌트로 넘기지 않는다', async () => {
|
||||
const prompts: Array<string | undefined> = []
|
||||
const replies = [
|
||||
'첫 번째 내용입니다.', // 조각 1
|
||||
LOOP, // 조각 2 — 앞 문맥 힌트 때문에 루프
|
||||
'두 번째 내용입니다.', // 조각 2 재시도(힌트 없음)
|
||||
'세 번째 내용입니다.', // 조각 3
|
||||
]
|
||||
hoisted.transcribe.mockImplementation(async (_buf: Buffer, opts: { initialPrompt?: string }) => {
|
||||
prompts.push(opts.initialPrompt)
|
||||
const text = replies[prompts.length - 1]
|
||||
return { text, segments: [{ text, start: 0, end: 3 }] }
|
||||
})
|
||||
|
||||
const mod = await import('../../../src/main/services/FileTranscriptionService')
|
||||
mod.resetFileTranscriptionServiceForTests()
|
||||
const result = await mod.getFileTranscriptionService().startTranscription(inputFile, 'ko')
|
||||
|
||||
expect(result.fullText).toBe('첫 번째 내용입니다. 두 번째 내용입니다. 세 번째 내용입니다.')
|
||||
expect(result.fullText).not.toContain('감사합니다')
|
||||
// 재시도는 힌트 없이, 다음 조각은 정상 결과를 힌트로 받는다
|
||||
expect(prompts).toEqual([undefined, '첫 번째 내용입니다.', undefined, '두 번째 내용입니다.'])
|
||||
})
|
||||
|
||||
it('다시 들어도 반복이면 한 번으로 줄이고, 다음 조각에는 힌트를 주지 않는다', async () => {
|
||||
const prompts: Array<string | undefined> = []
|
||||
hoisted.transcribe.mockImplementation(async (_buf: Buffer, opts: { initialPrompt?: string }) => {
|
||||
prompts.push(opts.initialPrompt)
|
||||
return { text: `회의 시작 ${LOOP}`, segments: [] }
|
||||
})
|
||||
|
||||
const mod = await import('../../../src/main/services/FileTranscriptionService')
|
||||
mod.resetFileTranscriptionServiceForTests()
|
||||
const result = await mod.getFileTranscriptionService().startTranscription(inputFile, 'ko')
|
||||
|
||||
expect(result.fullText).toBe('회의 시작 감사합니다 회의 시작 감사합니다 회의 시작 감사합니다')
|
||||
expect(prompts.every((p) => p === undefined)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
// Whisper 반복 루프 정리 — 파일 전사에서 같은 단어만 되풀이되던 버그
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
collapseRepeatedSegments,
|
||||
collapseRepeats,
|
||||
isDegenerateTranscript,
|
||||
} from '../../../../src/main/services/file-transcription/repetition'
|
||||
|
||||
describe('collapseRepeats', () => {
|
||||
it('4번 이상 이어진 같은 단어·구절을 한 번으로 줄인다', () => {
|
||||
expect(collapseRepeats('회의를 시작합니다. 감사합니다 감사합니다 감사합니다 감사합니다 감사합니다')).toBe(
|
||||
'회의를 시작합니다. 감사합니다',
|
||||
)
|
||||
expect(collapseRepeats('그래서 우리는 그래서 우리는 그래서 우리는 그래서 우리는 다음 주에')).toBe('그래서 우리는 다음 주에')
|
||||
expect(collapseRepeats('네.네.네.네.네.네.')).toBe('네.')
|
||||
})
|
||||
|
||||
it('실제 말에 나올 만한 짧은 반복(3번 이하)은 남긴다', () => {
|
||||
expect(collapseRepeats('네 네 네 알겠습니다')).toBe('네 네 네 알겠습니다')
|
||||
expect(collapseRepeats('정말 정말 좋았어요')).toBe('정말 정말 좋았어요')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isDegenerateTranscript', () => {
|
||||
it('반복이 대부분이면 망가진 결과로 본다', () => {
|
||||
expect(isDegenerateTranscript(Array(20).fill('자막 제공').join(' '))).toBe(true)
|
||||
expect(isDegenerateTranscript('오늘 안건은 예산과 일정입니다. 먼저 예산부터 보겠습니다.')).toBe(false)
|
||||
expect(isDegenerateTranscript('')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('collapseRepeatedSegments', () => {
|
||||
it('같은 문장의 연속 구간을 하나로 합치고 끝 시각을 늘린다', () => {
|
||||
const segments = [
|
||||
{ text: '시작하겠습니다', start: 0, end: 2 },
|
||||
{ text: '감사합니다', start: 2, end: 4 },
|
||||
{ text: '감사합니다.', start: 4, end: 6 },
|
||||
{ text: '감사합니다', start: 6, end: 8 },
|
||||
{ text: '다음 안건입니다', start: 8, end: 10 },
|
||||
]
|
||||
expect(collapseRepeatedSegments(segments)).toEqual([
|
||||
{ text: '시작하겠습니다', start: 0, end: 2 },
|
||||
{ text: '감사합니다', start: 2, end: 8 },
|
||||
{ text: '다음 안건입니다', start: 8, end: 10 },
|
||||
])
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue