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:
Yun Chan 2026-10-20 22:56:40 +09:00
parent a14bb52b7f
commit 45d8b1ddb1
4 changed files with 236 additions and 6 deletions

View file

@ -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

View file

@ -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()
}