Skip to content

fix(deepdoc): recover word boundaries for non-Latin scripts; skip OCR fallback the recogniser can't serve - #16958

Merged
xugangqiang merged 1 commit into
infiniflow:mainfrom
deadtrickster:pr1-deepdoc-word-boundaries
Jul 17, 2026
Merged

xugangqiang merged 1 commit into
infiniflow:mainfrom
deadtrickster:pr1-deepdoc-word-boundaries

Conversation

@deadtrickster

@deadtrickster deadtrickster commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Many PDFs — every TeX-family producer (pdfTeX, LuaTeX, xdvipdfmx) and some others — encode no space glyphs; words are separated by positioning only. (In TeX, interword space is glue, not a character: pdfTeX writes [(Summary)-250(of)-250(Contents)] TJ, where the -250 is the space.) DeepDoc's geometric space-recovery rule was gated on an ASCII-only character class, so non-Latin pages got no spaces and welded into a single token — which then tripped the garbled-text check and fell back to OCR, using a recogniser (ocr.res: 6312 CJK / 52 Latin / 6 Cyrillic) that cannot spell the script.

Repro (freely downloadable file):

import pdfplumber
chars = pdfplumber.open("ed3book.pdf").pages[40].chars
print(sum(1 for c in chars if c["text"] == " "), "/", len(chars))   # -> 0 / 2959

Concrete files, both freely downloadable, both TeX:

Verified end-to-end with the shipped functions on the real char stream pdfplumber extracts from PostgreSQL 18 Internals, page 31 (788 chars, 0 space glyphs):

_insert_word_spaces:
  BEFORE: Каталогbaseсоответствуеттабличномупространствуpg_default,сле-
  AFTER:  Каталог base соответствует табличному пространству pg_default, сле-

_ocr_can_represent (against the real ocr.res, 52 Latin / 6 Cyrillic glyphs):
  Russian line: coverage 27.9% -> False -> keep the text layer
  English line: coverage  100% -> True  -> OCR fallback allowed

