Skip to content

Fix MinerU parser page range handling - #16600

Closed
ayame-selachan wants to merge 7 commits into
infiniflow:0.27.xfrom
ayame-selachan:fix/mineru-page-range
Closed

ayame-selachan wants to merge 7 commits into
infiniflow:0.27.xfrom
ayame-selachan:fix/mineru-page-range

Conversation

@ayame-selachan

Copy link
Copy Markdown

What this PR changes

This PR makes the MinerU parser respect RAGFlow's PDF page-range tasks.

Currently, by_mineru(...) receives from_page and to_page, but those values are not passed into MinerUParser.parse_pdf(...). The MinerU API request then uses fixed values:

"start_page_id": 0,
"end_page_id": 99999,

This means every split RAGFlow task can parse the whole PDF, causing duplicate chunks.

Changes

  • Pass from_page and to_page from rag/app/naive.py to MinerUParser.parse_pdf(...).
  • Add start_page_id and end_page_id to MinerUParseOptions.
  • Convert RAGFlow's page range into MinerU API page IDs.
  • Send the converted page range to /file_parse.
  • Delay page image rendering until after MinerU output is read.
  • Handle MinerU output where page_idx may be either original-PDF-based or relative to start_page_id.

Why this is needed

When a PDF is split into tasks like:

Page(1~13)
Page(13~25)
Page(25~32)

the MinerU parser should parse only each assigned page range. Without this, all tasks may produce identical block counts and duplicated chunks.

Testing

Local syntax check:

python -m py_compile rag/app/naive.py deepdoc/parser/mineru_parser.py

Manual validation performed on a PDF parsed with MinerU:

  • Before fix: each page-range task parsed the same full-PDF block/image count.
  • After fix: each MinerU request sends the task-specific start_page_id and end_page_id.

Notes

This PR does not change the chunking strategy itself. It only ensures the MinerU API is called with the intended page range.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d8b7f0f8-c09c-4419-8d7d-7ccc6fe0ceca

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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

This PR adds page-range support to MinerU parsing. Page bounds flow from the caller through parse_pdf and the MinerU API, while image rendering is selected after output page indices are read.

Changes

MinerU Page-Range Support

Layer / File(s) Summary
Page-range options and API wiring
deepdoc/parser/mineru_parser.py
MinerUParseOptions carries page bounds, and the MinerU request uses them instead of fixed values.
parse_pdf range computation and wiring
deepdoc/parser/mineru_parser.py, rag/app/naive.py
parse_pdf accepts and normalizes from_page/to_page, while the MinerU path forwards the requested range.
Output-driven image rendering
deepdoc/parser/mineru_parser.py
Image generation is deferred until output parsing and then targets either the full document or the requested window based on page_idx values.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change to MinerU page-range handling.
Description check ✅ Passed The description clearly explains the problem, solution, rationale, and testing, satisfying the required summary section.
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.

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

A rabbit hops from page to page,
Bounds now guide the MinerU stage.
The API follows the window in view,
And images render the right pages too. 🐇

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

🧹 Nitpick comments (1)
deepdoc/parser/mineru_parser.py (1)

851-854: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Full-document image rendering per split task is wasteful.

In branch A, __images__(pdf, zoomin=1) renders every page of the PDF even though only [start_page_id, end_page_id] was parsed. For a large PDF split into many tasks this is roughly O(n²) rendering work and memory. Consider bounding rendering to max(page_indices) + 1 (or the requested window) while keeping the coordinate base consistent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/parser/mineru_parser.py` around lines 851 - 854, The image rendering
path in mineru_parser’s __images__ call is rendering the full PDF in the branch
where page_indices are already known, which causes unnecessary work for split
tasks. Update this logic to bound rendering to the parsed window or to
max(page_indices) + 1 while keeping the page coordinate base consistent, and
keep the existing start_page_id/end_page_id handling in MineruParser aligned
with __images__.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@deepdoc/parser/mineru_parser.py`:
- Around line 364-365: The page-tag generation in _line_tag() is adding
self.page_from too early, which breaks render-relative numbering for split-page
MinerU outputs. Remove the self.page_from offset from _line_tag() so tags stay
zero-based relative to the rendered window, and let extract_positions() continue
converting back to page indices while crop() remains the only place that
reintroduces self.page_from for absolute positions.

---

Nitpick comments:
In `@deepdoc/parser/mineru_parser.py`:
- Around line 851-854: The image rendering path in mineru_parser’s __images__
call is rendering the full PDF in the branch where page_indices are already
known, which causes unnecessary work for split tasks. Update this logic to bound
rendering to the parsed window or to max(page_indices) + 1 while keeping the
page coordinate base consistent, and keep the existing start_page_id/end_page_id
handling in MineruParser aligned with __images__.
🪄 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: 3fe4164a-0185-4d4b-b6a8-1771ff1d5bf2

📥 Commits

Reviewing files that changed from the base of the PR and between 994b603 and 8628100.

📒 Files selected for processing (2)
  • deepdoc/parser/mineru_parser.py
  • rag/app/naive.py

Comment thread deepdoc/parser/mineru_parser.py Resolved

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
deepdoc/parser/mineru_parser.py (1)

733-758: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Remove the duplicated parse_pdf() parameter block.

The current signature contains two parameter lists, so this file will not parse. Keep one signature and include the new from_page / to_page keyword-only parameters.

Proposed fix
 def parse_pdf(
-            self,
-            filepath: str | PathLike[str],
-            binary: BytesIO | bytes,
-            callback: Optional[Callable] = None,
-            *,
-            output_dir: Optional[str] = None,
-            backend: str = "pipeline",
-            server_url: Optional[str] = None,
-            delete_output: bool = True,
-            parse_method: str = "raw",
-            from_page: int = 0,
-            to_page: int = MAXIMUM_PAGE_NUMBER,
-            **kwargs,
-        self,
+        self,
         filepath: str | PathLike[str],
         binary: BytesIO | bytes,
         callback: Optional[Callable] = None,
         *,
         output_dir: Optional[str] = None,
         backend: str = "pipeline",
         server_url: Optional[str] = None,
         delete_output: bool = True,
         parse_method: str = "raw",
+        from_page: int = 0,
+        to_page: int = MAXIMUM_PAGE_NUMBER,
         **kwargs,
     ) -> tuple:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/parser/mineru_parser.py` around lines 733 - 758, The parse_pdf
signature is duplicated and currently contains two parameter blocks, which
breaks parsing. In mineru_parser.py, clean up parse_pdf so it has only one
function header, and keep the added keyword-only from_page and to_page
parameters alongside the existing filepath, binary, callback, output_dir,
backend, server_url, delete_output, and parse_method arguments. Make sure the
final signature is syntactically valid and there are no repeated self/parameter
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.

Outside diff comments:
In `@deepdoc/parser/mineru_parser.py`:
- Around line 733-758: The parse_pdf signature is duplicated and currently
contains two parameter blocks, which breaks parsing. In mineru_parser.py, clean
up parse_pdf so it has only one function header, and keep the added keyword-only
from_page and to_page parameters alongside the existing filepath, binary,
callback, output_dir, backend, server_url, delete_output, and parse_method
arguments. Make sure the final signature is syntactically valid and there are no
repeated self/parameter sections.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e5b92082-91a0-4148-814b-7f3b4986f9ca

📥 Commits

Reviewing files that changed from the base of the PR and between 33c9ec7 and 616ed3a.

📒 Files selected for processing (1)
  • deepdoc/parser/mineru_parser.py

@wangq8 wangq8 added the ci Continue Integration label Jul 6, 2026
@wangq8

wangq8 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

please fix lefthook format - @ayame-selachan

@codecov

codecov Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (0.27.x@4391e03). Learn more about missing BASE report.

Additional details and impacted files
@@            Coverage Diff            @@
##             0.27.x   #16600   +/-   ##
=========================================
  Coverage          ?   93.16%           
=========================================
  Files             ?       10           
  Lines             ?      717           
  Branches          ?      118           
=========================================
  Hits              ?      668           
  Misses            ?       29           
  Partials          ?       20           

☔ 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.

@ayame-selachan

Copy link
Copy Markdown
Author

please fix lefthook format - @ayame-selachan

Thanks for the reminder. I merged the latest main branch and fixed the lefthook formatting issues, including removing the duplicated MinerU parse_pdf signature and configuration block introduced during conflict resolution. The ragflow_preflight check is now passing. Could you please take another look when convenient?

@Js-Man-H5

Js-Man-H5 commented Jul 15, 2026 •

Copy link
Copy Markdown

This problem, which currently makes minerU almost unusable, when can it be fixed, please fix it as soon as possible @wangq8

@JinHai-CN

Copy link
Copy Markdown
Member

@ayame-selachan would you please resolve the conflicts?

@JinHai-CN JinHai-CN assigned JinHai-CN and unassigned xugangqiang Aug 31, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

Thanks for the contribution. Reviewing against current main, here are the findings:

1. Superseded by main (blocker)

This page-range bug is already fixed on main via later PRs (#16703, #18617). main already:

  • passes the page range from by_mineru (page_from=from_page, page_to=min(to_page, MAXIMUM_PAGE_NUMBER)), and
  • translates it at the API boundary in _run_mineru_api (end_page_id = 99999 if page_to >= MAXIMUM_PAGE_NUMBER else page_to - 1), and
  • removed start_page_id/end_page_id from MinerUParseOptions.

This PR still adds from_page/to_page params and start_page_id/end_page_id fields using different names, so it conflicts with main and cannot be cleanly rebased. Recommend closing in favor of the existing main fix.

2. No automated tests

Only py_compile + manual validation. The half-open → inclusive conversion, the MAXIMUM_PAGE_NUMBER sentinel, and the windowed-render branch are pure logic that should be unit-tested (there is already a stub-loading fixture pattern in test/unit_test/deepdoc/parser/test_mineru_parser.py). If a follow-up is opened, please add tests.

3. Fragile dual-branch render heuristic (carried from this PR)

mineru_parser.py selects full-document vs windowed rendering based on min(page_indices) >= start_page_id to guess whether MinerU returns original or relative page_idx. This is heuristic only — safe for the standard splitter by coincidence, but can misclassify under large task_page_size or custom pages ranges, causing out-of-range indices and silently dropped crops. main avoids this with a single windowed-render path + coordinate-space helpers.

4. Residual concern for main (not a blocker for this PR)

main unconditionally renders the window and indexes self.page_images[page_idx] directly. If a deployed MinerU version returns original (non-window-relative) page_idx, main would also hit out-of-range/shifted crops. This is exactly the version-difference this PR tried to handle and is currently unaddressed on main — worth a dedicated fix/verification there.

@JinHai-CN
JinHai-CN changed the base branch from main to 0.27.x October 9, 2026 04:47
@JinHai-CN

Copy link
Copy Markdown
Member

If you are still working on this PR, please re-open it.

@JinHai-CN JinHai-CN closed this Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants