From 5f18308b0a39bd44f3b44203c167663d0430a40b Mon Sep 17 00:00:00 2001 From: lyingbug Date: Sat, 10 Oct 2026 18:36:04 +0800 Subject: [PATCH] fix(ocr): reject split repetition and preserve no-text responses (#4135) Count distinct coverage across long repetitive runs and preserve HTML-wrapped no-text replies through normalization. Add sanitizer and image-persistence regressions for both cases. --- .../service/image_ocr_validation_test.go | 11 ++++ internal/application/service/ocr_sanitizer.go | 54 +++++++++++++------ .../application/service/ocr_sanitizer_test.go | 19 ++++++- 3 files changed, 67 insertions(+), 17 deletions(-) diff --git a/internal/application/service/image_ocr_validation_test.go b/internal/application/service/image_ocr_validation_test.go index be688fb8..dfa2e125 100644 --- a/internal/application/service/image_ocr_validation_test.go +++ b/internal/application/service/image_ocr_validation_test.go @@ -41,6 +41,10 @@ func TestImageOCRRejectsInvalidContentBeforePersistence(t *testing.T) { }{ {name: "recorded empty cells", raw: strings.Repeat("| ", 2500), status: "failed", code: "OCR_INVALID_OUTPUT"}, {name: "repeated words", raw: strings.Repeat("传球按钮 ", 200), status: "failed", code: "OCR_INVALID_OUTPUT"}, + { + name: "split delimiter loops", raw: strings.Repeat("| ", 1250) + "传球\n" + strings.Repeat("| ", 1250), + status: "failed", code: "OCR_INVALID_OUTPUT", + }, {name: "empty model output", status: "failed", code: "OCR_INVALID_OUTPUT"}, { name: "truncated output", status: "failed", code: "OCR_TRUNCATED", @@ -48,6 +52,10 @@ func TestImageOCRRejectsInvalidContentBeforePersistence(t *testing.T) { }, {name: "request failure", status: "failed", code: "OCR_REQUEST_FAILED", err: errors.New("model unavailable")}, {name: "no text", raw: "No text content.", status: "no_text"}, + {name: "HTML no text", raw: "

No text content.

", status: "no_text"}, + {name: "HTML short no text", raw: "

empty

", status: "no_text"}, + {name: "HTML emphasized no text", raw: "

No text content.

", status: "no_text"}, + {name: "empty HTML", raw: "", status: "failed", code: "OCR_INVALID_OUTPUT"}, } { for _, caption := range []bool{false, true} { t.Run(fmt.Sprintf("%s/caption=%v", tc.name, caption), func(t *testing.T) { @@ -80,7 +88,10 @@ func TestImageOCRRejectsInvalidContentBeforePersistence(t *testing.T) { require.Equal(t, "failed", out["outcome"]) } } else { + require.Empty(t, tracker.failed) require.NotContains(t, out, "ocr_error") + require.NotContains(t, out, "ocr_error_code") + require.NotContains(t, out, "outcome") require.Equal(t, "no_text", tracker.outputs["multimodal.image[0].ocr"]["status"]) } if caption { diff --git a/internal/application/service/ocr_sanitizer.go b/internal/application/service/ocr_sanitizer.go index ab0ad72d..61ac4986 100644 --- a/internal/application/service/ocr_sanitizer.go +++ b/internal/application/service/ocr_sanitizer.go @@ -42,10 +42,10 @@ func (e *ocrValidationError) Error() string { return fmt.Sprintf("invalid OCR ou // output. Reject the entire response, rather than indexing a plausible prefix // followed by hallucinated repetition. func validateOCRText(raw string) (string, error) { - if isKnownEmptyReply(stripMarkdownCodeBlock(strings.TrimSpace(raw))) { + text := normalizeOCRText(raw) + if isKnownEmptyReply(text) { return "", nil } - text := normalizeOCRText(raw) if text == "" { return "", &ocrValidationError{reason: "empty_content"} } @@ -66,26 +66,45 @@ func validateOCRText(raw string) (string, error) { return text, nil } -// Require a long, dominant periodic run to avoid rejecting ordinary repeated -// labels, table separators, or short numeric values. Normalize whitespace so -// line wrapping does not hide a decoding loop. Work is bounded by 64*n. +// Count the union of long periodic runs, including runs with different periods +// separated by readable text. Short repetitions (labels, table separators, +// numeric values) do not contribute. Normalize whitespace so line wrapping +// cannot hide a decoding loop. Work is bounded by 64*n, with O(n) storage. func hasOCRRepetition(text string) bool { runes := []rune(strings.Join(strings.Fields(text), " ")) + if len(runes) < 512 { + return false + } + // Range deltas avoid counting the same characters multiple times when a + // run matches several periods, and keep interval recording constant-time. + coverage := make([]int, len(runes)+1) for period := 1; period <= 64 && period <= len(runes)/32; period++ { matched := 0 + recordRun := func(end int) { + span := matched + period + if span >= 512 && span >= period*32 { + coverage[end-span]++ + coverage[end]-- + } + } for i := period; i < len(runes); i++ { if runes[i] == runes[i-period] { matched++ } else { + recordRun(i) matched = 0 } - span := matched + period - if span >= 512 && span >= period*32 && span*5 >= len(runes)*4 { - return true - } + } + recordRun(len(runes)) + } + active, repeated := 0, 0 + for i := range runes { + active += coverage[i] + if active > 0 { + repeated++ } } - return false + return repeated*5 >= len(runes)*4 } func normalizeOCRText(raw string) string { @@ -99,8 +118,15 @@ func normalizeOCRText(raw string) string { // If stripping HTML tags leaves almost no text, the response is useless // (e.g. "
"). plainText := strings.TrimSpace(htmlTagPattern.ReplaceAllString(text, "")) - if len(plainText) < 10 && htmlTagPattern.MatchString(text) { - return "" + if htmlTagPattern.MatchString(text) { + // Preserve no-text answers before a short response is discarded or + // inline tags become Markdown emphasis around the sentinel. + if isKnownEmptyReply(plainText) { + return plainText + } + if len(plainText) < 10 { + return "" + } } if looksLikeHTML(text) { @@ -118,10 +144,6 @@ func normalizeOCRText(raw string) string { // raw markup in place makes the chunker split inside table rows. text = docparser.NormalizeHTMLTables(text) - if isKnownEmptyReply(text) { - return "" - } - text = multipleNewlines.ReplaceAllString(text, "\n\n") return strings.TrimSpace(text) } diff --git a/internal/application/service/ocr_sanitizer_test.go b/internal/application/service/ocr_sanitizer_test.go index 9c858e06..bff2acbf 100644 --- a/internal/application/service/ocr_sanitizer_test.go +++ b/internal/application/service/ocr_sanitizer_test.go @@ -266,7 +266,16 @@ func TestValidateOCRTextRejectsDegenerateOutput(t *testing.T) { {"markdown skeleton", "| --- | --- |\n| | |", "no_readable_content"}, {"repeated phrase", strings.Repeat("传球按钮 ", 200), "repetitive_content"}, {"repeated suffix after real text", "传球\n" + strings.Repeat("| ", 2500), "repetitive_content"}, + { + "split delimiter loops", strings.Repeat("| ", 1250) + "传球\n" + strings.Repeat("| ", 1250), + "repetitive_content", + }, + { + "different repeated periods", strings.Repeat("| ", 600) + "传球\n" + strings.Repeat("取消施法 ", 240), + "repetitive_content", + }, {"repeated wrapped lines", strings.Repeat("开始\n锁定目标\n", 100), "repetitive_content"}, + {"empty HTML skeleton", "
", "empty_content"}, } { t.Run(tt.name, func(t *testing.T) { text, err := validateOCRText(tt.input) @@ -290,13 +299,21 @@ func TestValidateOCRTextPreservesRealContent(t *testing.T) { for _, input := range []string{ "A", "3", "传球", "A\nB\nL1\nL2\n传球\n传球", "0:0\n58.29\n取消施法", "±", "$x^2 + y^2 = z^2$", table.String(), strings.Repeat("同一个按钮\n", 5), + // A run matches many periods; its overlapping ranges must count once. + table.String() + strings.Repeat("X", 600), } { got, err := validateOCRText(input) if err != nil || got != strings.TrimSpace(input) { t.Fatalf("valid OCR rejected or changed: input=%q got=%q err=%v", input, got, err) } } - for _, input := range []string{"No text content.", "无文字内容", "```\nNo text content.\n```"} { + for _, input := range []string{ + "No text content.", "无文字内容", "```\nNo text content.\n```", + "

No text content.

", "No text content.", + "

No text content.

", + "```html\n

No text content.

\n```", "

无文字内容

", + "

empty

", "

no text

", "

No text content.

", + } { if got, err := validateOCRText(input); err != nil || got != "" { t.Fatalf("explicit no-text answer should succeed without text: %q %v", got, err) }