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.
main
lyingbug 2026-10-10 18:36:04 +08:00 committed by GitHub
parent d27ecade65
commit 5f18308b0a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 67 additions and 17 deletions

View File

@ -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: "<p>No text content.</p>", status: "no_text"},
{name: "HTML short no text", raw: "<p>empty</p>", status: "no_text"},
{name: "HTML emphasized no text", raw: "<p><strong>No text content.</strong></p>", status: "no_text"},
{name: "empty HTML", raw: "<html><body></body></html>", 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 {

View File

@ -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. "<html><body><div class="image"><img/></div></body></html>").
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)
}

View File

@ -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", "<html><body><div><img/></div></body></html>", "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```",
"<p>No text content.</p>", "<html><body>No text content.</body></html>",
"<p><strong>No text content.</strong></p>",
"```html\n<p>No text content.</p>\n```", "<p>无文字内容</p>",
"<p>empty</p>", "<p>no text</p>", "<p>No text content&#46;</p>",
} {
if got, err := validateOCRText(input); err != nil || got != "" {
t.Fatalf("explicit no-text answer should succeed without text: %q %v", got, err)
}