Repository navigation
fix(pdf/layout): replace KMeans-only column detection with gap + KMeans hybrid - #18023
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthrough
ChangesPDF column assignment
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant PDFLayout
participant AssignColumn
participant GutterVoting
participant KmeansK2PlusPlus
PDFLayout->>AssignColumn: text boxes
AssignColumn->>GutterVoting: page boxes
GutterVoting-->>AssignColumn: detected column count
AssignColumn->>KmeansK2PlusPlus: normalized body-line coordinates when needed
KmeansK2PlusPlus-->>AssignColumn: validated clusters and centroids
AssignColumn-->>PDFLayout: boxes with ordered column IDs
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: 3
🧹 Nitpick comments (1)
internal/deepdoc/parser/pdf/layout/combined_column.go (1)
12-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUpdate the documentation to match the Go implementation.
Remove the
tool-py/column_detectors.pymigration reference. State that gap detection can return more than two columns becausedetectColumnCountreturnsgwheng >= 2. The current comment at Line 43 is incorrect.As per coding guidelines, “keep package and doc comments aligned with the current runtime path rather than migration history.”
Also applies to: 42-44
🤖 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 12 - 26, Update the documentation surrounding AssignColumn and detectColumnCount to remove the tool-py/column_detectors.py migration reference and accurately describe the current runtime behavior: gap detection returns g for any g >= 2, so it can produce more than two columns. Correct the inaccurate comment around the existing line-43 logic while keeping the documentation aligned with the Go implementation.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 `@internal/deepdoc/parser/pdf/layout/combined_column_test.go`:
- Around line 108-111: Update the accuracy documentation and failure message
associated with TestAssignColumnCombined_Labeled to state the enforced Go target
of at least 88.0%, replacing the misleading 94.4% combined target. Keep the
assertion threshold unchanged at 88.0% and ensure all related references
consistently describe the Go result.
- Around line 113-116: Ensure TestAssignColumnCombined_Labeled cannot silently
skip the charspy regression check: either add and track the required PDF JSON
corpus files under the charspy testdata directory, or replace the os.Stat-based
t.Skipf path with t.Fatalf so missing corpus data fails the test and preserves
enforcement of the 88% threshold.
In `@internal/deepdoc/parser/pdf/layout/combined_column.go`:
- Around line 163-165: Update the len(out) == 0 branch in the surrounding layout
function to return an empty slice instead of restoring lines, so all-full-width
pages bypass balancedBodyK2 KMeans and preserve the single-column result from
lines 121–123.
---
Nitpick comments:
In `@internal/deepdoc/parser/pdf/layout/combined_column.go`:
- Around line 12-26: Update the documentation surrounding AssignColumn and
detectColumnCount to remove the tool-py/column_detectors.py migration reference
and accurately describe the current runtime behavior: gap detection returns g
for any g >= 2, so it can produce more than two columns. Correct the inaccurate
comment around the existing line-43 logic while keeping the documentation
aligned with the Go implementation.
🪄 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: 7979578d-5a99-4c0d-9d1d-c6f00b689b98
📒 Files selected for processing (4)
internal/deepdoc/parser/pdf/layout/combined_column.gointernal/deepdoc/parser/pdf/layout/combined_column_test.gointernal/deepdoc/parser/pdf/layout/layout.gointernal/deepdoc/parser/pdf/layout/layout_test.go
| // TestAssignColumnCombined_Labeled ports gap+KMeans to Go and scores it on the | ||
| // 18 human-labeled pages. Reference (Python) numbers: KMeans 11.1%, gap 61.1%, | ||
| // gap+KMeans combined 94.4%. The Go port must clear the gap baseline and land | ||
| // near the combined target. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the stated Go accuracy target.
The PR reports 88.9% for the Go implementation. These comments and the failure message state an expected result near 94.4%, while the assertion accepts 88.0%. Update the text to describe the enforced Go target.
Also applies to: 171-173
🤖 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_test.go` around lines 108
- 111, Update the accuracy documentation and failure message associated with
TestAssignColumnCombined_Labeled to state the enforced Go target of at least
88.0%, replacing the misleading 94.4% combined target. Keep the assertion
threshold unchanged at 88.0% and ensure all related references consistently
describe the Go result.
Source: Coding guidelines
| charspyDir := "../testdata/charspy" | ||
| if _, err := os.Stat(charspyDir); err != nil { | ||
| t.Skipf("charspy corpus not found at %s (run from package dir): %v", charspyDir, err) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
corpus='internal/deepdoc/parser/pdf/testdata/charspy'
echo 'Tracked corpus files:'
git ls-files | rg "^${corpus}/" || true
echo
echo 'Working-tree corpus directory:'
if test -d "$corpus"; then
printf 'present: %s\n' "$corpus"
else
printf 'missing: %s\n' "$corpus"
fi
echo
echo 'Skip path in the labeled test:'
rg -n -C 3 'charspyDir|t\.Skipf' internal/deepdoc/parser/pdf/layout/combined_column_test.goRepository: infiniflow/ragflow
Length of output: 932
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo 'Relevant test function:'
sed -n '1,230p' internal/deepdoc/parser/pdf/layout/combined_column_test.go
echo
echo 'References to combined column / charspy tests across config/docs:'
rg -n 'combined_column|TestAssignColumnCombined|charspy|charspy corpus|accuracy threshold|labeled' --glob '!**/.git/**' .
echo
echo 'Git files under parser PDF testdata (count/sample):'
git ls-files internal/deepdoc/parser/pdf/testdata | sortRepository: infiniflow/ragflow
Length of output: 11110
Track or fail on the charspy regression corpus.
internal/deepdoc/parser/pdf/testdata/charspy contains no tracked files, so TestAssignColumnCombined_Labeled skips instead of enforcing the 88% combined-column threshold. Add the required {pdf}.json files to the repo, or change the missing-corpus path to a t.Fatalf if this test blocks merge.
🤖 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_test.go` around lines 113
- 116, Ensure TestAssignColumnCombined_Labeled cannot silently skip the charspy
regression check: either add and track the required PDF JSON corpus files under
the charspy testdata directory, or replace the os.Stat-based t.Skipf path with
t.Fatalf so missing corpus data fails the test and preserves enforcement of the
88% threshold.
Source: Coding guidelines
…ns hybrid The previous AssignColumn used KMeans x0 clustering with silhouette-score selection of k. On real multi-column PDFs this over-splits single columns (16/18 of our hand-labeled pages were detected as multi-column) while still missing genuine academic double-column pages. Replace it with a hybrid that combines the two detectors' complementary error directions: - Geometric gap (whitespace-gutter voting) is a reliable LOWER bound: it never over-splits a single column. When it reports >=2 gutters we trust it. - A forced k=2 KMeans on the BODY x0 (full-width front matter excluded) with a balance gate (each cluster >=30% of body lines AND centroid separation >=10% of page width) recovers double-column pages that gap alone misses. Unbalanced splits — the usual KMeans false-split on a single page — are dropped, staying single column. The gate uses density-aware k-means++ (random first center, farthest second) rather than util.KMeans1D's even-Lloyd partition, so it respects natural x0 density and correctly rejects a single column whose x0 merely spans a wide range. Measured on 18 human-labeled real-document pages: KMeans-only 11.1% (false-split=16) gap-only 61.1% (miss=7) gap + KMeans (Go) 88.9% (false-split=1, miss=1) gap + KMeans (Py) 94.4% (false-split=1, miss=0) parser.go already calls lyt.AssignColumn(boxes) by name, so the swap is wired into the pipeline automatically with no call-site change. Removed the now-dead KMeans helpers (determineBestKForPage, extractX0Values, applyIndentTolerance, findBestK, assignColIDsForPage, remapLabelsByCentroidOrder) and their obsolete unit tests; added combined_column.go + tests.
… gap==2 to balance gate The old detectColumnCount trusted gap>=2 unconditionally, which over-split single-column and table pages (gap returned 2-9 on indentation / table cells). New logic: - gap>=2 with narrow columns (max col width < 0.22*page) => table: return 1 text block directly (do not fall through to balance gate). - gap==2 => defer to the balanced k=2 gate (fake gutters are common). - gap>=3 with wide columns => real multi-column, trust it. - balanced gate (fmin>=0.30) unchanged => catches high-fmin doubles. Eval on the 70-page labeled set (tool-py/column_labeling_sheet.json): combined ACC 58.6% -> 74.3%, false-split 20 -> 8, vs gap-only 24.3%. The 9 remaining misses are doubles whose columns overlap in x0 and need vertical reading-flow features (out of scope here). Co-authored-by: CodeBuddy <[email protected]>
When every line on a page spans >=90% of the width, the full-width filter keeps nothing, so there is no narrow body to form a second column. Returning the original lines pushed the whole page through the balance gate, which could mis-split a full-width single column whose x0 happens to be bimodal. Return nil instead so the caller's len(body) < 4 guard treats the page as a single column. No change for pages that have any narrow body lines. Co-authored-by: CodeBuddy <[email protected]>
…moke test - Silhouette1D has no production caller since the KMeans-only column detector was replaced; delete it and its unit test (and the now-unused sort import in kmeans.go). - TestKmeansK2PlusPlus_Smoke asserted cents[0] <= cents[1], a property kmeansK2PlusPlus does not guarantee (assignColIDs sorts centroids itself). Assert centroid separation instead, which the function does guarantee. Co-authored-by: CodeBuddy <[email protected]>
The gap voting can over-split a single page into many spurious gutters (e.g. first-line indentation), and detectColumnCount returned g unbounded for g >= 3. That let a single page be reported as 7+ columns (2023-07-03 p7: gap=7 -> got=7), a failure mode the old detector could not produce because it capped best-k at min(4, n). Cap the reported count at maxColumnCount (4), matching the old bound, so spurious gutters cannot split a page into many columns. The 3-column case (11_three_column p1) is preserved. Co-authored-by: CodeBuddy <[email protected]>
After k-means partitioning, drop columns that capture no lines (an empty centroid, e.g. 12_mixed_columns p0's spurious third column) or fewer than 12% of the page's lines (an indentation/footnote sliver, e.g. 16_dense_cjk p0). The 12% floor sits with margin below the sparsest genuine column on the 70-page labeled corpus (real triple 22%+, real double 17.7%+), so it prunes outliers without harming real multi-column pages. Measured on the 70-page labeled corpus: ACC 75.7% -> 78.6%, false-split 7 -> 5. The 5 remaining over-splits are the indentation/dense-text family whose spurious column (8-27 lines at 23-33%) sits inside the real-double envelope and needs the reading-order model tracked in infiniflow#18079. Co-authored-by: CodeBuddy <[email protected]>
f801e75 to
e824350
Compare
Add hand-built []pdf.TextBox geometries committed to the repo so the column detector has a regression guardrail that runs on every `go test ./...` without the gitignored 70-page label sheet + 343MB corpus (which only run locally and are skipped in CI). Green assertions pin current correct behavior: single column stays 1, balanced double is recovered as 2, narrow side-by-side columns are treated as a table (1), and a sparse second column is rejected by the balance gate (1, guarding the minColLineFrac prune). A skipped TODO captures the infiniflow#18079 acceptance target (title-bridged double should split into 2 once a 2D spatial detector lands). Co-authored-by: CodeBuddy <[email protected]>
The balance gate clusters the BODY (full-width front matter excluded) but pruneColumns counted all lines, so full-width titles/abstracts inflated one column and could collapse a balanced two-column page back to one. Return the body slice from balancedBodyK2 and prune on it so both steps use the same line set. Adds TestAssignColumn_FullWidthBridgeKeepsBalancedTwoColumn (RED->GREEN).
|
Added a follow-up commit (Fix B) addressing the balance-gate / prune line-set inconsistency in the column detector:
The two earlier review points are already handled on this branch:
PR description updated with a Fix B section plus Files-changed / Test-plan notes. |
Summary
Replace the KMeans-only column detector (
AssignColumn) in the Go PDF layoutpackage with a gap + KMeans hybrid. The replacement keeps the
lyt.AssignColumn(boxes)signature thatparser.gocalls by name, so thepipeline picks it up automatically.
This PR also fixes a regression introduced by blindly trusting
gap >= 2(see "Fix A" below).
Problem
kselectionover-splits single-column pages — 16/18 detected as multi-column on a
first 18-page labeled sample (11.1% ACC).
over-splits, but misses academic double columns whose gutter is bridged by
full-width front matter. On the full 70-page labeled corpus:
25.7% ACC (false-split 18, miss 34).
Solution
The two detectors have complementary error directions (gap = safe floor,
KMeans = recoveries only), so we combine them:
>= 2gutters wetrust it and partition by
util.KMeans1D(g)— unless the columns arenarrow, which means a table (one text block, not text columns); tables
are returned as a single column directly so the balance gate does not
re-split them into 2.
k = 2density-aware k-means(k-means++) on the BODY x0 (full-width titles/abstracts excluded via
dropFullWidth) with a balance gate decides whether a real secondcolumn exists: each cluster holds
>= minModeFrac(30%) of body linesand the centroid separation is
>= minSepFrac(10%) of page width. Anunbalanced split — the usual KMeans false-split on a single page — is
dropped, so the page stays single column.
(
minColLineFrac = 0.12): a k-means centroid that captures no lines, orfewer than 12% of the page's lines, is not a real reading column — it is an
indentation sliver or a stray block. This recovers pages where gap
over-split (e.g. a spurious third column) without harming genuine sparse
multi-column pages (the labeled corpus's only real triple holds 22%+ per
column, and the sparsest real double 17.7%+ — both clear of the 12% floor).
Fix A (this PR's second commit): stop trusting gap >= 2 blindly
The first hybrid commit trusted
gap >= 2unconditionally. On real pages thatover-splits: indentation and table cells produce
gapvalues of 2–9 with noreal column, while genuine doubles (title-bridged gutter) report
gap == 1and were missed. The fix:
gap >= 2with narrow columns (max col width< 0.22 × page) → table →return 1 directly (skip the balance gate).
gap == 2→ defer to the balance gate (a fake gutter from indentationhas no real second cluster; a real 2-col passes).
gap >= 3with wide columns → trust as a real multi-column layout,capped at
maxColumnCount = 4so spurious gutters cannot split a page intomany columns.
fmin >= 0.30).Fix B (this PR's column-prune follow-up): balance gate and prune must use the same line set
The balance gate deliberately clusters the BODY — full-width front matter
(title / abstract / heading) is dropped via
dropFullWidthso a gutterbridged by front matter does not create a fake second column. But
pruneColumnswas then counting ALL lines, including that full-width frontmatter. Because full-width lines are reassigned to the nearest centroid, a
large full-width block inflates one column and can push the other below the
minColLineFrac(12%) floor, silently collapsing a real, gate-acceptedtwo-column page back to one.
Fix:
balancedBodyK2now also returns thebodyslice it clustered on, andthe balance branch of
detectColumnCountcallspruneColumns(body, cents)instead of
pruneColumns(lines, cents). Theg >= 3path is unchanged — italready clusters and prunes on the same all-lines set, so it stays
self-consistent.
TestAssignColumn_FullWidthBridgeKeepsBalancedTwoColumnreproduces the collapse (RED) and verifies the fix (GREEN).
Measured accuracy (70 human-labeled real pages, Go test harness)
(The earlier 88.9% / 94.4% figures came from the comfortable 18-page sample
and must not be used as a target — they are circular. The test now scores on
all 70 labeled pages.)
The corpus label for
2023-07-03.pdf.jsonpage 0 was corrected fromsingle-column to double-column (real narrow sidebar ≈ half the main column);
the gap-only detector had identified its gutter correctly all along, which is
why both the baseline and the hybrid improve by one page after the relabel.
Residual misses (10) — known limitations
heavily (minority fraction 0.05–0.29), so the balance gate's
fmin >= 0.30floor correctly rejects them. Lowering
fminto catch them adds ~18single-column over-splits → net worse. A vertical-coverage / reading-flow
rescue (option B) was evaluated: it recovers 7–8 of the 9 misses but adds
19 false-splits (wide tables and wide single pages have identical vertical
coverage to a real second column) → net −8 to −10 accuracy points.
Option B is rejected as a cheap heuristic; recovering these needs a genuine
reading-order / column-structure model, not a coverage proxy.
truth = 3). Three-column detection is out ofscope for this 2-column detector.
These 10 misses are tracked separately in #18079 (Go-side only) and are
intentionally left out of this PR.
Residual false-splits (5) — known limitations
After the sparse-column prune, 5 pages are still over-split (got > truth). All
five are the indentation / dense-text family: the page has a genuine
secondary x0 mode (block indentation, a dense CJK sub-block) that passes the
balance gate (gap == 1/2) or the gap >= 3 path, and the spurious column holds
8–27 lines at 23–33% ratio — squarely inside the real-double envelope (the
labeled corpus's sparsest real double is 17.7%, its only real triple 22%+ per
column). No count/width threshold can reject them without also breaking
genuine doubles/triples, so they are intentionally left out of this PR and
tracked in #18079 (reading-order model).
16_dense_cjk p1,2023-07-03 p1 / p2 / p8— single column split into 2(spurious column 8–27 lines).
2023-07-03 p7— single column split into 4 (gap=7 → capped to 4;spurious columns are indentation slivers).
Files changed
internal/deepdoc/parser/pdf/layout/combined_column.go— hybrid detector;table collapse (
tableMaxColFrac = 0.22);gap == 2deferral to balancegate;
maxColumnCount = 4cap; sparse-column prune (minColLineFrac = 0.12,pruneColumns);gapColumnWidths;clampInt; balance gate andpruneColumnsnow share the same BODY line set (Fix B).internal/deepdoc/parser/pdf/layout/combined_column_test.go— labeled evalover 70 pages with a live gap-only baseline (no hardcoded accuracy
target);
TestKmeansK2PlusPlus_Smoke;TestAssignColumn_FullWidthBridgeKeepsBalancedTwoColumn(full-width-bridged balanced two-column regression for Fix B).internal/deepdoc/parser/pdf/layout/layout.go— removed the dead KMeansAssignColumnand its helpers;AssignColumnnow lives incombined_column.go.internal/deepdoc/parser/pdf/layout/layout_test.go— updatedTestAssignColumnfixtures to carry real
X1geometry (the gap detector needs text width, notjust x0).
parser.goneeded no change.Test plan
All layout tests pass. The labeled test asserts the hybrid does not regress
the gap-only baseline by more than 5 points (a live comparison, not a tuned
constant). Reported:
ACC=78.6% false-split=5 miss=10 (n=70).Stderr: (empty)
Exit Code: 0
Signal: (none)