Repository navigation
fix(pdf/layout): recover title-bridged & gutter-less double columns (2D rescue + L3) - #18150
Conversation
Extend AssignColumn with two complementary detectors that run only after the gap detector and the balance gate both fail, so already-correct pages are never touched: - detectColumnCount2D: recovers title-bridged double columns. It drops full-width front matter (dropFullWidth) and in-body bridging headings/captions (dropWide at bridgingFrac), then scans the glyph-density x-projection for a single clean interior valley (k=2). This recovers the double-column pages the 1D balance gate correctly rejects because the minority column is too sparse (< 30% of body lines). - detectColumnCountMedian: the L3 signal inspired by PR infiniflow#10475 (page_w / median_line_width). Targets gutter-less doubles/triples whose x-projection has no clean ink dip, yet each line is only ~page_w/N wide (raw_cols >= 2). Guarded by raw_cols <= maxColumnCount (skip table cells) and a near-full-width line requirement (skip uniformly short lines). Measured on the 70-page labeled corpus: 78.6% -> 82.9% accuracy. The 2D rescue trades 5 more false-splits (5 -> 10) for 8 fewer misses (10 -> 2); the remaining false-splits are the pure-table column edge case tracked separately in infiniflow#18079 (table guard). See infiniflow#18079.
- Un-skip TestSyntheticTitleBridgedDouble and fix its geometry to model a real title-bridged double (clean gutter at 240-260, non-overlapping x0, 12-line right column above valleyFrac peak ink). Now recovered by detectColumnCount2D. - Add TestSyntheticMedianWidthDouble for the gutter-less double that only the median-width ratio recovers. Both run in the default unit tier (no manual build tag). See infiniflow#18079.
📝 WalkthroughWalkthroughChangesPDF column detection
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant LayoutDetector
participant ProjectionPreparation
participant GutterRescue
participant MedianWidthDetector
participant ColumnPruning
LayoutDetector->>ProjectionPreparation: filter boxes and calculate robust extents
ProjectionPreparation->>GutterRescue: provide page projection inputs
GutterRescue->>ColumnPruning: validate 2D valley columns
ColumnPruning-->>LayoutDetector: return split or continue
LayoutDetector->>MedianWidthDetector: analyze normalized line widths
MedianWidthDetector->>ColumnPruning: prune sparse columns
ColumnPruning-->>LayoutDetector: return accepted column count
Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 2
🧹 Nitpick comments (6)
internal/deepdoc/parser/pdf/layout/combined_column.go (5)
541-541: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueName the full-width threshold.
0.8is a bare literal here, whiledropFullWidthuses0.9for the same concept. Two different unnamed full-width thresholds in one file are easy to misread. Declare a named constant next tobridgingFracand state why the median path uses a lower value.🤖 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/combined_column.go` at line 541, Replace the bare 0.8 multiplier in the combined-column layout path with a named full-width threshold constant declared alongside bridgingFrac, and use that constant when computing fwThr. Document that the median path intentionally uses a lower threshold than dropFullWidth’s 0.9 value.
416-436: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueThe split metric and the prune metric use different x values.
Lines 420-428 assign a line to left or right by its center
(X0+X1)/2compared tovalleyC.pruneColumnsthen re-assigns the same lines by nearestX0to the centroids (Line 176-182). For lines whose center andX0fall on opposite sides, the two counts differ. The prune gate can therefore reject a column that the valley split accepted. Consider assigning by the same value in both places.🤖 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/combined_column.go` around lines 416 - 436, Align the split metric in the body partition before pruneColumns with pruneColumns’ X0-based assignment: classify each block using b.X0 relative to valleyC, then compute centroids from those same X0 values. Preserve the existing empty-side guard and pruneColumns flow.
352-364: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConfirm the intended glyph weighting.
Each bin covered by a line receives the full rune count
w. A wide line therefore contributeswto every bin it covers, so its total contribution scales with its width. The doc comment calls this "glyph-density weighting", which usually means glyphs per unit width (w / (i1-i0+1)). If the current form is the tuned behavior, update the comment to say "glyph-count weighting per bin" so the code and the comment agree.🤖 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/combined_column.go` around lines 352 - 364, Resolve the mismatch between the projection logic near nb, proj, and the surrounding doc comment: either distribute each line’s rune count across its covered bins for glyph-density weighting, or, if the current full-w-per-bin behavior is intentional, revise the comment to describe glyph-count weighting per bin. Preserve the intended tuned behavior and ensure the documentation matches the implementation.
439-459: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
dropWideduplicatesdropFullWidth.
dropFullWidth(Line 631) keeps lines narrower than0.9*widthand returnsnilwhen nothing remains.dropWideperforms the same operation with a configurable fraction. ExpressdropFullWidthin terms ofdropWideto keep one implementation path.The repository guideline states: "In actively refactored Go ingestion, parser, and DeepDOC code, collapse duplicate paths rather than preserving transitional wrappers."
♻️ Proposed consolidation
func dropFullWidth(lines []pdf.TextBox, width float64) []pdf.TextBox { - fwThr := 0.9 * width - out := make([]pdf.TextBox, 0, len(lines)) - for _, b := range lines { - if b.X1-b.X0 < fwThr { - out = append(out, b) - } - } - if len(out) == 0 { - // Every line is full-width: there is no narrow body to form a second - // column. Return nil (not the original lines) so the caller's - // len(body) < 4 guard treats the page as a single column instead of - // pushing the whole page through the balance gate, which could - // mis-split a full-width single column whose x0 happens to be bimodal. - return nil - } - return out + // Every line full-width => dropWide returns nil, so the caller's + // len(body) < 4 guard treats the page as a single column. + return dropWide(lines, width, fullWidthFrac) }Add
const fullWidthFrac = 0.9next to the other detection constants.🤖 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/combined_column.go` around lines 439 - 459, Consolidate the duplicate filtering logic by adding the proposed full-width fraction constant alongside the detection constants and updating dropFullWidth to delegate to dropWide with that constant and the existing width argument. Preserve dropFullWidth’s current narrower-than-threshold and nil-on-empty behavior while leaving dropWide as the shared implementation.Source: Coding guidelines
78-87: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename the shadowing parameters in
gapColumnCount.
combined_column_test.goalso callsgapColumnCountwith explicit values, so do not remove the parameters. RenamegapMinFracandbinPtparameters to avoid shadowing the package-level constants.🤖 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/combined_column.go` around lines 78 - 87, Rename the gapMinFrac and binPt parameters in gapColumnCount to distinct names so they no longer shadow the package-level constants, while retaining the parameters and updating their references and existing callers as needed.Source: Coding guidelines
internal/deepdoc/parser/pdf/layout/combined_column_synthetic_test.go (1)
152-160: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd a full-width line to the median-width fixture.
Every box in this fixture is 200 wide, so no line reaches the
0.8*widthfull-width threshold indetectColumnCountMedian. The test therefore never exercises the path where full-width lines are excluded from bucketing but still counted bypruneColumns. Add a full-width title row to cover that path.🧪 Proposed additional coverage
func TestSyntheticMedianWidthDouble(t *testing.T) { boxes := concat( stackedColumn(50, 250, 30, 10, 10), // left body column [50,250] stackedColumn(250, 450, 12, 10, 20), // right body column [250,450]: adjacent, no gutter ) if got := columnCount(boxes); got != 2 { t.Errorf("median-width gutter-less double: got %d, want 2", got) } } + +// Same gutter-less double, preceded by a full-width title block. The title +// must not affect the median-width column assignment. +func TestSyntheticMedianWidthDoubleWithTitle(t *testing.T) { + boxes := concat( + stackedColumn(50, 450, 3, 0, 10), // full-width title + concat( + stackedColumn(50, 250, 30, 40, 10), + stackedColumn(250, 450, 12, 40, 20), + ), + ) + if got := columnCount(boxes); got != 2 { + t.Errorf("median-width double with title: got %d, want 2", got) + } +}🤖 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/combined_column_synthetic_test.go` around lines 152 - 160, Update TestSyntheticMedianWidthDouble to include a full-width title-row box spanning the combined fixture width, while preserving the existing two adjacent stacked columns. Ensure the added row exercises exclusion from median-width bucketing and inclusion in pruneColumns, and keep the expected column count at 2.
🤖 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 `@internal/deepdoc/parser/pdf/layout/combined_column_synthetic_test.go`:
- Around line 90-123: Remove the obsolete TODO above the fixture and the
historical note describing the earlier overlapping-column geometry; keep the
current fixture rationale and active test documentation unchanged.
In `@internal/deepdoc/parser/pdf/layout/combined_column.go`:
- Around line 540-581: Update the bucketing flow and the pruneColumns call so
pruning uses the same non-full-width line set that produced buckets, excluding
lines with width at least 0.8*width. Preserve the existing centroid calculation
and fallback behavior while ensuring full-width lines are not included in column
counts.
---
Nitpick comments:
In `@internal/deepdoc/parser/pdf/layout/combined_column_synthetic_test.go`:
- Around line 152-160: Update TestSyntheticMedianWidthDouble to include a
full-width title-row box spanning the combined fixture width, while preserving
the existing two adjacent stacked columns. Ensure the added row exercises
exclusion from median-width bucketing and inclusion in pruneColumns, and keep
the expected column count at 2.
In `@internal/deepdoc/parser/pdf/layout/combined_column.go`:
- Line 541: Replace the bare 0.8 multiplier in the combined-column layout path
with a named full-width threshold constant declared alongside bridgingFrac, and
use that constant when computing fwThr. Document that the median path
intentionally uses a lower threshold than dropFullWidth’s 0.9 value.
- Around line 416-436: Align the split metric in the body partition before
pruneColumns with pruneColumns’ X0-based assignment: classify each block using
b.X0 relative to valleyC, then compute centroids from those same X0 values.
Preserve the existing empty-side guard and pruneColumns flow.
- Around line 352-364: Resolve the mismatch between the projection logic near
nb, proj, and the surrounding doc comment: either distribute each line’s rune
count across its covered bins for glyph-density weighting, or, if the current
full-w-per-bin behavior is intentional, revise the comment to describe
glyph-count weighting per bin. Preserve the intended tuned behavior and ensure
the documentation matches the implementation.
- Around line 439-459: Consolidate the duplicate filtering logic by adding the
proposed full-width fraction constant alongside the detection constants and
updating dropFullWidth to delegate to dropWide with that constant and the
existing width argument. Preserve dropFullWidth’s current
narrower-than-threshold and nil-on-empty behavior while leaving dropWide as the
shared implementation.
- Around line 78-87: Rename the gapMinFrac and binPt parameters in
gapColumnCount to distinct names so they no longer shadow the package-level
constants, while retaining the parameters and updating their references and
existing callers as needed.
🪄 Autofix
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 Plus
Run ID: 20d5fe75-7c20-4eeb-b284-283703f2dbaa
📒 Files selected for processing (2)
internal/deepdoc/parser/pdf/layout/combined_column.gointernal/deepdoc/parser/pdf/layout/combined_column_synthetic_test.go
…rojection Stack on infiniflow#18150 (2D+L3). Add two robustness guards to the column detectors (Borrow A from pdf-inspector), implemented additively without touching the shared pageExtent helper so the balance/median gates keep their current behavior: A1 textProjectionLines: exclude LayoutType figure/equation boxes from BOTH the gap projection (gapColumnCount) and the 2D rescue projection (detectColumnCount2D). A figure spanning the gutter would otherwise fill the gap/valley and mask a real column boundary. A2 robustPageExtent: drop malformed/outlier lines (width > maxPageExtent=14400 or minority clusters separated by a full-page gap) before computing the page extent, and cap the histogram bin count (maxBins=65536) so a single bad box cannot balloon the allocation or collapse multi-column detection. Normal pages are unchanged (verified: labeled-corpus ACC stays 81.4% on the 2D+L3 base). Adds 6 synthetic unit tests covering both guards, the 2D projection path, and the no-over-trim case. Co-Authored-by: CodeBuddy <[email protected]>
…une + 2D split) Apply the 5 review fixes for the combined column detector on top of infiniflow#18150 (2D valley rescue + L3 median-width). All are behavior-preserving on the labeled corpus (ACC stays 81.4%, false-split=11, miss=2, n=70). 1. (Major) detectColumnCountMedian must prune on the SAME non-full-width lines that produced the centroids. Previously it collected centroids from lines narrower than 0.8*width but then called pruneColumns(lines, cents), which re-counted full-width titles/abstracts into one column and let a real multi-column page collapse to 1. Now collect the narrow lines into body and call pruneColumns(body, cents), matching the discipline already used by balancedBodyK2 and detectColumnCount2D. Regression test: TestSyntheticMedianWidthDoubleWithTitle (got 1 -> 2). 2. Remove the stale TODO infiniflow#18079 and historical NOTE paragraph from TestSyntheticTitleBridgedDouble; the 2D detector now covers this shape. 3. Replace the bare 0.8*width literal with a named medianFullWidthFrac = 0.80 constant and document why it differs from dropFullWidth's 0.9. 4. Align the 2D valley split metric to X0 (b.X0 < valleyC) instead of the center, so the split agrees with pruneColumns' X0-based assignment. 5. Correct the doc comment: the projection uses glyph-count-per-bin weighting (each covered bin gets the line's full rune count), not 'glyph-density'. Co-Authored-by: CodeBuddy <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@internal/deepdoc/parser/pdf/layout/combined_column.go`:
- Around line 276-280: Update the layout parsing flow around textProjectionLines
so n is recomputed from the filtered lines before the threshold calculation at
line 315 uses it. Add a regression case covering one text column with enough
figure boxes to exceed crossTol, preserving it as a single column.
- Around line 816-825: Update the selected-cluster extent calculation around
clusters[best] so lo uses the retained boxes’ X0 values while hi is derived from
their X1 values, returning the full horizontal box extent rather than the X0
range. Add a regression test covering a distant plausible-width box removed by
clusteredExtent and verifying the retained cluster’s width.
🪄 Autofix
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 Plus
Run ID: 3dd1109a-28ed-4f47-8afb-2ee13d795b3f
📒 Files selected for processing (3)
internal/deepdoc/parser/pdf/layout/combined_column.gointernal/deepdoc/parser/pdf/layout/combined_column_defensive_test.gointernal/deepdoc/parser/pdf/layout/combined_column_synthetic_test.go
| // A1: image/equation placeholders must not feed the projection — a figure | ||
| // spanning the gutter would otherwise fill the gap and mask a real column | ||
| // boundary. | ||
| lines = textProjectionLines(lines) | ||
| if len(lines) == 0 { |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Compute the coverage threshold from filtered lines.
n is captured before textProjectionLines removes figure and equation boxes. Line 315 then uses that stale count for thr.
A page with many excluded boxes can mark every text bin as below threshold. The gap path can then false-split a single-column page.
Set n = len(lines) after filtering. Add a regression case with one text column and enough figure boxes to exceed crossTol.
Proposed fix
lines = textProjectionLines(lines)
if len(lines) == 0 {
return 1
}
+ n = len(lines)📝 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.
| // A1: image/equation placeholders must not feed the projection — a figure | |
| // spanning the gutter would otherwise fill the gap and mask a real column | |
| // boundary. | |
| lines = textProjectionLines(lines) | |
| if len(lines) == 0 { | |
| // A1: image/equation placeholders must not feed the projection — a figure | |
| // spanning the gutter would otherwise fill the gap and mask a real column | |
| // boundary. | |
| lines = textProjectionLines(lines) | |
| if len(lines) == 0 { | |
| return 1 | |
| } | |
| n = len(lines) |
🤖 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/combined_column.go` around lines 276 -
280, Update the layout parsing flow around textProjectionLines so n is
recomputed from the filtered lines before the threshold calculation at line 315
uses it. Add a regression case covering one text column with enough figure boxes
to exceed crossTol, preserving it as a single column.
| lo, hi := clusters[best][0], clusters[best][0] | ||
| for _, x := range clusters[best] { | ||
| if x < lo { | ||
| lo = x | ||
| } | ||
| if x > hi { | ||
| hi = x | ||
| } | ||
| } | ||
| return lo, hi - lo |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Return the selected cluster's full box extent.
Line 825 calculates width from the selected boxes' X0 values only. If a distant minority box is removed by clusteredExtent, retained boxes at X0=100 and X0=400 with X1=600 produce width 300, not the required width 500.
This underreports the extent used by the gap and 2D detectors. It can also return zero width when all retained lines share one X0.
Calculate hi from X1 for boxes in the selected cluster. Add a test with a plausible-width distant box that is removed by clustering.
Proposed fix
- lo, hi := clusters[best][0], clusters[best][0]
- for _, x := range clusters[best] {
- if x < lo {
- lo = x
- }
- if x > hi {
- hi = x
- }
+ selected := clusters[best]
+ lo, hi := selected[0], selected[0]
+ for _, b := range lines {
+ if b.X0 < selected[0] || b.X0 > selected[len(selected)-1] {
+ continue
+ }
+ if b.X1 > hi {
+ hi = b.X1
+ }
}
return lo, hi - lo🤖 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/combined_column.go` around lines 816 -
825, Update the selected-cluster extent calculation around clusters[best] so lo
uses the retained boxes’ X0 values while hi is derived from their X1 values,
returning the full horizontal box extent rather than the X0 range. Add a
regression test covering a distant plausible-width box removed by
clusteredExtent and verifying the retained cluster’s width.
Summary
Incremental follow-up to #18023 (gap + balance-gate hybrid). Adds two complementary column detectors to
AssignColumnthat run only after the gap detector and the balance gate both fail, so already-correct pages are never touched.detectColumnCount2D): recovers title-bridged double columns. The 1D x0 balance gate correctly rejects these because the minority column is too sparse (< 30% of body lines) and the full-width heading/caption bridges the gutter in projection. The rescue drops full-width front matter (dropFullWidth) and in-body bridging lines (dropWideatbridgingFrac), then scans the glyph-density x-projection for a single clean interior valley. One gutter -> 2 columns. It accepts only exactly one valley, so it never over-splits a single column into 3+.detectColumnCountMedian): inspired by PR Feat: add support for multi-column PDF parsing #10475'spage_w / median_line_width. Targets gutter-less doubles/triples whose x-projection has no clean ink dip, yet each line is only ~page_w/N wide (raw_cols >= 2). Guarded byraw_cols <= maxColumnCount(skip table cells) and a near-full-width line requirement (skip uniformly short lines).Accuracy impact (70-page labeled corpus)
The 2D rescue trades 5 more false-splits for 8 fewer misses, net +4.3 pt. The remaining false-splits are the pure-table column edge case (a column that is entirely a table collapses to 1 because internal cell gaps inflate the 1D projection past the table guard). That is tracked separately in #18079 (table guard) and intentionally left out of this PR to keep it small and revertible.
Test coverage
TestSyntheticTitleBridgedDouble: un-skipped and re-geometried to model a real title-bridged double (clean gutter at 240-260, non-overlapping x0, 12-line right column above the valleyFrac peak ink). Now recovered by the 2D rescue.TestSyntheticMedianWidthDouble: new, locks the gutter-less double that only the median-width ratio recovers.Both run in the default unit tier (no
manualbuild tag) and pass inbash build.sh --test ./internal/deepdoc/parser/pdf/layout/....Relationship to other work
main)._assign_columnis intentionally left unchanged (separate concern).Risk / regression
Code is wired strictly behind the existing gap + balance gates (rescue only fires when both return single), so single-column pages are unaffected. The unit tests in this package are the regression guard, plus the 70-page corpus baseline above.