This fixes both the Python parser (deepdoc/parser/pdf_parser.py) and its Go port (internal/deepdoc/parser/pdf/...):

  1. Drop the ASCII gate on the gap rule — a gap is a gap regardless of script. (Aside: the Python parser's other space regex, in __ocr, already includes Cyrillic — [0-9a-zA-Zа-яА-Я,.?;:!%]; the Go port carried the character class over but dropped the а-яА-Я.)

  2. Fix the threshold: insert a space on gap > 0.25 × mean_char_width. The old min(width)/2 (~2.5pt) under-inserted even for Latin — real word gaps are 1.6–2.4pt. Validated against pdftotext's segmentation:

    rule Russian (ref 253 words) English (ref 442 words)
    min(width)/2 (old) 150 416
    0.25 × mean (new) 258 440

    The new rule lands within ~2% of ground truth on both scripts (RU +2.0%, EN −0.5%); the old rule recovered only 59% of Russian words.

  3. Guard the OCR fallback: before re-OCRing garbled text, check the recogniser's alphabet actually covers it (_ocr_can_represent / OcrCanRepresent). It covers ~100% of an English page but ~6% of a pure-Cyrillic one, so discarding a usable text layer for OCR only produces garbage — keep the text layer instead. Genuine PUA garbage is still cleared first.

Python and Go kept in parity (both use strict >); tests added on both sides (TestInsertWordSpaces, TestOcrCanRepresent, Go layout + util). Bonus: TeX PDFs with a perfect text layer are no longer needlessly OCR'd (OCR is the dominant per-page cost).

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The PDF parser now checks OCR alphabet coverage before OCR and garbled-text fallback decisions. PDF text assembly also uses character geometry to recover missing spaces across scripts, with new Python and Go tests for coverage, word gaps, and kerning.

OCR text recovery

Layer / File(s) Summary
OCR representability gating
deepdoc/parser/pdf_parser.py, internal/deepdoc/parser/pdf/util/garbled.go, internal/deepdoc/parser/pdf/parser_ocr.go, .../garbled_ocr_test.go, test/unit_test/deepdoc/parser/test_pdf_garbled_detection.py
OCR alphabet coverage is cached and used to gate OCR-related fallback behavior, with tests for supported, unsupported, empty, and threshold cases.
Geometry-based word boundaries
deepdoc/parser/pdf_parser.py, internal/deepdoc/parser/pdf/layout/*, test/unit_test/deepdoc/parser/test_pdf_garbled_detection.py
Missing spaces are inferred from character widths and horizontal gaps rather than ASCII matching, with coverage for Cyrillic boundaries, Latin gaps, CJK adjacency, and intra-word kerning.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PDFParser
  participant GarbledDetection
  participant OCRAlphabet
  PDFParser->>GarbledDetection: evaluate extracted text
  GarbledDetection->>OCRAlphabet: measure character coverage
  OCRAlphabet-->>GarbledDetection: return coverage result
  GarbledDetection-->>PDFParser: preserve text or permit OCR fallback
Loading

Suggested labels: 🌈 python, 🧪 test

Suggested reviewers: xugangqiang

Poem

A rabbit hops through glyphs so bright,
And finds lost spaces left and right.
Cyrillic hops, Latin too,
OCR knows what text can do.
Gaps grow wide—“a space!” we cheer.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: non-Latin word-boundary recovery plus OCR fallback gating.
Description check ✅ Passed The description is detailed and includes background, repro, examples, and the fix rationale required by the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@deadtrickster
deadtrickster marked this pull request as ready for review July 15, 2026 21:15
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 15, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
deepdoc/parser/pdf_parser.py (1)

761-767: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Replace migration-history comments with concise runtime invariants.

  • deepdoc/parser/pdf_parser.py#L761-L767: retain only why positional gaps must recover missing spaces.
  • deepdoc/parser/pdf_parser.py#L1635-L1649: remove old-threshold metrics and historical implementation details.
  • internal/deepdoc/parser/pdf/util/garbled.go#L216-L223: document the configured OCR resource without referencing Python.
  • internal/deepdoc/parser/pdf/util/garbled.go#L242-L249: describe coverage semantics without parallel-path notes.
  • internal/deepdoc/parser/pdf/util/garbled.go#L315-L317: state why unsupported scripts retain usable extracted text.
  • internal/deepdoc/parser/pdf/parser_ocr.go#L276-L279: remove the Python comparison.
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go#L182-L188: document geometry and the strict threshold only.

As per coding guidelines, keep Go comments aligned with the current runtime path and remove stale or dual-track migration notes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/parser/pdf_parser.py` around lines 761 - 767, Rewrite the comments at
deepdoc/parser/pdf_parser.py:761-767 to state only that positional gaps recover
missing spaces; remove old thresholds and implementation history at
deepdoc/parser/pdf_parser.py:1635-1649; update
internal/deepdoc/parser/pdf/util/garbled.go:216-223 to document the configured
OCR resource without Python references, 242-249 to describe coverage semantics
without parallel-path notes, and 315-317 to explain retaining usable extracted
text for unsupported scripts; remove the Python comparison at
internal/deepdoc/parser/pdf/parser_ocr.go:276-279; and at
internal/deepdoc/parser/pdf/layout/chars_boxes.go:182-188 document only the
geometry basis and strict threshold.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@deepdoc/parser/pdf_parser.py`:
- Around line 787-788: Reorder OCR garbling detection so intrinsic garbling is
evaluated before alphabet-coverage gating: in deepdoc/parser/pdf_parser.py lines
787-788, process the garbled_count/total_count fallback before
_ocr_can_represent; in internal/deepdoc/parser/pdf/util/garbled.go lines
315-320, call IsGarbledText before rejecting unsupported scripts; and in
internal/deepdoc/parser/pdf/parser_ocr.go lines 280-286, clear text based on
garbledCnt before applying OcrCanRepresent to secondary heuristics.
- Around line 211-214: Update the OCR alphabet loading exception handler around
cls._OCR_ALPHABET to catch expected I/O and decoding failures, log the ocr.res
resource path and failure details, then preserve the existing fallback of
setting an empty alphabet and returning True for unknown alphabets. Keep
unexpected exceptions from being silently swallowed.

In `@test/unit_test/deepdoc/parser/test_pdf_garbled_detection.py`:
- Around line 524-543: Replace the duplicated algorithm in test helper
`_patched_rule` by extracting the spacing geometry rule into a private
production helper owned by `__img_ocr`, then have `__img_ocr` call that helper.
Update these tests to invoke the production helper directly, preserving the
no-script-gate and mean-width gap behavior while keeping `_old_rule` only for
comparison.
- Around line 479-503: Update the tests that assign _Parser._OCR_ALPHABET,
including test_english_is_representable and the related representability tests,
to restore the prior class-level value after each test. Use pytest monkeypatch
or an autouse fixture so every test is isolated and no synthetic alphabet
remains installed for later tests.

---

Nitpick comments:
In `@deepdoc/parser/pdf_parser.py`:
- Around line 761-767: Rewrite the comments at
deepdoc/parser/pdf_parser.py:761-767 to state only that positional gaps recover
missing spaces; remove old thresholds and implementation history at
deepdoc/parser/pdf_parser.py:1635-1649; update
internal/deepdoc/parser/pdf/util/garbled.go:216-223 to document the configured
OCR resource without Python references, 242-249 to describe coverage semantics
without parallel-path notes, and 315-317 to explain retaining usable extracted
text for unsupported scripts; remove the Python comparison at
internal/deepdoc/parser/pdf/parser_ocr.go:276-279; and at
internal/deepdoc/parser/pdf/layout/chars_boxes.go:182-188 document only the
geometry basis and strict threshold.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ba8b488d-44d0-4539-bcfd-6b6f2e759f13

📥 Commits

Reviewing files that changed from the base of the PR and between df5c8e7 and d142b2c.

📒 Files selected for processing (7)
  • deepdoc/parser/pdf_parser.py
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go
  • internal/deepdoc/parser/pdf/layout/chars_boxes_test.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/util/garbled.go
  • internal/deepdoc/parser/pdf/util/garbled_ocr_test.go
  • test/unit_test/deepdoc/parser/test_pdf_garbled_detection.py

Comment thread deepdoc/parser/pdf_parser.py Resolved
Comment thread deepdoc/parser/pdf_parser.py Resolved
@deadtrickster
deadtrickster force-pushed the pr1-deepdoc-word-boundaries branch from d142b2c to 1fa4374 Compare July 15, 2026 22:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
deepdoc/parser/pdf_parser.py (1)

235-235: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Specify the strict parameter for zip().

As per coding guidelines, the backend code targets Python 3.13+. In Python 3.10 and later, using zip() without the strict parameter triggers linter warnings (e.g., Ruff B905). Because the two slices intentionally have unequal lengths (N and N-1), explicitly setting strict=False clarifies the intent and prevents linting noise.

💡 Proposed fix
-        for cur, nxt in zip(chars, chars[1:]):
+        for cur, nxt in zip(chars, chars[1:], strict=False):
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/parser/pdf_parser.py` at line 235, Update the zip call in the
character-pair iteration to explicitly pass strict=False, preserving the
intentional pairing of chars with its one-element-shorter slice.

Sources: Coding guidelines, Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@deepdoc/parser/pdf_parser.py`:
- Around line 805-809: Add a log entry in the OCR fallback guard around
_ocr_can_represent when an unsupported text alphabet causes the fallback to be
skipped. Include enough context to identify the affected block/page and the skip
reason, matching the logging style used by the adjacent Strategy 1 and Strategy
2 fallback paths.

---

Nitpick comments:
In `@deepdoc/parser/pdf_parser.py`:
- Line 235: Update the zip call in the character-pair iteration to explicitly
pass strict=False, preserving the intentional pairing of chars with its
one-element-shorter slice.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b01d7ee1-2514-442b-a0d7-edaea39fa70b

📥 Commits

Reviewing files that changed from the base of the PR and between d142b2c and 1fa4374.

📒 Files selected for processing (7)
  • deepdoc/parser/pdf_parser.py
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go
  • internal/deepdoc/parser/pdf/layout/chars_boxes_test.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/util/garbled.go
  • internal/deepdoc/parser/pdf/util/garbled_ocr_test.go
  • test/unit_test/deepdoc/parser/test_pdf_garbled_detection.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/deepdoc/parser/pdf/layout/chars_boxes_test.go
  • internal/deepdoc/parser/pdf/util/garbled_ocr_test.go
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go
  • internal/deepdoc/parser/pdf/util/garbled.go

Comment on lines +805 to +809
# Keep a clean text layer the recogniser cannot spell: ocr.res is
# CJK+Latin, so re-OCRing e.g. a Cyrillic page only produces garbage.
if total_count > 0 and not self._ocr_can_represent(b["text"]):
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add logging for the OCR alphabet fallback skip.

As per coding guidelines, "Add logging for new flows." This new guard skips the OCR fallback process for unsupported alphabets but does not log the event, unlike the adjacent Strategy 1 and Strategy 2 blocks which log their respective fallback actions.

💬 Proposed fix
             # Keep a clean text layer the recogniser cannot spell: ocr.res is
             # CJK+Latin, so re-OCRing e.g. a Cyrillic page only produces garbage.
             if total_count > 0 and not self._ocr_can_represent(b["text"]):
+                logging.info(
+                    "Page %d: OCR recogniser cannot represent text, skipping OCR fallback for box at (%.1f, %.1f)",
+                    pagenum,
+                    b["x0"],
+                    b["top"],
+                )
                 continue
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Keep a clean text layer the recogniser cannot spell: ocr.res is
# CJK+Latin, so re-OCRing e.g. a Cyrillic page only produces garbage.
if total_count > 0 and not self._ocr_can_represent(b["text"]):
continue
# Keep a clean text layer the recogniser cannot spell: ocr.res is
# CJK+Latin, so re-OCRing e.g. a Cyrillic page only produces garbage.
if total_count > 0 and not self._ocr_can_represent(b["text"]):
logging.info(
"Page %d: OCR recogniser cannot represent text, skipping OCR fallback for box at (%.1f, %.1f)",
pagenum,
b["x0"],
b["top"],
)
continue
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/parser/pdf_parser.py` around lines 805 - 809, Add a log entry in the
OCR fallback guard around _ocr_can_represent when an unsupported text alphabet
causes the fallback to be skipped. Include enough context to identify the
affected block/page and the skip reason, matching the logging style used by the
adjacent Strategy 1 and Strategy 2 fallback paths.

Source: Coding guidelines

@yingfeng
yingfeng requested a review from xugangqiang July 16, 2026 01:31
@yingfeng yingfeng added the ci Continue Integration label Jul 16, 2026
@yingfeng
yingfeng marked this pull request as draft July 16, 2026 01:31
@yingfeng
yingfeng marked this pull request as ready for review July 16, 2026 01:31
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 16, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

Hi @deadtrickster, thanks for this fix — the root cause analysis is spot on. The ASCII-only regex gating word-boundary recovery was clearly wrong for non-Latin scripts, and skipping OCR for scripts the recogniser can't spell is the right call. The overall approach looks solid.

I had two small suggestions:

  1. ocr.res path resolution in Go

The Python side uses get_project_base_directory() to locate ocr.res, which handles different deployment layouts. The Go side currently uses os.Getwd():

cwd, err := os.Getwd()
data, err := os.ReadFile(filepath.Join(cwd, "rag", "res", "deepdoc", "ocr.res"))

This assumes the working directory is the project root, which may not hold in containerised deployments or when the binary is launched from elsewhere. The repo already has utility.GetProjectRoot() (internal/utility/path.go) that resolves the project root via env vars → go.mod walking → executable path — would you mind switching to that instead? Something like:

root := utility.GetProjectRoot()
data, err := os.ReadFile(filepath.Join(root, "rag", "res", "deepdoc", "ocr.res"))

The graceful fallback (treating alphabet as unknown on error) is already in place, so a missing file won't crash — this is just about making the happy path work in more environments.

  1. Testing evidence

Would it be possible to attach a before/after comparison showing the fix in action? Even a simple screenshot or console snippet — e.g., a Cyrillic PDF page where the old code produced welded-together text (Окнигекак-тоиначе) vs. the new code producing properly spaced text (О книге как-то иначе), and similarly for the OCR-fallback guard. It'd help reviewers confirm the fix addresses the reported issue end-to-end.

Thanks again for tackling this!

@deadtrickster
deadtrickster force-pushed the pr1-deepdoc-word-boundaries branch from 1fa4374 to 7ff1aa9 Compare July 16, 2026 09:25

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
deepdoc/parser/pdf_parser.py (1)

235-237: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer itertools.pairwise over zip with offset slices.

Since the backend targets Python 3.13+, you can use itertools.pairwise to iterate over successive pairs. It is more idiomatic and avoids creating an intermediate sliced list.

♻️ Proposed fix

If itertools is not already imported, add it at the top of the file:

import itertools

Then update the loop:

-        for cur, nxt in zip(chars, chars[1:]):
+        for cur, nxt in itertools.pairwise(chars):
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/parser/pdf_parser.py` around lines 235 - 237, Update the
character-pair iteration in the surrounding parser method to use
itertools.pairwise(chars) instead of zip(chars, chars[1:]); add the itertools
import if needed, and preserve the existing spacing condition and text mutation
unchanged.

Sources: Coding guidelines, Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@deepdoc/parser/pdf_parser.py`:
- Around line 235-237: Update the character-pair iteration in the surrounding
parser method to use itertools.pairwise(chars) instead of zip(chars, chars[1:]);
add the itertools import if needed, and preserve the existing spacing condition
and text mutation unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3958fb3f-882e-412b-a38e-d6591b437323

📥 Commits

Reviewing files that changed from the base of the PR and between 1fa4374 and 7ff1aa9.

📒 Files selected for processing (7)
  • deepdoc/parser/pdf_parser.py
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go
  • internal/deepdoc/parser/pdf/layout/chars_boxes_test.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/util/garbled.go
  • internal/deepdoc/parser/pdf/util/garbled_ocr_test.go
  • test/unit_test/deepdoc/parser/test_pdf_garbled_detection.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/deepdoc/parser/pdf/layout/chars_boxes_test.go
  • internal/deepdoc/parser/pdf/util/garbled_ocr_test.go
  • internal/deepdoc/parser/pdf/util/garbled.go
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go
  • internal/deepdoc/parser/pdf/parser_ocr.go

@deadtrickster

Copy link
Copy Markdown
Contributor Author

Thanks for the review @xugangqiang!

  1. Refactored the Go ocr.res lookup to utility.GetProjectRoot() as suggested (instead of os.Getwd()).
  2. Added the concrete Cyrillic book to the description: PostgreSQL 18 Internals (Rogov), https://edu.postgrespro.ru/postgresql_internals-18.pdf. It's typeset with LuaTeX and carries no space glyphs, so it's a clean reproduction of the bug. Below is a before/after from running the shipped functions on its real extracted char stream (page 31: 788 chars, 0 space glyphs):
_insert_word_spaces:
  BEFORE: Каталогbaseсоответствуеттабличномупространствуpg_default,сле-
  AFTER:  Каталог base соответствует табличному пространству pg_default, сле-

_ocr_can_represent (real ocr.res):
  Russian line -> False -> keep the text layer
  English line -> True  -> OCR fallback allowed

@codecov

codecov Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (5cf95d2) to head (8f60b44).
⚠️ Report is 90 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16958      +/-   ##
==========================================
- Coverage   94.56%   90.65%   -3.91%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      650      -28     
- Misses         25       39      +14     
- Partials       14       28      +14     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@xugangqiang

Copy link
Copy Markdown
Contributor

2026/07/17 13:50:23 WARN scan page OCR detect failed page=0 err="OCR model OOM"
--- FAIL: TestOCRMergeChars_OverlappingBoxes (0.00s)
parser_ocr_test.go:337: box B: expected '乙丙', got "乙 丙"
FAIL

@deadtrickster Could you please fix CI failures? Above is one example. Please check if there's other failures. Thank you.

@deadtrickster

Copy link
Copy Markdown
Contributor Author

@xugangqiang thanks for the ping. OOM message is interesting. Looking.

… fallback the recogniser can't serve

Many PDFs -- all TeX-family output (pdfTeX, LuaTeX, xdvipdfmx) and some others --
encode no space glyphs; words are separated by positioning alone, so the
extracted text welds into a single token. The geometric space-recovery rule was
gated on an ASCII-only character class, so non-Latin pages got no spaces at all
and then tripped the garbled-text check, falling back to an OCR recogniser
(ocr.res: 52 Latin, 6 Cyrillic glyphs) that cannot spell the script.

- Recover spaces from geometry for space-separated scripts: insert a space when
  the gap to the next char exceeds 0.25 * mean char width (_insert_word_spaces /
  chars_boxes.go). The old min(width)/2 threshold under-inserted even for Latin.
  CJK is excluded -- it does not write inter-word spaces, so a gap between CJK
  glyphs is ordinary tracking, not a boundary (the ASCII gate had masked this).
- Skip the OCR garbled-text fallback for a script the recogniser cannot spell
  (_ocr_can_represent / util.OcrCanRepresent): keep a usable text layer rather
  than discard it for OCR that can only produce garbage. Genuine PUA garbage is
  still cleared first.

Python and Go kept in parity. Tests added on both sides, including CJK guards.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@deadtrickster
deadtrickster force-pushed the pr1-deepdoc-word-boundaries branch from 7ff1aa9 to 8f60b44 Compare July 17, 2026 16:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
internal/deepdoc/parser/pdf/layout/chars_boxes_test.go (1)

107-109: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep comments focused on current behavior, not migration history.

Replace the “Before the fix” explanation with the invariant being tested: Cyrillic gaps use the same geometry-based boundary rule as other space-separated scripts. As per coding guidelines, Go comments should align with the current runtime path rather than migration history.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/deepdoc/parser/pdf/layout/chars_boxes_test.go` around lines 107 -
109, Update the comment near the word-boundary test to remove the “Before the
fix” migration history and describe the current invariant: Cyrillic gaps use the
same geometry-based boundary rule as other space-separated scripts. Keep the
comment focused on present runtime behavior.

Source: Coding guidelines

deepdoc/parser/pdf_parser.py (1)

241-241: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add strict=False to zip()

chars and chars[1:] are intentionally different lengths; making that explicit keeps the intent clear.

♻️ Proposed fix
-        for cur, nxt in zip(chars, chars[1:]):
+        for cur, nxt in zip(chars, chars[1:], strict=False):
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/parser/pdf_parser.py` at line 241, Update the zip call in the
character-pairing loop to pass strict=False explicitly, preserving the existing
iteration over chars and chars[1:] while documenting that their unequal lengths
are intentional.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@deepdoc/parser/pdf_parser.py`:
- Line 241: Update the zip call in the character-pairing loop to pass
strict=False explicitly, preserving the existing iteration over chars and
chars[1:] while documenting that their unequal lengths are intentional.

In `@internal/deepdoc/parser/pdf/layout/chars_boxes_test.go`:
- Around line 107-109: Update the comment near the word-boundary test to remove
the “Before the fix” migration history and describe the current invariant:
Cyrillic gaps use the same geometry-based boundary rule as other space-separated
scripts. Keep the comment focused on present runtime behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 32379f2a-aee0-44bf-9dae-7a83e7252d0a

📥 Commits

Reviewing files that changed from the base of the PR and between 7ff1aa9 and 8f60b44.

📒 Files selected for processing (7)
  • deepdoc/parser/pdf_parser.py
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go
  • internal/deepdoc/parser/pdf/layout/chars_boxes_test.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/util/garbled.go
  • internal/deepdoc/parser/pdf/util/garbled_ocr_test.go
  • test/unit_test/deepdoc/parser/test_pdf_garbled_detection.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/deepdoc/parser/pdf/util/garbled_ocr_test.go
  • internal/deepdoc/parser/pdf/layout/chars_boxes.go
  • internal/deepdoc/parser/pdf/util/garbled.go
  • internal/deepdoc/parser/pdf/parser_ocr.go

@xugangqiang xugangqiang self-assigned this Jul 17, 2026
@xugangqiang
xugangqiang merged commit 982b9c7 into infiniflow:main Jul 17, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants