Skip to content

fix(pdf/layout): replace KMeans-only column detection with gap + KMeans hybrid - #18023

Merged
yuzhichang merged 9 commits into
infiniflow:mainfrom
xugangqiang:fix/pdf-column-gap-kmeans
Aug 11, 2026
Merged

yuzhichang merged 9 commits into
infiniflow:mainfrom
xugangqiang:fix/pdf-column-gap-kmeans

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Replace the KMeans-only column detector (AssignColumn) in the Go PDF layout
package with a gap + KMeans hybrid. The replacement keeps the
lyt.AssignColumn(boxes) signature that parser.go calls by name, so the
pipeline picks it up automatically.

This PR also fixes a regression introduced by blindly trusting gap >= 2
(see "Fix A" below).

Problem

  • KMeans-only (old): x0 clustering with silhouette k selection
    over-splits single-column pages — 16/18 detected as multi-column on a
    first 18-page labeled sample (11.1% ACC).
  • gap-only (whitespace-gutter voting, the safe lower bound): never
    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:

  1. Gap gutter voting is the safe base. When it finds >= 2 gutters we
    trust it and partition by util.KMeans1D(g) — unless the columns are
    narrow
    , 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.
  2. When gap reports a single column, a forced k = 2 density-aware k-means
    (k-means++) on the BODY x0
    (full-width titles/abstracts excluded via
    dropFullWidth) with a balance gate decides whether a real second
    column exists: each cluster holds >= minModeFrac (30%) of body lines
    and the centroid separation is >= minSepFrac (10%) of page width. An
    unbalanced split — the usual KMeans false-split on a single page — is
    dropped, so the page stays single column.
  3. After any partition, empty and too-sparse columns are pruned
    (minColLineFrac = 0.12): a k-means centroid that captures no lines, or
    fewer 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 >= 2 unconditionally. On real pages that
over-splits: indentation and table cells produce gap values of 2–9 with no
real column, while genuine doubles (title-bridged gutter) report gap == 1
and were missed. The fix:

  • gap >= 2 with 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 indentation
    has no real second cluster; a real 2-col passes).
  • gap >= 3 with wide columns → trust as a real multi-column layout,
    capped at maxColumnCount = 4 so spurious gutters cannot split a page into
    many columns.
  • balance gate unchanged (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 dropFullWidth so a gutter
bridged by front matter does not create a fake second column. But
pruneColumns was then counting ALL lines, including that full-width front
matter. 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-accepted
two-column page back to one.

Fix: balancedBodyK2 now also returns the body slice it clustered on, and
the balance branch of detectColumnCount calls pruneColumns(body, cents)
instead of pruneColumns(lines, cents). The g >= 3 path is unchanged — it
already clusters and prunes on the same all-lines set, so it stays
self-consistent. TestAssignColumn_FullWidthBridgeKeepsBalancedTwoColumn
reproduces the collapse (RED) and verifies the fix (GREEN).

Measured accuracy (70 human-labeled real pages, Go test harness)

detector ACC false-split miss
gap-only (baseline) 25.7% 18 34
gap + KMeans (this PR) 78.6% 5 10

(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.json page 0 was corrected from
single-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

  • 9 are title-bridged academic doubles. Their body x0 clusters overlap
    heavily (minority fraction 0.05–0.29), so the balance gate's fmin >= 0.30
    floor correctly rejects them. Lowering fmin to catch them adds ~18
    single-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.
  • 1 is a three-column page (truth = 3). Three-column detection is out of
    scope 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 == 2 deferral to balance
    gate; maxColumnCount = 4 cap; sparse-column prune (minColLineFrac = 0.12, pruneColumns); gapColumnWidths; clampInt; balance gate and pruneColumns now share the same BODY line set (Fix B).
  • internal/deepdoc/parser/pdf/layout/combined_column_test.go — labeled eval
    over 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 KMeans
    AssignColumn and its helpers; AssignColumn now lives in
    combined_column.go.
  • internal/deepdoc/parser/pdf/layout/layout_test.go — updated TestAssignColumn
    fixtures to carry real X1 geometry (the gap detector needs text width, not
    just x0).

parser.go needed no change.

Test plan

bash build.sh --test ./internal/deepdoc/parser/pdf/layout/

The Fix B regression test (`TestAssignColumn_FullWidthBridgeKeepsBalancedTwoColumn`) runs on every `go test ./internal/deepdoc/parser/pdf/layout/` with no external corpus, guarding the balance-gate / prune line-set consistency.

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)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 9, 2026
@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

AssignColumn now detects PDF text columns per page with whitespace-gap voting and validated KMeans fallback logic. It normalizes coordinates, assigns ordered column IDs, and replaces the previous layout.go implementation. Tests add labeled-corpus accuracy and clustering coverage.

Changes

PDF column assignment

Layer / File(s) Summary
Hybrid column detection
internal/deepdoc/parser/pdf/layout/combined_column.go
AssignColumn groups boxes by page, detects gutters, classifies narrow regions, excludes full-width lines, normalizes indentation, and validates balanced two-cluster body splits.
Deterministic clustering and assignment
internal/deepdoc/parser/pdf/layout/combined_column.go
Deterministic KMeans++ calculates centroids. Boxes receive left-to-right column IDs. Empty and single-column inputs use ID 0.
Implementation migration and validation
internal/deepdoc/parser/pdf/layout/layout.go, internal/deepdoc/parser/pdf/layout/combined_column_test.go, internal/deepdoc/parser/pdf/layout/layout_test.go, internal/deepdoc/parser/pdf/util/kmeans.go, internal/deepdoc/parser/pdf/util/kmeans_test.go
The former implementation and Silhouette1D are removed. Tests reconstruct text lines, compare labeled-corpus accuracy with the gap-only baseline, check KMeans behavior, and update fixtures.

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
Loading

Possibly related PRs

Suggested labels: ☯️ refactor, 🐞 bug

Suggested reviewers: yingfeng, jinhai-cn, yuzhichang

Poem

I hop through gutters, left to right,
KMeans finds columns out of sight.
Centroids sort each text-box line,
Corpus tests check every sign.
The burrow ships a cleaner layout.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly and concisely identifies the replacement of KMeans-only detection with a gap plus KMeans hybrid.
Description check ✅ Passed The description includes the required Summary section and provides problem, solution, metrics, files, limitations, and test results.

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.

@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: 3

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

12-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update the documentation to match the Go implementation.

Remove the tool-py/column_detectors.py migration reference. State that gap detection can return more than two columns because detectColumnCount returns g when g >= 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

📥 Commits

Reviewing files that changed from the base of the PR and between 99110c2 and a0a4e74.

📒 Files selected for processing (4)
  • internal/deepdoc/parser/pdf/layout/combined_column.go
  • internal/deepdoc/parser/pdf/layout/combined_column_test.go
  • internal/deepdoc/parser/pdf/layout/layout.go
  • internal/deepdoc/parser/pdf/layout/layout_test.go

Comment on lines +108 to +111
// 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.

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

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

Comment on lines +113 to +116
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)
}

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 | 🟠 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.go

Repository: 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 | sort

Repository: 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

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Aug 10, 2026
@xugangqiang xugangqiang added the ci Continue Integration label Aug 10, 2026
xugangqiang and others added 6 commits August 11, 2026 13:04
…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]>
@xugangqiang
xugangqiang force-pushed the fix/pdf-column-gap-kmeans branch from f801e75 to e824350 Compare August 11, 2026 05:05
xugangqiang and others added 3 commits August 11, 2026 14:33
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).
@xugangqiang

Copy link
Copy Markdown
Contributor Author

Added a follow-up commit (Fix B) addressing the balance-gate / prune line-set inconsistency in the column detector:

  • The balance gate clusters the BODY (full-width title/abstract dropped via dropFullWidth), but pruneColumns was counting ALL lines, so a large full-width front-matter block could inflate one column and silently collapse a real, gate-accepted two-column page back to one.
  • balancedBodyK2 now also returns the body slice it clustered on, and the balance branch of detectColumnCount calls pruneColumns(body, cents) instead of pruneColumns(lines, cents). The g >= 3 path is unchanged — it already clusters and prunes on the same all-lines set, so it stays self-consistent.
  • Added TestAssignColumn_FullWidthBridgeKeepsBalancedTwoColumn (RED → GREEN, no external corpus needed) covering a full-width-bridged balanced two-column page.

The two earlier review points are already handled on this branch:

  • the misleading 94.4% figure is removed (docs commit), and
  • the labeled eval now ships CI-runnable synthetic fixtures (combined_column_synthetic_test.go), so accuracy is guarded on every go test ./... without the gitignored corpus.

PR description updated with a Fix B section plus Files-changed / Test-plan notes.

@yuzhichang
yuzhichang merged commit b4dd0f7 into infiniflow:main Aug 11, 2026
3 checks passed
yuzhichang pushed a commit that referenced this pull request Aug 12, 2026
…2D rescue + L3) (#18150)

Incremental follow-up to #18023 (gap + balance-gate hybrid). Adds two
complementary column detectors to `AssignColumn` that run **only after**
the gap detector and the balance gate both fail, so already-correct
pages are never touched.
@xugangqiang
xugangqiang deleted the fix/pdf-column-gap-kmeans branch August 12, 2026 11:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants