Repository navigation
fix(deepdoc): recover word boundaries for non-Latin scripts; skip OCR fallback the recogniser can't serve - #16958
Conversation
📝 WalkthroughWalkthroughChangesThe 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
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
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
deepdoc/parser/pdf_parser.py (1)
761-767: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace 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
📒 Files selected for processing (7)
deepdoc/parser/pdf_parser.pyinternal/deepdoc/parser/pdf/layout/chars_boxes.gointernal/deepdoc/parser/pdf/layout/chars_boxes_test.gointernal/deepdoc/parser/pdf/parser_ocr.gointernal/deepdoc/parser/pdf/util/garbled.gointernal/deepdoc/parser/pdf/util/garbled_ocr_test.gotest/unit_test/deepdoc/parser/test_pdf_garbled_detection.py
d142b2c to
1fa4374
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
deepdoc/parser/pdf_parser.py (1)
235-235: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSpecify the
strictparameter forzip().As per coding guidelines, the backend code targets Python 3.13+. In Python 3.10 and later, using
zip()without thestrictparameter triggers linter warnings (e.g., Ruff B905). Because the two slices intentionally have unequal lengths (NandN-1), explicitly settingstrict=Falseclarifies 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
📒 Files selected for processing (7)
deepdoc/parser/pdf_parser.pyinternal/deepdoc/parser/pdf/layout/chars_boxes.gointernal/deepdoc/parser/pdf/layout/chars_boxes_test.gointernal/deepdoc/parser/pdf/parser_ocr.gointernal/deepdoc/parser/pdf/util/garbled.gointernal/deepdoc/parser/pdf/util/garbled_ocr_test.gotest/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
| # 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 | ||
|
|
There was a problem hiding this comment.
📐 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.
| # 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
|
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:
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() 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() 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.
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! |
1fa4374 to
7ff1aa9
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
deepdoc/parser/pdf_parser.py (1)
235-237: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePrefer
itertools.pairwiseoverzipwith offset slices.Since the backend targets Python 3.13+, you can use
itertools.pairwiseto iterate over successive pairs. It is more idiomatic and avoids creating an intermediate sliced list.♻️ Proposed fix
If
itertoolsis not already imported, add it at the top of the file:import itertoolsThen 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
📒 Files selected for processing (7)
deepdoc/parser/pdf_parser.pyinternal/deepdoc/parser/pdf/layout/chars_boxes.gointernal/deepdoc/parser/pdf/layout/chars_boxes_test.gointernal/deepdoc/parser/pdf/parser_ocr.gointernal/deepdoc/parser/pdf/util/garbled.gointernal/deepdoc/parser/pdf/util/garbled_ocr_test.gotest/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
|
Thanks for the review @xugangqiang!
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
2026/07/17 13:50:23 WARN scan page OCR detect failed page=0 err="OCR model OOM" @deadtrickster Could you please fix CI failures? Above is one example. Please check if there's other failures. Thank you. |
|
@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]>
7ff1aa9 to
8f60b44
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/deepdoc/parser/pdf/layout/chars_boxes_test.go (1)
107-109: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep 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 valueAdd
strict=Falsetozip()
charsandchars[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
📒 Files selected for processing (7)
deepdoc/parser/pdf_parser.pyinternal/deepdoc/parser/pdf/layout/chars_boxes.gointernal/deepdoc/parser/pdf/layout/chars_boxes_test.gointernal/deepdoc/parser/pdf/parser_ocr.gointernal/deepdoc/parser/pdf/util/garbled.gointernal/deepdoc/parser/pdf/util/garbled_ocr_test.gotest/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
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-250is 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):
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):
This fixes both the Python parser (
deepdoc/parser/pdf_parser.py) and its Go port (internal/deepdoc/parser/pdf/...):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а-яА-Я.)Fix the threshold: insert a space on
gap > 0.25 × mean_char_width. The oldmin(width)/2(~2.5pt) under-inserted even for Latin — real word gaps are 1.6–2.4pt. Validated againstpdftotext's segmentation:min(width)/2(old)0.25 × mean(new)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.
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).