Skip to content

Feat/oss parser no post - #16464

Merged
yuzhichang merged 10 commits into
infiniflow:mainfrom
xugangqiang:feat/oss-parser-no-post
Jul 2, 2026
Merged

yuzhichang merged 10 commits into
infiniflow:mainfrom
xugangqiang:feat/oss-parser-no-post

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Remove dead code

@coderabbitai

coderabbitai Bot commented Jun 29, 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

Extracts shared PDF parser types into a new doctype package, renames the InferenceClient to Client, exports several previously unexported engine/renderer symbols, decouples DocAnalyzer/TableBuilder from Parser construction into a new ParseRaw/Parse API, removes the vision-based image-description post-processing layer, and migrates all pdf package tests accordingly.

Changes

PDF Parser Refactoring

Layer / File(s) Summary
Shared doctype package
internal/deepdoc/parser/type/types.go, internal/deepdoc/parser/pdf/type/types.go, internal/deepdoc/parser/pdf/util/geometry*.go
New doctype package defines format-agnostic parser types/constants/interfaces; pdf/type/types.go becomes a thin alias layer over doctype; SortXByPage is removed from util.
Inference client rename
internal/deepdoc/parser/pdf/inference/client*.go
InferenceClient renamed to Client, NewInferenceClient→NewClient, adds BaseURL(), DefaultDLALabels(), DefaultTSRLabels().
Engine/renderer exports & mocks
internal/deepdoc/parser/pdf/pdfoxide_bridge.go, renderer.go, renderer_pdfium.go, mock_engine.go, mock_doc_analyzer.go
pdfoxideEngine→PDFOxideEngine, renderPageToImage→RenderPageToImage, refined nil-render guard, new exported MockEngine stub, MockDocAnalyzer moved to pdf package.
Parser decoupling & table extraction
parser.go, parser_ocr.go, parse_cgo.go, table_extract.go, table/table_construct.go
Parser stripped of stored dependencies; NewParser(cfg) + new ParseRaw/Parse inject docAnalyzer/TableBuilder per call; table extraction and OCR merge refactored (processOneTable, matchTableImage, buildTextBoxes); adds SimpleRowsToHTML.
Test suite migration
internal/deepdoc/parser/pdf/*_test.go
All test files moved to package pdf and updated to the NewParser(cfg) + ParseRaw/Parse(ctx, data, client) API, MockEngine/inf.Client, and util.OverlapX/util.CropImageRegion.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • infiniflow/ragflow#16391: Overlapping refactor of the PDF parser and inference client touching the same internal/deepdoc/parser/pdf components.

Suggested labels: ☯️ refactor, size:XXL

Suggested reviewers: yingfeng, yuzhichang, JinHai-CN

A rabbit hopped through code so deep,
Untangling clients while the parser did leap,
Types now shared in a burrow anew,
Client renamed, and MockEngine too,
Tests all reshuffled, hop hop, all set—
A tidy warren, no loose ends yet! 🐇✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description is too brief and generic, lacking the background context and scope requested by the template. Expand the Summary section to explain what dead code was removed and why, plus the problem this PR is solving.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is brief and clearly points to the parser/post-processing removal theme of this changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

❤️ Share

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

@xugangqiang
xugangqiang force-pushed the feat/oss-parser-no-post branch from fa5a3ae to a63bdd1 Compare June 29, 2026 14:29
@xugangqiang xugangqiang added the ci Continue Integration label Jun 29, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review June 29, 2026 14:30
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 17

🧹 Nitpick comments (1)
internal/deepdoc/parser/docx/tools/export_raw_blocks.py (1)

4-6: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use logging here and format the file to pass Ruff.

This new Python flow still uses a multi-import line plus print(..., file=sys.stderr) for status output. Please switch to logging and split imports so the script matches the repo’s Python conventions. As per coding guidelines, **/*.py: Add logging for new flows and use ruff check / ruff format.

Proposed cleanup
-import json, sys, os, base64
+import base64
+import json
+import logging
+import os
+import sys
 from docx import Document
 from docx.text.paragraph import Paragraph
+
+logger = logging.getLogger(__name__)
@@
 if __name__ == "__main__":
+    logging.basicConfig(level=logging.INFO)
     if len(sys.argv) < 2:
-        print(f"Usage: {sys.argv[0]} <docx_file> [output_dir]", file=sys.stderr)
+        logger.error("Usage: %s <docx_file> [output_dir]", sys.argv[0])
         sys.exit(1)
@@
         with open(out_path, "w") as f:
             json.dump(blocks, f, indent=2, ensure_ascii=False)
-        print(f"Wrote {out_path} ({len(blocks)} blocks)", file=sys.stderr)
+        logger.info("Wrote %s (%d blocks)", out_path, len(blocks))

Also applies to: 50-66

🤖 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/docx/tools/export_raw_blocks.py` around lines 4 - 6,
The script setup in export_raw_blocks.py still uses a combined import line and
stderr prints for status, which conflicts with the repo’s Python style and Ruff
rules. Split the imports into separate lines, replace the print-based status
output with the logging module in the main flow that handles raw block export,
and keep the logging calls consistent with the surrounding script structure.
Make sure the updated code passes both ruff check and ruff format, and use the
existing export_raw_blocks flow as the place to apply the logging change.

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 @.gitignore:
- Line 248: The .gitignore rule for internal/deepdoc/parser/docx/testdata is too
broad and is hiding committed DOCX fixtures used by the parser tests. Narrow the
ignore entry in .gitignore so it only excludes truly generated scratch
artifacts, and leave the shared testdata directory tracked for the test cases
that reference it.

In `@internal/deepdoc/parser/docx/parser.go`:
- Around line 56-60: `Parse` in the docx parser currently depends on
`ExtractRawBlocks`, which only exists in the cgo-backed implementation, so the
package won’t compile in non-cgo builds. Make `parser.go` buildable the same way
as `reader.go` by adding the appropriate build gate, or provide a non-cgo
`ExtractRawBlocks` stub that returns a clear unsupported error so `Parse` can
still compile everywhere.

In `@internal/deepdoc/parser/docx/reader.go`:
- Around line 136-140: The joinElements helper is flattening nested paragraphs
in table cells without any separator, which collapses multi-paragraph cell text
and breaks parity with the Python baseline. Update joinElements in the docx
reader path so it preserves paragraph boundaries when iterating over irElement
content, using the same text separator semantics expected by cell.text. Keep the
fix scoped to the table-cell text assembly flow that uses joinElements and
joinRuns.

In `@internal/deepdoc/parser/pdf/batch_smoke_test.go`:
- Around line 241-243: The parse helper is still calling the old parser API, so
update the `parseOne` flow to use the refactored raw parse path instead of
`Parse`. In `batch_smoke_test.go`, replace the `p.Parse(context.Background(),
eng)` call on the `NewParser(cfg)` instance with the new `ParseRaw(ctx, eng,
deepDoc)` signature used by `parser.go`, and make sure the helper passes the
required deepDoc/analyzer input that the refactor expects.

In `@internal/deepdoc/parser/pdf/crop_integration_test.go`:
- Line 3: The crop integration tests are still calling the old coupled parser
API, so update both test cases to use the decoupled parser entrypoints in
parser.go. Replace NewParser(cfg, &MockDocAnalyzer{...}) with NewParser(cfg),
and change the parse invocation from p.Parse(ctx, eng) to the appropriate new
method signature, passing the analyzer explicitly with ParseRaw(ctx, eng,
analyzer) or Parse(ctx, data, analyzer) as needed. Apply the same migration in
TestCrop_Regression_SnapshotPDFs so both tests compile against the new Parser
API.

In `@internal/deepdoc/parser/pdf/mock_engine.go`:
- Around line 20-29: `MockEngine.RenderPage` currently returns `(nil, nil)`,
which makes byte-rendering callers think page rendering succeeded when no data
was produced. Update this method to return a non-nil error for the mock path, or
generate deterministic mock image bytes instead of empty output, so any code
using `pdf.PDFEngine` can detect the failure correctly. Keep the fix localized
to `MockEngine.RenderPage` and preserve the existing width/height fallback
behavior.

In `@internal/deepdoc/parser/pdf/parser_pipeline_manual_test.go`:
- Line 50: The manual test still calls the old Parse(ctx, eng) signature after
switching to NewParser(cfg), which leaves the new analyzer dependency unused and
breaks compilation. Update the test around NewParser and the Parse call to use
the current parse API by passing the analyzer at the call site, and make sure
the existing client variable is wired into that new argument instead of
remaining unused.

In `@internal/deepdoc/parser/pdf/parser_test.go`:
- Around line 571-572: The concurrency test is ignoring ParseRaw failures by
discarding the returned error, so unsafe concurrent behavior can slip through
unnoticed. Update the ParseRaw call in the test that uses MockEngine and mockDLA
to capture the error, and if it is non-nil report it with t.Errorf from inside
the goroutine so the test reliably fails; use the ParseRaw invocation and the
surrounding goroutine in parser_test as the location to fix.

In `@internal/deepdoc/parser/pdf/parser.go`:
- Around line 497-517: The fallback in matchTableImage currently hardcodes page
0 when Section.Positions is empty, so it can miss images for tables on later
pages. Update the fallback to derive the page number from the table’s own
position metadata (for example, sec.TableItem.Positions or equivalent) before
building the lookup key, and keep the existing region-based key format
consistent with the main Section.Positions path.
- Around line 44-47: The parser in `Parse` is overwriting caller-provided
taxonomy settings by resetting `inf.Client.DLALabels` and `TSRLabels` to
defaults whenever the client is detected. Remove this unconditional mutation in
`parser.go` and make the parse path use the existing label taxonomies from the
passed-in `*inf.Client`, preserving any model-specific values already configured
and avoiding shared-state changes during concurrent reuse.

In `@internal/deepdoc/parser/pdf/pdfium_integration_test.go`:
- Around line 37-38: The pdfium integration test is still calling removed parser
APIs after the decoupling. Update the test to use the new parser construction
and parsing flow instead of NewParser(cfg, analyzer) and Parse(ctx, eng), and
keep the RenderPageToImage check aligned with the current parser/pipeline
symbols so the test compiles again.

In `@internal/deepdoc/parser/pdf/pipeline_parity_test.go`:
- Around line 57-59: The test is still calling the old parser constructor, which
no longer matches the exported API in parser.go. Update the pipeline parity test
to use NewParser(cfg) instead of New(cfg), and keep the rest of the ParseRaw
setup intact so the test continues to exercise the same parser path.

In `@internal/deepdoc/parser/pdf/scan_all_pdfs_test.go`:
- Around line 44-46: The test still uses the removed parser entrypoint, so
update it to the new engine-based flow in the pdf parser test by switching the
call site that currently uses Parse(ctx, eng) to the new parser API and passing
the engine through the parser instance instead of as a Parse argument. Also
remove or reuse the now-unused client variable in scan_all_pdfs_test.go so the
test compiles cleanly, and keep the change aligned with NewParser and Parse in
the pdf parser package.

In `@internal/deepdoc/parser/pdf/table_rotate_integration_test.go`:
- Line 36: The parser constructor migration is incomplete: update the test setup
to use the new NewParser(cfg) signature instead of passing the analyzer/client
there. Keep the analyzer injection at the Parse and ParseRaw call sites, and use
the relevant symbols NewParser, Parse, and ParseRaw in this test to ensure the
API matches the current parser contract.
- Line 181: The stability loop in table_rotate_integration_test currently
ignores the error from util.CropImageRegion, which can hide invalid or empty
table regions. Update the crop handling in the loop that uses pageImg and r to
check the returned error, and fail the test or otherwise surface the problem
instead of silently continuing. Keep the fix localized to the CropImageRegion
call site so invalid regions are not treated as successful skips.

In `@internal/deepdoc/parser/pdf/text_dump_test.go`:
- Line 3: This test is still using the removed coupled parser API, so update the
PDF test to the decoupled flow. In the text dump test, replace the
`NewParser(cfg, analyzer)` construction with `NewParser(cfg)`, and swap the old
`Parse(ctx, eng)` call for `ParseRaw(ctx, eng, docAnalyzer)` using the analyzer
instance the test already sets up. Make the changes in the test logic that
exercises the parser so it matches the current `Parser` API and compiles again.

In `@internal/deepdoc/parser/type/types.go`:
- Around line 127-139: SectionsByPage is appending the same Section multiple
times when more than one Position matches the same page because the current
break only exits the inner PageNumbers loop. Update SectionsByPage to stop
scanning the remaining Positions once a match is found for a Section, using the
existing Section, Positions, and PageNumbers loops as the location to add the
deduplication logic. Keep the behavior of returning all matching sections, but
ensure each Section appears at most once in the result.

---

Nitpick comments:
In `@internal/deepdoc/parser/docx/tools/export_raw_blocks.py`:
- Around line 4-6: The script setup in export_raw_blocks.py still uses a
combined import line and stderr prints for status, which conflicts with the
repo’s Python style and Ruff rules. Split the imports into separate lines,
replace the print-based status output with the logging module in the main flow
that handles raw block export, and keep the logging calls consistent with the
surrounding script structure. Make sure the updated code passes both ruff check
and ruff format, and use the existing export_raw_blocks flow as the place to
apply the logging change.
🪄 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: 7765a0f4-fb80-48bf-a434-dfcb5ffa96b6

📥 Commits

Reviewing files that changed from the base of the PR and between 6370fce and a63bdd1.

📒 Files selected for processing (53)
  • .gitignore
  • internal/deepdoc/parser/docx/parser.go
  • internal/deepdoc/parser/docx/parser_test.go
  • internal/deepdoc/parser/docx/raw_blocks_test.go
  • internal/deepdoc/parser/docx/reader.go
  • internal/deepdoc/parser/docx/tools/export_raw_blocks.py
  • internal/deepdoc/parser/pdf/batch_smoke_test.go
  • internal/deepdoc/parser/pdf/compare_test.go
  • internal/deepdoc/parser/pdf/crop_integration_test.go
  • internal/deepdoc/parser/pdf/dla_real_world_test.go
  • internal/deepdoc/parser/pdf/dla_tsr_compare_test.go
  • internal/deepdoc/parser/pdf/helpers_test.go
  • internal/deepdoc/parser/pdf/inference/client.go
  • internal/deepdoc/parser/pdf/inference/client_test.go
  • internal/deepdoc/parser/pdf/inference_client_integration_test.go
  • internal/deepdoc/parser/pdf/mock_doc_analyzer.go
  • internal/deepdoc/parser/pdf/mock_engine.go
  • internal/deepdoc/parser/pdf/ocr_merge_test.go
  • internal/deepdoc/parser/pdf/ocr_recognize_batch_test.go
  • internal/deepdoc/parser/pdf/outline_extraction_test.go
  • internal/deepdoc/parser/pdf/page_batch_test.go
  • internal/deepdoc/parser/pdf/parse_cgo.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/parser_mock_test.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/parser_ocr_test.go
  • internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
  • internal/deepdoc/parser/pdf/parser_pipeline_manual_test.go
  • internal/deepdoc/parser/pdf/parser_test.go
  • internal/deepdoc/parser/pdf/pdfium_integration_test.go
  • internal/deepdoc/parser/pdf/pdfoxide_bridge.go
  • internal/deepdoc/parser/pdf/pipeline_parity_test.go
  • internal/deepdoc/parser/pdf/post/model_image_describer.go
  • internal/deepdoc/parser/pdf/post/model_image_describer_test.go
  • internal/deepdoc/parser/pdf/post/outline_postprocess_test.go
  • internal/deepdoc/parser/pdf/post/post_steps.go
  • internal/deepdoc/parser/pdf/post/post_steps_test.go
  • internal/deepdoc/parser/pdf/post/vision_describe.go
  • internal/deepdoc/parser/pdf/post/vision_describe_test.go
  • internal/deepdoc/parser/pdf/render_compare_test.go
  • internal/deepdoc/parser/pdf/renderer.go
  • internal/deepdoc/parser/pdf/renderer_pdfium.go
  • internal/deepdoc/parser/pdf/rotate_test.go
  • internal/deepdoc/parser/pdf/scan_all_pdfs_test.go
  • internal/deepdoc/parser/pdf/snapshot_test.go
  • internal/deepdoc/parser/pdf/table_extract.go
  • internal/deepdoc/parser/pdf/table_rotate_integration_test.go
  • internal/deepdoc/parser/pdf/table_section_test.go
  • internal/deepdoc/parser/pdf/test_helpers_test.go
  • internal/deepdoc/parser/pdf/text_dump_test.go
  • internal/deepdoc/parser/pdf/type/types.go
  • internal/deepdoc/parser/pdf/ycoord_test.go
  • internal/deepdoc/parser/type/types.go
💤 Files with no reviewable changes (7)
  • internal/deepdoc/parser/pdf/post/post_steps.go
  • internal/deepdoc/parser/pdf/post/vision_describe.go
  • internal/deepdoc/parser/pdf/post/outline_postprocess_test.go
  • internal/deepdoc/parser/pdf/post/vision_describe_test.go
  • internal/deepdoc/parser/pdf/post/model_image_describer_test.go
  • internal/deepdoc/parser/pdf/post/model_image_describer.go
  • internal/deepdoc/parser/pdf/post/post_steps_test.go

Comment thread .gitignore
# Parser test fixtures and python tools
internal/deepdoc/parser/pdf/testdata/
internal/deepdoc/parser/pdf/tools-py/
internal/deepdoc/parser/docx/testdata/

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

This ignore rule is too broad for the new test fixtures.

Both DOCX test files read committed assets from internal/deepdoc/parser/docx/testdata/.... Ignoring the entire tree makes future fixture additions or golden updates easy to miss from the repo and can break CI on a clean clone. Please narrow this to only truly generated scratch artifacts, not the shared fixture directory.

🤖 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 @.gitignore at line 248, The .gitignore rule for
internal/deepdoc/parser/docx/testdata is too broad and is hiding committed DOCX
fixtures used by the parser tests. Narrow the ignore entry in .gitignore so it
only excludes truly generated scratch artifacts, and leave the shared testdata
directory tracked for the test cases that reference it.

Comment thread internal/deepdoc/parser/docx/parser.go Resolved
Comment thread internal/deepdoc/parser/docx/reader.go Outdated
Comment on lines +136 to +140
func joinElements(els []irElement) string {
var b strings.Builder
for _, el := range els {
b.WriteString(joinRuns(el.Content))
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve paragraph boundaries inside table cells.

joinElements concatenates each nested paragraph with no separator, so a cell containing multiple paragraphs becomes foobar instead of matching the Python baseline’s cell.text behavior. That will corrupt table cell text and break Go/Python parity for multi-paragraph cells.

Proposed fix
 func joinElements(els []irElement) string {
-	var b strings.Builder
+	parts := make([]string, 0, len(els))
 	for _, el := range els {
-		b.WriteString(joinRuns(el.Content))
+		if text := joinRuns(el.Content); text != "" {
+			parts = append(parts, text)
+		}
 	}
-	return b.String()
+	return strings.Join(parts, "\n")
 }
📝 Committable suggestion

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

Suggested change
func joinElements(els []irElement) string {
var b strings.Builder
for _, el := range els {
b.WriteString(joinRuns(el.Content))
}
func joinElements(els []irElement) string {
parts := make([]string, 0, len(els))
for _, el := range els {
if text := joinRuns(el.Content); text != "" {
parts = append(parts, text)
}
}
return strings.Join(parts, "\n")
}
🤖 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/docx/reader.go` around lines 136 - 140, The
joinElements helper is flattening nested paragraphs in table cells without any
separator, which collapses multi-paragraph cell text and breaks parity with the
Python baseline. Update joinElements in the docx reader path so it preserves
paragraph boundaries when iterating over irElement content, using the same text
separator semantics expected by cell.text. Keep the fix scoped to the table-cell
text assembly flow that uses joinElements and joinRuns.

Comment thread internal/deepdoc/parser/type/types.go Outdated
Comment on lines +127 to +139
func SectionsByPage(sections []Section, page int) []Section {
var out []Section
for _, s := range sections {
for _, p := range s.Positions {
for _, pn := range p.PageNumbers {
if pn == page {
out = append(out, s)
break
}
}
}
}
return out

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Deduplicate matches in SectionsByPage.

A Section with multiple Positions on the same page is appended more than once here, because the break only exits the PageNumbers loop.

Suggested fix
 func SectionsByPage(sections []Section, page int) []Section {
 	var out []Section
 	for _, s := range sections {
+		matched := false
 		for _, p := range s.Positions {
 			for _, pn := range p.PageNumbers {
 				if pn == page {
 					out = append(out, s)
+					matched = true
 					break
 				}
 			}
+			if matched {
+				break
+			}
 		}
 	}
 	return out
 }
📝 Committable suggestion

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

Suggested change
func SectionsByPage(sections []Section, page int) []Section {
var out []Section
for _, s := range sections {
for _, p := range s.Positions {
for _, pn := range p.PageNumbers {
if pn == page {
out = append(out, s)
break
}
}
}
}
return out
func SectionsByPage(sections []Section, page int) []Section {
var out []Section
for _, s := range sections {
matched := false
for _, p := range s.Positions {
for _, pn := range p.PageNumbers {
if pn == page {
out = append(out, s)
matched = true
break
}
}
if matched {
break
}
}
}
return out
}
🤖 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/type/types.go` around lines 127 - 139, SectionsByPage
is appending the same Section multiple times when more than one Position matches
the same page because the current break only exits the inner PageNumbers loop.
Update SectionsByPage to stop scanning the remaining Positions once a match is
found for a Section, using the existing Section, Positions, and PageNumbers
loops as the location to add the deduplication logic. Keep the behavior of
returning all matching sections, but ensure each Section appears at most once in
the result.

@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/docx/parser_integration_test.go (1)

65-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid asserting the current HTML whitespace format.

These checks hard-code <th > / <td >, so a harmless renderer change to <th> or different attribute spacing will fail the tests even when the table output is still correct. Assert on the tag/text pair or parsed cell content instead.

Suggested change
-	if !strings.Contains(result.Sections[2].Text, "<th >Product</th>") {
+	if !strings.Contains(result.Sections[2].Text, ">Product</th>") {
 		t.Errorf("table HTML missing header: %s", result.Sections[2].Text)
 	}
...
-	if !strings.Contains(s.Text, "<th >A</th>") || !strings.Contains(s.Text, "<th >B</th>") {
+	if !strings.Contains(s.Text, ">A</th>") || !strings.Contains(s.Text, ">B</th>") {
 		t.Errorf("table header cells: %s", s.Text)
 	}
-	if !strings.Contains(s.Text, "<td >1</td>") || !strings.Contains(s.Text, "<td >2</td>") {
+	if !strings.Contains(s.Text, ">1</td>") || !strings.Contains(s.Text, ">2</td>") {
 		t.Errorf("table data cells: %s", s.Text)
 	}

Also applies to: 143-147

🤖 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/docx/parser_integration_test.go` around lines 65 -
66, The DOCX parser integration tests are overly brittle because they assert
exact HTML whitespace formatting in the table output. Update the checks in
parser_integration_test.go around the table assertions (including the ones in
the later table cases) to verify the tag/text content or parsed cell values
instead of matching literal strings like "<th >" and "<td >". Keep the existing
test intent, but make the assertions tolerant of harmless renderer spacing
changes in result.Sections.
🤖 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/docx/parser_integration_test.go`:
- Line 1: The DOCX integration test file is excluded from the CI test run
because it is guarded by the cgo/manual build tag. Update the Go test workflow
so the `./build.sh --test` path includes the `manual` tag, or add a dedicated
job that runs the manual-tagged tests; use the existing
`parser_integration_test.go` build constraint as the reference point when wiring
this into CI.

In `@internal/deepdoc/parser/pdf/parser_ocr.go`:
- Around line 249-250: Treat whitespace-only assembled text as empty so OCR is
not skipped for blank regions. Update the OCR decision in the parser flow around
needOCR and the later filtering of TextBoxes in parser_ocr.go to use
strings.TrimSpace(tb.Text) instead of only checking tb.Text == "" or filtering
exact empty strings. Keep the existing matching behavior for real text, but
ensure whitespace-only TextBox values are treated the same as empty before
deciding whether to return them or send them to OCR fallback.

In `@internal/deepdoc/parser/pdf/table/table_construct.go`:
- Around line 722-730: Escape the per-cell content in SimpleRowsToHTML before
appending it to the HTML buffer, since row text is parsed input and can inject
markup when written verbatim. Update the loop that builds each <tag> cell so it
HTML-escapes text (including <, >, &, and quotes) before b.WriteString, and keep
the existing table/tag construction unchanged.

---

Nitpick comments:
In `@internal/deepdoc/parser/docx/parser_integration_test.go`:
- Around line 65-66: The DOCX parser integration tests are overly brittle
because they assert exact HTML whitespace formatting in the table output. Update
the checks in parser_integration_test.go around the table assertions (including
the ones in the later table cases) to verify the tag/text content or parsed cell
values instead of matching literal strings like "<th >" and "<td >". Keep the
existing test intent, but make the assertions tolerant of harmless renderer
spacing changes in result.Sections.
🪄 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: 1020756b-e066-4aa9-a731-0e151b5f0cd0

📥 Commits

Reviewing files that changed from the base of the PR and between a63bdd1 and e08bc10.

📒 Files selected for processing (12)
  • .gitignore
  • internal/deepdoc/parser/docx/parser_integration_test.go
  • internal/deepdoc/parser/docx/parser_test.go
  • internal/deepdoc/parser/docx/raw_blocks_test.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/table/table_construct.go
  • internal/deepdoc/parser/pdf/table_extract.go
  • internal/deepdoc/parser/pdf/type/types.go
  • internal/deepdoc/parser/pdf/util/geometry.go
  • internal/deepdoc/parser/pdf/util/geometry_test.go
  • internal/deepdoc/parser/type/types.go
💤 Files with no reviewable changes (5)
  • internal/deepdoc/parser/pdf/util/geometry.go
  • internal/deepdoc/parser/docx/parser_test.go
  • internal/deepdoc/parser/pdf/util/geometry_test.go
  • internal/deepdoc/parser/pdf/type/types.go
  • internal/deepdoc/parser/type/types.go
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/deepdoc/parser/docx/raw_blocks_test.go
  • internal/deepdoc/parser/pdf/table_extract.go
  • internal/deepdoc/parser/pdf/parser.go

@@ -0,0 +1,154 @@
//go:build cgo && manual

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

for p in .github/workflows .circleci .gitlab-ci.yml .gitlab-ci.yaml Makefile makefile Taskfile.yml Taskfile.yaml justfile; do
  [ -e "$p" ] || continue
  echo "== $p =="
  rg -n --hidden -S 'go test|gotestsum|manual|tags=' "$p" || true
done

Repository: infiniflow/ragflow

Length of output: 536


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== search for manual tag / go test invocations =="
rg -n --hidden -S --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  '(-tags=manual|tags: *manual|manual\b|go test|gotestsum)' \
  .github/workflows .circleci .gitlab-ci.yml .gitlab-ci.yaml Makefile makefile Taskfile.yml Taskfile.yaml justfile \
  internal 2>/dev/null || true

echo
echo "== workflow excerpts around go test =="
sed -n '220,275p' .github/workflows/tests.yml
echo
sed -n '675,710p' .github/workflows/tests.yml

Repository: infiniflow/ragflow

Length of output: 15548


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== build.sh references =="
rg -n --hidden -S 'tags?=manual|manual|go test|build.sh --test|--test' build.sh . 2>/dev/null || true

echo
echo "== build.sh excerpt =="
sed -n '1,260p' build.sh

Repository: infiniflow/ragflow

Length of output: 50376


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== CI / scripts with explicit manual tags =="
rg -n --hidden -S --glob '.github/workflows/**' --glob 'build.sh' --glob 'run_go_tests.sh' \
  '(-tags=manual|tags=.*manual|manual.*-tags|go test .*manual)' \
  .github/workflows build.sh run_go_tests.sh . 2>/dev/null || true

echo
echo "== DOCX manual test file context =="
sed -n '1,220p' internal/deepdoc/parser/docx/parser_integration_test.go

Repository: infiniflow/ragflow

Length of output: 4684


Run the DOCX integration tests in CI .github/workflows/tests.yml currently invokes ./build.sh --test without -tags=manual, so internal/deepdoc/parser/docx/parser_integration_test.go stays out of the default test path. Add the tag to the Go test job or wire in a dedicated manual-test job.

🤖 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/docx/parser_integration_test.go` at line 1, The DOCX
integration test file is excluded from the CI test run because it is guarded by
the cgo/manual build tag. Update the Go test workflow so the `./build.sh --test`
path includes the `manual` tag, or add a dedicated job that runs the
manual-tagged tests; use the existing `parser_integration_test.go` build
constraint as the reference point when wiring this into CI.

@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (42a0faa) to head (fd9fe62).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16464      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

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

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

@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: 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/parser_test.go`:
- Around line 609-619: The Zoom=0 test only checks coordinates inside existing
positions, so it can pass even if ParseRaw returns no sections or positions.
Update the pdf parser test around ParseRaw/result.Sections to explicitly assert
that Zoom=0 still yields at least one section and at least one position before
iterating, then keep the NaN coordinate checks on those positions.
- Around line 582-596: Make the negative-FromPage test in parser_test.go
page-specific so it fails if ParseRaw starts at the wrong page. In the ParseRaw
test using NewParser, MockEngine, and MockDocAnalyzer, either leave content only
on page 0 and keep the existing assertion, or strengthen the assertions to
verify the returned section/text specifically comes from page 0 rather than any
populated page. Avoid having identical content on pages 1 and 2 when the test is
meant to validate the FromPage fallback behavior.
🪄 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: 6152ac02-45af-48f5-b64e-7020b31e2df4

📥 Commits

Reviewing files that changed from the base of the PR and between a4e9823 and b592625.

📒 Files selected for processing (2)
  • internal/deepdoc/parser/pdf/parser_test.go
  • internal/deepdoc/parser/pdf/renderer.go

Comment on lines +609 to +619
result, err := p.ParseRaw(context.Background(), eng, mockDLA)
if err != nil {
t.Fatalf("ParseRaw: %v", err)
}
for _, s := range result.Sections {
for _, pos := range s.Positions {
if math.IsNaN(pos.Left) || math.IsNaN(pos.Top) {
t.Error("Zoom=0 produced NaN coordinates")
}
}
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that Zoom=0 still produces at least one position.

If ParseRaw drops all sections or positions when Zoom=0, this loop never runs and the test passes without validating anything.

Suggested change
 	result, err := p.ParseRaw(context.Background(), eng, mockDLA)
 	if err != nil {
 		t.Fatalf("ParseRaw: %v", err)
 	}
+	foundPosition := false
 	for _, s := range result.Sections {
 		for _, pos := range s.Positions {
+			foundPosition = true
 			if math.IsNaN(pos.Left) || math.IsNaN(pos.Top) {
 				t.Error("Zoom=0 produced NaN coordinates")
 			}
 		}
 	}
+	if !foundPosition {
+		t.Fatal("expected at least one position to validate")
+	}
 }
📝 Committable suggestion

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

Suggested change
result, err := p.ParseRaw(context.Background(), eng, mockDLA)
if err != nil {
t.Fatalf("ParseRaw: %v", err)
}
for _, s := range result.Sections {
for _, pos := range s.Positions {
if math.IsNaN(pos.Left) || math.IsNaN(pos.Top) {
t.Error("Zoom=0 produced NaN coordinates")
}
}
}
result, err := p.ParseRaw(context.Background(), eng, mockDLA)
if err != nil {
t.Fatalf("ParseRaw: %v", err)
}
foundPosition := false
for _, s := range result.Sections {
for _, pos := range s.Positions {
foundPosition = true
if math.IsNaN(pos.Left) || math.IsNaN(pos.Top) {
t.Error("Zoom=0 produced NaN coordinates")
}
}
}
if !foundPosition {
t.Fatal("expected at least one position to validate")
}
🤖 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/parser_test.go` around lines 609 - 619, The
Zoom=0 test only checks coordinates inside existing positions, so it can pass
even if ParseRaw returns no sections or positions. Update the pdf parser test
around ParseRaw/result.Sections to explicitly assert that Zoom=0 still yields at
least one section and at least one position before iterating, then keep the NaN
coordinate checks on those positions.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 1, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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/crop_integration_test.go`:
- Around line 30-31: Update TestCrop_Regression_SnapshotPDFs to match the new
parser API: NewParser should be called with only the config, and parsing should
use ParseRaw with the engine and MockDocAnalyzer instead of Parse. Follow the
same pattern used in TestParse_CropSectionImages, and keep the test wired
through the parser symbols NewParser and ParseRaw so it compiles against the
updated interface.
🪄 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: 6972163f-f640-4a69-8875-bf70f2241870

📥 Commits

Reviewing files that changed from the base of the PR and between b592625 and ecea8b4.

📒 Files selected for processing (12)
  • internal/deepdoc/parser/pdf/batch_smoke_test.go
  • internal/deepdoc/parser/pdf/crop_integration_test.go
  • internal/deepdoc/parser/pdf/mock_engine.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/parser_pipeline_manual_test.go
  • internal/deepdoc/parser/pdf/pdfium_integration_test.go
  • internal/deepdoc/parser/pdf/pipeline_parity_test.go
  • internal/deepdoc/parser/pdf/scan_all_pdfs_test.go
  • internal/deepdoc/parser/pdf/table/table_construct.go
  • internal/deepdoc/parser/pdf/table_rotate_integration_test.go
  • internal/deepdoc/parser/pdf/text_dump_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • internal/deepdoc/parser/pdf/pdfium_integration_test.go
  • internal/deepdoc/parser/pdf/table_rotate_integration_test.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/pipeline_parity_test.go
  • internal/deepdoc/parser/pdf/batch_smoke_test.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/table/table_construct.go

@xugangqiang xugangqiang added ci Continue Integration and removed ci Continue Integration labels Jul 1, 2026
@xugangqiang
xugangqiang marked this pull request as draft July 1, 2026 13:23
@xugangqiang
xugangqiang marked this pull request as ready for review July 1, 2026 13:24

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 2, 2026
@yuzhichang
yuzhichang merged commit 5bc4753 into infiniflow:main Jul 2, 2026
5 of 8 checks passed
@xugangqiang
xugangqiang deleted the feat/oss-parser-no-post branch August 7, 2026 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants