Skip to content

feat(MinerU):Add support for MinerU table and image chunk classification - #16703

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
Aeovy:aeovy/feat-mineruparser
Aug 19, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
Aeovy:aeovy/feat-mineruparser

Conversation

@Aeovy

@Aeovy Aeovy commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Fix MinerU table and image chunk classification

Summary

This PR fixes two issues with MinerU PDF parser where table and image chunks were not properly classified or associated:

  1. Table chunks were incorrectly classified as text instead of table
  2. Image chunks were missing image resource association and classified as text

Background

#16118 fixed table HTML tag sanitization, but did not add chunk type parsing in mineru_parser, so table chunks were still classified as text.

#14946 implemented VLM-based image description for MinerU, but did not mount image resources to Chunks.

This PR connects the missing piece: processing mineru_media_blocks in the parser pipeline to properly classify and associate table and image chunks.

Changes

deepdoc/parser/mineru_parser.py

  • Added chunk type detection and classification for tables and images in parse_pdf()
  • Tables (identified by <table> tags) are now returned with proper type information
  • Images (identified by <img> tags) are extracted with position data and associated with their VLM-generated captions

rag/flow/parser/parser.py

  • Updated MinerU parsing branch to process mineru_media_blocks return value
  • Tables → layout_type: "table", text contains HTML content
  • Images → layout_type: "figure", text contains VLM description, image stores the image object

Before & After

Table Classification

Table Before (v0.26.3)

O2

Table After

C2

Tables are now correctly classified as table type instead of text.

Image Association

Image Before (v0.26.3)

O1

Image After

C1

Images are now properly associated with their resources and classified as image type.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. labels Jul 7, 2026
@coderabbitai

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

MinerU parsing now caches page metadata, normalizes content, produces table and image media blocks, and returns them to downstream parsing. Position handling preserves unpositioned media, while vision enrichment is limited to image sections and raw parsing paths.

Changes

MinerU Media Parsing

Layer / File(s) Summary
Rendering and media assembly
deepdoc/parser/mineru_parser.py
Caches page images and dimensions, handles rendering failures, normalizes content, assembles sections, and returns searchable table/image media blocks.
Downstream media and position flow
rag/flow/parser/parser.py, rag/app/naive.py, rag/app/manual.py, rag/flow/parser/utils.py, rag/nlp/__init__.py, deepdoc/parser/figure_parser.py
Consumes media blocks, preserves missing positions, aligns figure metadata, and applies vision enrichment only to images and raw MinerU parsing.
Parser and enrichment validation
test/unit_test/deepdoc/parser/test_mineru_parser.py, test/unit_test/rag/flow/parser/test_media_vision.py, test/unit_test/rag/test_naive_mineru.py
Tests rendering fallbacks, media positions, image-only vision processing, and raw versus non-raw enrichment paths.

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

Sequence Diagram(s)

sequenceDiagram
  participant Parser
  participant MinerUParser
  participant MediaBlocks
  participant VisionWrapper
  Parser->>MinerUParser: parse_pdf
  MinerUParser->>MediaBlocks: build table and image blocks
  MediaBlocks-->>Parser: return sections and media blocks
  Parser->>Parser: append media bboxes
  Parser->>VisionWrapper: enrich raw image media
  VisionWrapper-->>Parser: return enriched image chunks
Loading

Possibly related PRs

Suggested labels: 💞 feature, 🧪 test

Suggested reviewers: xugangqiang, zcxggmu

Poem

A rabbit watched pages render bright,
Tables and figures took flight.
Images found vision, positions stayed true,
Media blocks hopped neatly through.
“Parse on!” cried the bunny tonight. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: adding MinerU table and image chunk classification support.
Description check ✅ Passed The description includes the required Summary section and provides useful background, change details, and examples.
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.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks

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

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

756-784: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add logging for the new media-block generation flow.

_transfer_to_media_blocks is a new flow that resolves images and builds table/image chunks but emits no logs (e.g., count of media blocks produced, or when a media type is skipped). A debug/info line here would aid observability, consistent with the surrounding parser code that already logs block counts.

As per coding guidelines: **/*.py: "Add logging for new flows".

🤖 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 756 - 784, Add logging inside
_transfer_to_media_blocks to cover this new media-block generation flow, since
it currently resolves tables/images and returns silently. Use the existing
parser logger pattern in MinerUParser and emit a debug/info message when a media
item is skipped (for unsupported types or disabled tables) and a summary count
of media blocks produced before returning. Keep the log placement close to the
processing in _transfer_to_media_blocks so the behavior is easy to trace
alongside _normalize_output_type, _resolve_output_image, _build_table_text, and
_build_image_texts.

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 `@rag/flow/parser/parser.py`:
- Around line 421-434: Figure blocks without an image can still be emitted from
the parser and later hit markdown rendering where VLM.image2base64 expects
b["image"], causing a KeyError. Update the parser logic in the
mineru_media_blocks handling to either skip those image-less figure boxes or
flatten them to text-only entries before appending to bboxes, and ensure the
downstream writer path in VLM/image rendering only processes figure boxes when
an image key exists.

---

Nitpick comments:
In `@deepdoc/parser/mineru_parser.py`:
- Around line 756-784: Add logging inside _transfer_to_media_blocks to cover
this new media-block generation flow, since it currently resolves tables/images
and returns silently. Use the existing parser logger pattern in MinerUParser and
emit a debug/info message when a media item is skipped (for unsupported types or
disabled tables) and a summary count of media blocks produced before returning.
Keep the log placement close to the processing in _transfer_to_media_blocks so
the behavior is easy to trace alongside _normalize_output_type,
_resolve_output_image, _build_table_text, and _build_image_texts.
🪄 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: 4cd47385-bdd8-4487-8e40-fa084bdb45fb

📥 Commits

Reviewing files that changed from the base of the PR and between f8f049e and e2da068.

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

Comment thread rag/flow/parser/parser.py Resolved
@Aeovy Aeovy changed the title feat(MinerU): Fix MinerU table and image chunk classification feat(MinerU):Add support for MinerU table and image chunk classification Jul 10, 2026
@gavinage

Copy link
Copy Markdown

相同的问题!

@yingfeng yingfeng added the ci Continue Integration label Jul 22, 2026
@yingfeng
yingfeng requested a review from xugangqiang July 22, 2026 06:27
@xugangqiang

Copy link
Copy Markdown
Contributor

Thanks for the PR. I reviewed the changes against mineru_parser.py and rag/flow/parser/parser.py. Overall the direction is correct — the missing link for MinerU table/image chunk classification and image-resource mounting is now connected.

What it fixes

  • Tables are now emitted as layout_type: "table" (→ doc_type_kwd: table) and images as layout_type: "figure" with the image resource mounted, so they render via VLM.image2base64 in markdown output.
  • VLM description is folded into the chunk text via _build_image_texts, so figure chunks become searchable.

Concerns worth addressing (not necessarily blockers)

  1. Double VLM inference. MinerU already generates vlm_description in _enhance_images_with_vlm, and enhance_media_sections_with_vision (rag/flow/parser/utils.py:162) will run VLM again on the same image (and now also on tables) when a VLM model is configured, then concatenate the result to text (utils.py:207). This adds cost/latency and can duplicate descriptions. We should skip the second pass for MinerU-sourced media (e.g. a marker flag) or reuse the existing vlm_description.
  2. Fake position when bbox is missing. _transfer_to_media_blocks falls back to [(0,0,0,0,0)]; parser.py:511 turns that into a real [[1,0,0,0,0]]. The lines path only writes positions when actually present. Suggest omitting positions when none exist.
  3. Memory. _load_image_from_path loads the full MinerU-rendered PNG into memory per table/image, vs. the previous crop() slice. Worth considering crop reuse or resizing for docs with many media blocks.
  4. Latent paper duplication. The skip guard is parse_method != "paper". Production always uses pipeline, so no dup today, but if paper is ever wired up, table/image would appear in both lines and media_blocks.
  5. No tests for _transfer_to_media_blocks (table/image/no-bbox/no-caption branches).

Question for the author
Would you prefer to:

  • (A) merge this PR as-is and open a follow-up issue to address the items above, or
  • (B) add one more commit to this PR that resolves the double-VLM pass, the fake-position case, and adds the missing unit tests before merging?

I'm happy to help with either path.

@xugangqiang

Copy link
Copy Markdown
Contributor

@Aeovy Could you please also help to fix CI failure? - I guess this may be a wrong test and your fix expose the bad behavior.

=================================== FAILURES ===================================
____ test_read_output_enriches_cross_page_table_positions_from_middle_json _____
test/unit_test/deepdoc/parser/test_mineru_parser.py:340: in test_read_output_enriches_cross_page_table_positions_from_middle_json
assert len(sections) == 1
E assert 0 == 1
E + where 0 = len([])
_ test_read_output_keeps_original_tag_when_middle_json_has_single_table_position _
test/unit_test/deepdoc/parser/test_mineru_parser.py:469: in test_read_output_keeps_original_tag_when_middle_json_has_single_table_position
assert len(sections) == 1
E assert 0 == 1
E + where 0 = len([])
=========================== short test summary info ===========================

@Aeovy

Aeovy commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

@Aeovy Could you please also help to fix CI failure? - I guess this may be a wrong test and your fix expose the bad behavior.

=================================== FAILURES =================================== ____ test_read_output_enriches_cross_page_table_positions_from_middle_json _____ test/unit_test/deepdoc/parser/test_mineru_parser.py:340: in test_read_output_enriches_cross_page_table_positions_from_middle_json assert len(sections) == 1 E assert 0 == 1 E + where 0 = len([]) _ test_read_output_keeps_original_tag_when_middle_json_has_single_table_position _ test/unit_test/deepdoc/parser/test_mineru_parser.py:469: in test_read_output_keeps_original_tag_when_middle_json_has_single_table_position assert len(sections) == 1 E assert 0 == 1 E + where 0 = len([]) =========================== short test summary info ===========================

Thanks for reviewing,I will add few more commits to this pr to fix them this week :)

@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)
deepdoc/parser/mineru_parser.py (1)

897-897: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: implicit Optional on parse_method.

parse_method: str = None should be parse_method: Optional[str] = None per PEP 484 (flagged by Ruff RUF013). Cosmetic, no runtime impact.

🤖 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` at line 897, Update the
_transfer_to_sections method annotation so parse_method is typed as
Optional[str] while retaining its existing None default and runtime behavior.

Source: Linters/SAST tools

🤖 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 941-971: Update _transfer_to_media_blocks so missing or invalid
position data produces no positions rather than the synthetic page-0 zero-bbox
fallback. Preserve valid results from extract_positions, and ensure downstream
media blocks receive an empty positions collection when no real bounding box
exists.
- Around line 863-870: The _build_table_text method currently returns "FAILED TO
PARSE TABLE" without recording the failure. Before returning this fallback when
no usable table content exists, log a diagnostic message through the parser’s
existing logging mechanism, while preserving the current successful text
assembly and fallback return value.
- Line 908: Update parse_pdf and _transfer_to_media_blocks so parse_method is
passed into media-block conversion; when parse_method is "paper", exclude IMAGE
and TABLE outputs from media blocks, while preserving existing behavior for
other methods and non-media content.

---

Nitpick comments:
In `@deepdoc/parser/mineru_parser.py`:
- Line 897: Update the _transfer_to_sections method annotation so parse_method
is typed as Optional[str] while retaining its existing None default and runtime
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 Plus

Run ID: d42680d8-c3f6-47ab-af4a-7926e32ddc7d

📥 Commits

Reviewing files that changed from the base of the PR and between 07e8007 and 162868a.

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

Comment thread deepdoc/parser/mineru_parser.py Resolved
Comment thread deepdoc/parser/mineru_parser.py Resolved
Comment thread deepdoc/parser/mineru_parser.py Resolved
@Aeovy
Aeovy force-pushed the aeovy/feat-mineruparser branch from 162868a to 7dddf1a Compare July 30, 2026 06:42

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

🧹 Nitpick comments (6)
test/unit_test/deepdoc/parser/test_mineru_parser.py (1)

133-134: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the absence assertion for the removed VLM helper.

assert not hasattr(parser, "_enhance_images_with_vlm") guards a method that no longer exists; it pins a deleted API rather than current behavior.

As per coding guidelines, "remove tests that protect obsolete behavior".

♻️ Proposed change
     assert image_texts == ["Figure caption", "Figure footnote"]
-    assert not hasattr(parser, "_enhance_images_with_vlm")
🤖 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 `@test/unit_test/deepdoc/parser/test_mineru_parser.py` around lines 133 - 134,
Remove the obsolete hasattr assertion from the parser test, leaving the image
text assertions unchanged. Do not add a replacement assertion for the deleted
_enhance_images_with_vlm helper.

Source: Coding guidelines

deepdoc/parser/mineru_parser.py (3)

936-952: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a case _ fallback to the match.

section is only bound inside the enumerated cases; today every reachable MinerUContentType is covered, but adding a new enum member would reuse the previous iteration's section value instead of failing loudly.

♻️ Proposed guard
                 case MinerUContentType.LIST:
                     list_items = output.get("list_items")
                     section = "\n".join(self._normalize_text_lines(list_items if isinstance(list_items, list) else None))
+                case _:
+                    self.logger.debug("[MinerU] Unhandled section type=%s", output.get("type"))
+                    continue
🤖 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 936 - 952, Update the match on
output_type in the section-building logic to add a case _ fallback that raises
an explicit error for unsupported MinerUContentType values, preventing section
from retaining a previous iteration’s value. Keep the existing enumerated cases
unchanged.

922-922: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fix the implicit Optional annotation.

parse_method: str = None is invalid typing (PEP 484) and is flagged by Ruff RUF013.

♻️ Proposed fix
-    def _transfer_to_sections(self, outputs: list[dict[str, Any]], parse_method: str = None, table_enable: bool = True):
+    def _transfer_to_sections(self, outputs: list[dict[str, Any]], parse_method: str | None = None, table_enable: bool = True):
🤖 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` at line 922, Update the
_transfer_to_sections method signature so parse_method explicitly allows None
using the project's supported Optional/nullable annotation style, while
preserving its existing default and behavior.

Source: Linters/SAST tools


409-413: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Log when the target page size is unavailable.

_content_bbox_to_page_space warns and bails when _get_page_size returns None, but here the bbox silently passes through unscaled, so a downstream wrong position has no diagnostic trail.

As per coding guidelines, "Add logging for new flows" applies to **/*.py.

🪵 Proposed tweak
         target_page_size = self._get_page_size(page_idx)
-        if target_page_size is not None:
+        if target_page_size is None:
+            self.logger.warning("[MinerU] Missing page size for page_idx=%s; using raw middle bbox=%s", page_idx, bbox)
+        else:
             page_width, page_height = target_page_size
🤖 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 409 - 413, Update
_middle_bbox_to_page_space to log a warning and return the existing
unscaled/fallback result when _get_page_size(page_idx) returns None, matching
_content_bbox_to_page_space’s diagnostic behavior; preserve the current scaling
path when target_page_size is available.

Source: Coding guidelines

rag/flow/parser/parser.py (1)

446-451: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Log instead of silently swallowing the position conversion failure.

Positions here are produced by MinerUParser._transfer_to_media_blocks as fixed 5-tuples, so an exception means malformed upstream data — dropping it silently makes that undebuggable. Flagged by Ruff S110/BLE001.

As per coding guidelines, "Add logging for new flows" applies to **/*.py.

🪵 Proposed fix
                 if positions:
                     try:
                         box["positions"] = [[p[0] + 1, p[1], p[2], p[3], p[4]] for p in positions]
-                    except Exception:
-                        pass
+                    except Exception as e:
+                        logging.warning("MinerU media block has malformed positions %s: %s", positions, e)
🤖 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 `@rag/flow/parser/parser.py` around lines 446 - 451, Update the exception
handler in the position conversion block within
MinerUParser._transfer_to_media_blocks to log the conversion failure instead of
silently passing. Use the module’s existing logger and include the exception
details, while preserving the current behavior of still appending the box
without converted positions.

Sources: Coding guidelines, Linters/SAST tools

test/unit_test/rag/flow/parser/test_media_vision.py (1)

14-69: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Four copies of the same AST-exec symbol loader across the new tests. Each helper parses a source file, picks a single top-level node by name, compiles it, and execs it into a stubbed namespace — differing only in module path, symbol name, namespace stubs, and a hardcoded parents[...] depth. Extract one shared _load_symbol(relative_module_path, symbol_name, namespace) helper into a common test utility.

  • test/unit_test/rag/flow/parser/test_media_vision.py#L14-L69: replace _load_media_vision_function, _load_vision_figure_parser_class, and _load_pdf_context_function with calls to the shared helper, keeping only their distinct namespace stubs.
  • test/unit_test/rag/test_naive_mineru.py#L14-L29: replace _load_by_mineru with the shared helper and drop the duplicate parents[3] repo-root computation.

As per coding guidelines, "collapse duplicate implementations".

🤖 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 `@test/unit_test/rag/flow/parser/test_media_vision.py` around lines 14 - 69,
Extract the shared AST symbol-loading logic into a common test utility helper
such as _load_symbol, centralizing repository-root resolution, source parsing,
top-level symbol lookup, compilation, and execution. In
test/unit_test/rag/flow/parser/test_media_vision.py lines 14-69, replace
_load_media_vision_function, _load_vision_figure_parser_class, and
_load_pdf_context_function with calls to the helper while preserving their
namespace stubs. In test/unit_test/rag/test_naive_mineru.py lines 14-29, replace
_load_by_mineru with the helper and remove its duplicate parents[3] root
calculation.

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.

Nitpick comments:
In `@deepdoc/parser/mineru_parser.py`:
- Around line 936-952: Update the match on output_type in the section-building
logic to add a case _ fallback that raises an explicit error for unsupported
MinerUContentType values, preventing section from retaining a previous
iteration’s value. Keep the existing enumerated cases unchanged.
- Line 922: Update the _transfer_to_sections method signature so parse_method
explicitly allows None using the project's supported Optional/nullable
annotation style, while preserving its existing default and behavior.
- Around line 409-413: Update _middle_bbox_to_page_space to log a warning and
return the existing unscaled/fallback result when _get_page_size(page_idx)
returns None, matching _content_bbox_to_page_space’s diagnostic behavior;
preserve the current scaling path when target_page_size is available.

In `@rag/flow/parser/parser.py`:
- Around line 446-451: Update the exception handler in the position conversion
block within MinerUParser._transfer_to_media_blocks to log the conversion
failure instead of silently passing. Use the module’s existing logger and
include the exception details, while preserving the current behavior of still
appending the box without converted positions.

In `@test/unit_test/deepdoc/parser/test_mineru_parser.py`:
- Around line 133-134: Remove the obsolete hasattr assertion from the parser
test, leaving the image text assertions unchanged. Do not add a replacement
assertion for the deleted _enhance_images_with_vlm helper.

In `@test/unit_test/rag/flow/parser/test_media_vision.py`:
- Around line 14-69: Extract the shared AST symbol-loading logic into a common
test utility helper such as _load_symbol, centralizing repository-root
resolution, source parsing, top-level symbol lookup, compilation, and execution.
In test/unit_test/rag/flow/parser/test_media_vision.py lines 14-69, replace
_load_media_vision_function, _load_vision_figure_parser_class, and
_load_pdf_context_function with calls to the helper while preserving their
namespace stubs. In test/unit_test/rag/test_naive_mineru.py lines 14-29, replace
_load_by_mineru with the helper and remove its duplicate parents[3] root
calculation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 97e2180b-c0a1-4254-835c-24c401762cd7

📥 Commits

Reviewing files that changed from the base of the PR and between 162868a and 7dddf1a.

📒 Files selected for processing (10)
  • deepdoc/parser/figure_parser.py
  • deepdoc/parser/mineru_parser.py
  • rag/app/manual.py
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • rag/flow/parser/utils.py
  • rag/nlp/__init__.py
  • test/unit_test/deepdoc/parser/test_mineru_parser.py
  • test/unit_test/rag/flow/parser/test_media_vision.py
  • test/unit_test/rag/test_naive_mineru.py

@Aeovy

Aeovy commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor Author

I have not changed the image-loading logic to optimize memory usage, as doing so would require more extensive testing and careful technical evaluation. I suggest tracking this as a known issue and addressing it separately. In practice, it is unlikely to affect normal operation in most cases.
Additionally, I fixed an issue that could cause bounding boxes to shift. In my testing, the bounding boxes of PDF elements are now accurate.
image
image

Mathematical formulas may still have slightly inaccurate boundaries, but their positions are correct.
image

@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 (2)
deepdoc/parser/mineru_parser.py (2)

976-983: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Skip disabled tables before processing their positions.

When table_enable=False, _line_tag() still runs first. Malformed table bbox data can therefore abort parsing even though table processing is disabled; valid tables also incur unnecessary work. Move this gate immediately after type normalization.

Proposed fix
             if output_type not in {MinerUContentType.TABLE, MinerUContentType.IMAGE}:
                 self.logger.debug("[MinerU] Skip non-media type=%s", output.get("type"))
                 continue
+            if output_type == MinerUContentType.TABLE and not table_enable:
+                self.logger.debug("[MinerU] Skip table (table_enable=False)")
+                continue

             position_tag = self._line_tag(output) if "page_idx" in output and "bbox" in output else ""
             positions = [(pages[-1], left, right, top, bottom) for pages, left, right, top, bottom in self.extract_positions(position_tag) if pages]

             if output_type == MinerUContentType.TABLE:
-                if not table_enable:
-                    self.logger.debug("[MinerU] Skip table (table_enable=False)")
-                    continue
🤖 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 976 - 983, Move the
table_enable=False guard in the output-processing flow to immediately after
output_type normalization, before computing position_tag or calling
extract_positions. Preserve the existing skip log and continue behavior, while
ensuring disabled tables never invoke _line_tag, extract_positions, or
_build_table_text.

362-374: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Bound the raster cache to the requested page range.

This materializes every PDF page and parse_pdf invokes it without page_from/page_to at Line 1061. A one-page parse therefore still retains the full document in memory, creating avoidable memory spikes for large PDFs. Render only the requested pages or lazily cache media crops, while preserving absolute-page coordinate mapping.

🤖 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 362 - 374, The PDF raster cache
in the parser initialization must be limited to the requested page range. Update
the flow around the page-loading logic and the parse_pdf call site so
page_from/page_to are propagated instead of defaulting to the full document,
while preserving absolute page indices in page_sizes and coordinate mapping.
Ensure page_images contains only requested pages, avoiding full-document
materialization for single-page parses.
🧹 Nitpick comments (1)
test/unit_test/deepdoc/parser/test_mineru_parser.py (1)

154-170: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert VLM behavior rather than attribute absence.

assert not hasattr(parser, "_enhance_images_with_vlm") only protects against one implementation shape; a renamed or delegated VLM call would still pass. Spy on the enrichment boundary, or keep this test focused on the caption/footnote output contract. (raw.githubusercontent.com)

🤖 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 `@test/unit_test/deepdoc/parser/test_mineru_parser.py` around lines 154 - 170,
Update test_build_image_texts_uses_only_mineru_caption_and_footnote to verify
behavior through the enrichment boundary rather than asserting absence of
_enhance_images_with_vlm; spy on any VLM enrichment call and assert it is not
invoked, while preserving the existing caption and footnote output assertion.
🤖 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 976-983: Move the table_enable=False guard in the
output-processing flow to immediately after output_type normalization, before
computing position_tag or calling extract_positions. Preserve the existing skip
log and continue behavior, while ensuring disabled tables never invoke
_line_tag, extract_positions, or _build_table_text.
- Around line 362-374: The PDF raster cache in the parser initialization must be
limited to the requested page range. Update the flow around the page-loading
logic and the parse_pdf call site so page_from/page_to are propagated instead of
defaulting to the full document, while preserving absolute page indices in
page_sizes and coordinate mapping. Ensure page_images contains only requested
pages, avoiding full-document materialization for single-page parses.

---

Nitpick comments:
In `@test/unit_test/deepdoc/parser/test_mineru_parser.py`:
- Around line 154-170: Update
test_build_image_texts_uses_only_mineru_caption_and_footnote to verify behavior
through the enrichment boundary rather than asserting absence of
_enhance_images_with_vlm; spy on any VLM enrichment call and assert it is not
invoked, while preserving the existing caption and footnote output assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9c4e570a-8bd7-407e-b7ca-68a71af7a0b8

📥 Commits

Reviewing files that changed from the base of the PR and between 7dddf1a and 1863eab.

📒 Files selected for processing (2)
  • deepdoc/parser/mineru_parser.py
  • test/unit_test/deepdoc/parser/test_mineru_parser.py

@xugangqiang

Copy link
Copy Markdown
Contributor

@Aeovy pls check CI error - seems like Lefthook issue.

@Aeovy
Aeovy force-pushed the aeovy/feat-mineruparser branch from 072fdd5 to 5d57c83 Compare July 30, 2026 09:52
@codecov

codecov Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (c3153ba) to head (3d5a546).
⚠️ Report is 8 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16703   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

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

@Aeovy

Aeovy commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@Aeovy pls check CI error - seems like Lefthook issue.

fixed,I clicked the 'update branch' by accident

@xugangqiang

Copy link
Copy Markdown
Contributor

Review: MinerU table & image chunk classification (#16703)

Thanks for the contribution. I reviewed the current diff (via gh pr diff). The overall direction is right — moving MinerU tables/images into a dedicated media-block return value instead of letting them fall through as text sections is the correct fix, and the parser.py classification ternary ("table" if not isinstance(html_or_caption, list) else "figure") is correct. A few issues should be addressed before merge:

1. figure_parser.py discards real positions (and breaks its own new test)

In VisionFigureParser._extract_figures_info, the position-shape branch now does:

self.positions.append(None)   # was: self.positions.append(item[1])

This throws away the actual position metadata. Two consequences:

  • The else branch still does not append to self.positions, while the new strict assertion assert len(self.figures) == len(self.positions) requires them to match — any item reaching the else branch will now trip the assertion.
  • Position-dependent callers (e.g. table/image context placement) lose real coordinates.

It also contradicts the new test test_vision_figure_parser_preserves_empty_and_mixed_positions, which expects ((positioned_image, ["positioned"]), positioned) to be preserved — with None stored, that test fails.

Suggestion: restore self.positions.append(item[1]) in the if has_position_shape branch and add self.positions.append(None) to the else branch (or keep the previous has_positions guard) so the lengths stay consistent.

2. Divergence / duplication with current main

main already contains the consumer loop in rag/flow/parser/parser.py, but under the name odl_tables with the (correct) list-based ternary. This PR re-adds a parallel mineru_media_blocks consumer. After rebasing onto current main this will duplicate the media→bbox logic and conflict on the variable name. Recommended:

  • Rebase onto current main.
  • Keep only the producer side (_transfer_to_media_blocks, the _transfer_to_sections table/image skip, and the VLM refactor); let the existing odl_tables consumer handle the media→bbox conversion.
  • Align naming so we don't ship two copies of the same loop.

3. VLM for tables — behavioral change to confirm

enhance_media_sections_with_vision now filters doc_type_kwd != "image", so tables are no longer sent to VLM (they keep structured HTML). main currently enriches both image and table. This is a sensible choice, but it is a behavior change — please confirm it is intended and won't regress searchability of table content.

4. Unpositioned media is now retained (regression check)

rag/app/manual.py changed if not rows: → if not rows or not poss:, and rag/nlp/__init__.py now appends empty contexts for media without positions. Previously unpositioned tables/images were dropped; now they become independent searchable chunks. This increases chunk count and changes retrieval — please confirm this is the intended behavior.

5. Missing test coverage for the classification mapping

No unit test asserts the layout_type/doc_type_kwd mapping for the parser.py media loop (table → table → table doc_type, image → figure → image doc_type). Since this is the core of the PR, adding a focused test would prevent future regressions (and would have caught the inverted-ternary variant seen in an earlier revision of this diff).

Minor

  • _transfer_to_sections now defaults table_enable=True (was False). Changing a default is a smell; prefer keeping callers explicit.

Summary: The producer-side fix is valuable and the classification logic is correct. The blocking items are #1 (positions discarded + failing self-test) and #2 (rebase/duplication). Once those are resolved and the behavioral changes in #3/#4 are confirmed, this should be good to merge.

@Aeovy
Aeovy force-pushed the aeovy/feat-mineruparser branch from 5d57c83 to f536586 Compare July 31, 2026 03:06
@Aeovy

Aeovy commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

Review: MinerU table & image chunk classification (#16703)

Thanks for the contribution. I reviewed the current diff (via gh pr diff). The overall direction is right — moving MinerU tables/images into a dedicated media-block return value instead of letting them fall through as text sections is the correct fix, and the parser.py classification ternary ("table" if not isinstance(html_or_caption, list) else "figure") is correct. A few issues should be addressed before merge:

1. figure_parser.py discards real positions (and breaks its own new test)

In VisionFigureParser._extract_figures_info, the position-shape branch now does:

self.positions.append(None)   # was: self.positions.append(item[1])

This throws away the actual position metadata. Two consequences:

  • The else branch still does not append to self.positions, while the new strict assertion assert len(self.figures) == len(self.positions) requires them to match — any item reaching the else branch will now trip the assertion.
  • Position-dependent callers (e.g. table/image context placement) lose real coordinates.

It also contradicts the new test test_vision_figure_parser_preserves_empty_and_mixed_positions, which expects ((positioned_image, ["positioned"]), positioned) to be preserved — with None stored, that test fails.

Suggestion: restore self.positions.append(item[1]) in the if has_position_shape branch and add self.positions.append(None) to the else branch (or keep the previous has_positions guard) so the lengths stay consistent.

2. Divergence / duplication with current main

main already contains the consumer loop in rag/flow/parser/parser.py, but under the name odl_tables with the (correct) list-based ternary. This PR re-adds a parallel mineru_media_blocks consumer. After rebasing onto current main this will duplicate the media→bbox logic and conflict on the variable name. Recommended:

  • Rebase onto current main.
  • Keep only the producer side (_transfer_to_media_blocks, the _transfer_to_sections table/image skip, and the VLM refactor); let the existing odl_tables consumer handle the media→bbox conversion.
  • Align naming so we don't ship two copies of the same loop.

3. VLM for tables — behavioral change to confirm

enhance_media_sections_with_vision now filters doc_type_kwd != "image", so tables are no longer sent to VLM (they keep structured HTML). main currently enriches both image and table. This is a sensible choice, but it is a behavior change — please confirm it is intended and won't regress searchability of table content.

4. Unpositioned media is now retained (regression check)

rag/app/manual.py changed if not rows: → if not rows or not poss:, and rag/nlp/__init__.py now appends empty contexts for media without positions. Previously unpositioned tables/images were dropped; now they become independent searchable chunks. This increases chunk count and changes retrieval — please confirm this is the intended behavior.

5. Missing test coverage for the classification mapping

No unit test asserts the layout_type/doc_type_kwd mapping for the parser.py media loop (table → table → table doc_type, image → figure → image doc_type). Since this is the core of the PR, adding a focused test would prevent future regressions (and would have caught the inverted-ternary variant seen in an earlier revision of this diff).

Minor

  • _transfer_to_sections now defaults table_enable=True (was False). Changing a default is a smell; prefer keeping callers explicit.

Summary: The producer-side fix is valuable and the classification logic is correct. The blocking items are #1 (positions discarded + failing self-test) and #2 (rebase/duplication). Once those are resolved and the behavioral changes in #3/#4 are confirmed, this should be good to merge.

Thanks for the detailed review. I rebased the branch onto the current main and rechecked each item against the resulting diff.

  1. Figure positions

The code shown in the review does not match the current rebased HEAD. The position-shaped branch currently preserves the original value:

  if has_position_shape:
      ...
      self.positions.append(item[1])
  else:
      ...
      self.positions.append(None)

self.positions.append(item[1]) predates this PR and was not changed to None by the current commit series. The new None entry is only used by the fallback branch for the
legacy (image, descriptions) shape, where no position value exists.

Commit 8dbe32cd2 makes explicit empty positions ([]) a valid positioned shape and ensures that figures, descriptions, and positions remain aligned. _assemble()
distinguishes an explicit empty position list from the internal None sentinel. The regression test verifies that both [] and a real five-field position list are preserved
unchanged, and it passes.

  1. MinerU and OpenDataLoader consumers

I agree that the two loops have some source-level similarity, but I did not consolidate them in this feature PR because they are inside mutually exclusive provider branches.

mineru_media_blocks is assigned and consumed only in the parse_method == "mineru" branch. odl_tables is assigned and consumed only in the parse_method == "opendataloader"
branch. They cannot execute during the same _pdf() call, so there is no runtime duplication or variable-name conflict.

The existing odl_tables loop cannot consume MinerU's second parse_pdf() return value without moving the conversion outside both provider branches or introducing a provider-
neutral media contract. Simply removing the MinerU consumer would leave mineru_media_blocks unused and silently drop MinerU tables and images.

The paths also differ slightly: MinerU preserves all non-empty caption and description entries, while the current OpenDataLoader path keeps only the first list item. I therefore
kept the MinerU consumer scoped to this feature and would treat provider-neutral consolidation as a separate cross-provider refactor.

  1. VLM processing for tables

The image-only filter was not intended as a behavior change. Commit c84203e89 restores the current main behavior: enhance_media_sections_with_vision() processes both image
and table chunks. There is now no diff against main in rag/flow/parser/utils.py.

Tables retain their structured HTML, and the VLM description is appended to that searchable text. The focused test verifies that one image and one table each receive exactly one
VLM call.

The duplicate-inference issue is handled separately by making the caller own VLM enrichment: the MinerU parser no longer performs its own internal VLM pass. General/raw invokes
its wrapper once, while Manual and Paper defer to their existing wrappers.

  1. Unpositioned media

Retaining unpositioned media is intentional.

When MinerU provides no valid bbox, the media block now carries an empty position list instead of a fabricated zero-area bbox. Missing display coordinates should prevent PDF
overlay and context placement, but should not discard valid image captions, descriptions, or table HTML.

In Manual chunking, such media is excluded only from the position-sorted text-section merge. It remains in tbls and is tokenized as an independent searchable media chunk. The
context helper preserves it with empty surrounding context instead of indexing poss[0].

This changes chunk counts only for media whose position metadata is unavailable. Those chunks remain searchable and renderable, but do not receive misleading position metadata.

  1. Classification coverage

Commit cb81cc948 adds a focused regression test covering the production MinerU media consumer and normalization logic:

  • table HTML -> layout_type = "table" -> doc_type_kwd = "table"
  • image caption list -> layout_type = "figure" -> doc_type_kwd = "image"
  • image resource preservation
  • one-based page conversion
  • omission of positions when no real bbox exists

Minor

Commit f536586f4 restores _transfer_to_sections(..., table_enable=False), matching the previous default, and adds coverage for the default behavior.

@xugangqiang

Copy link
Copy Markdown
Contributor

Thanks for this — the direction is right and the net effect is positive. I checked out the branch locally, ran the new unit tests (24 passed), and diffed the runtime behavior against main. The core goal is genuinely achieved: MinerU tables now land as table chunks, images carry their resource, _transfer_to_sections correctly cedes ownership so nothing is duplicated, and you incidentally fixed two latent crashes (_line_tag KeyError when page_idx is absent, and the IndexError on item[1][0] for empty positions in VisionFigureParser._extract_figures_info).

Four things I'd like to see before merge.

1. deepdoc/parser/mineru_parser.py:952 — sanitization is now unconditional and silently deletes text

The gate changed from if not table_enable: section = self._sanitize_section_text(section) to an unconditional call. Since mineru_table_enable defaults to True, TEXT / CODE / EQUATION blocks are now tag-stripped, which they never were before on the default path.

Reproduced by running _transfer_to_sections(outputs, "raw", table_enable=True) on both branches with the same input:

input : "Use List<String> and a<b. 5 &lt; 6"  /  "template<typename T> void f();"

main  : ('Use List<String> and a<b. 5 &lt; 6', '@@1...##')
        ('template<typename T> void f();',      '@@1...##')

PR    : ('Use List and a<b. 5 < 6', '')
        ('template void f();',      '')

<String> and <typename T> are gone. Any technical PDF with generics, C++ templates, or LaTeX angle brackets loses content, with no warning. _sanitize_section_text was written to clean MinerU's table HTML — it should stay scoped to that. Either restore the if not table_enable: gate, or apply the sanitizer only in the TABLE branch of the match.

2. rag/flow/parser/parser.py:803 — markdown output can raise KeyError

The new media loop only sets the image key when the image is non-null:

if img is not None:
    box["image"] = img

but the markdown writer dereferences it unconditionally:

if b.get("layout_type", "") == "figure":
    mkdn += "\n![Image]({})".format(VLM.image2base64(b["image"]))

A MinerU image whose img_path fails to load and whose crop() fallback returns None — precisely the page-render-failure case this PR handles elsewhere — produces a figure box with no image, and markdown output blows up. Please use b.get("image") and skip rendering when it is None. (The same hazard exists on the pre-existing OpenDataLoader branch, so fixing it here covers both.)

3. The PR description no longer matches the change

The body says two files are touched (mineru_parser.py, rag/flow/parser/parser.py). The diff is 10 files / +712 −122 and includes several changes the description never mentions:

  • removal of _enhance_images_with_vlm, moving VLM enrichment to the callers (naive.py raw path, manual.py, paper.py, and flow's enhance_media_sections_with_vision)
  • __images__ now holds the process-global pdfplumber lock across open + full-document render (mineru_parser.py:366)
  • bbox projection falls back to page metadata on render failure, and returns None (dropping the position tag) when no page size is available
  • VisionFigureParser positions semantics changed to per-item alignment, allowing None / empty entries
  • empty-poss guard in rag/nlp/append_context2table_image4pdf
  • manual.py skips unpositioned media when folding tbls into sections

Please rewrite the description to cover the actual scope. Reviewers and anyone bisecting later will be reading it as the record of intent.

Separately: items 2–6 in that list are standalone robustness fixes with no coupling to table/image classification. Splitting them into a follow-up PR would make both easier to reason about and to bisect, though I won't block on that.

4. Add a regression test for a figure box with no image

The new tests are thorough on the parser side (render failure, shared lock, missing page size, empty positions), but nothing covers the consumer-side crash from item 2. Worth adding a case that feeds ((None, ["caption"]), []) through the media loop and asserts the markdown writer produces output instead of raising.


Once 1 and 2 are addressed this looks good to me. Happy to re-review.

@Aeovy

Aeovy commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for your thorough and patient review. It has been highly valuable in helping me identify multiple production-environment issues.

1. Unconditional Section Sanitization

Fixed in: 95914ba31

Sanitization is now exclusively owned by the TABLE branch:

  • Enabled tables are routed to media blocks and retain their structured HTML.
  • The table-as-text fallback is sanitized only when table extraction is disabled.

TEXT, CODE, EQUATION, and LIST blocks no longer pass through the HTML sanitizer. Their angle brackets and HTML entities are preserved exactly, including edge cases such as:

  • List<String>
  • template<typename T>
  • 5 &lt; 6
  • Literal XML-like text

Testing: Regression tests cover both table_enable=True and table_enable=False.

before

before

after

after

2. Missing Figure Image in Markdown Output

Fixed in: 6c4f30667

The shared Markdown writer now safely resolves images via b.get("image"). If the image key is absent or evaluates to None, the system logs a warning and gracefully skips the figure instead of calling VLM.image2base64().

While this edge case is extremely rare in production (I have not encountered it after parsing 1,000+ PDF documents in extensive local testing), this defensive check significantly enhances code robustness by preventing potential KeyError or AttributeError exceptions when downstream providers emit sparse or malformed figure metadata.

This resolves edge cases from MinerU, OpenDataLoader, and any other provider that emits a figure without an associated image resource. Tests verify:

  • Missing image key
  • Explicit image=None assignment
  • Correct warning emission
  • Preservation of downstream Markdown content
  • Unchanged rendering behavior for valid images

Additional Finding: Pre-existing MinerU CODE Path Formatting Issue

While validating the angle-bracket fixture, I identified a separate, pre-existing formatting inconsistency in the MinerU CODE path. RAGFlow currently concatenates code_body directly before code_caption without an explicit separator. This can push the caption behind its corresponding code block, resulting in output where a closing code fence (```) is immediately followed by the caption text.

This issue does not affect angle bracket handling and was not introduced by the sanitization fix. A complete resolution would require defining a clear ordering and separation strategy for code_caption, code_body, and code_footnote, potentially leveraging the child-block ordering from MinerU's intermediate JSON.

I will document this as a known issue and may address it in a separate PR.

Thanks for this — the direction is right and the net effect is positive. I checked out the branch locally, ran the new unit tests (24 passed), and diffed the runtime behavior against main. The core goal is genuinely achieved: MinerU tables now land as table chunks, images carry their resource, _transfer_to_sections correctly cedes ownership so nothing is duplicated, and you incidentally fixed two latent crashes (_line_tag KeyError when page_idx is absent, and the IndexError on item[1][0] for empty positions in VisionFigureParser._extract_figures_info).

Four things I'd like to see before merge.

1. deepdoc/parser/mineru_parser.py:952 — sanitization is now unconditional and silently deletes text

The gate changed from if not table_enable: section = self._sanitize_section_text(section) to an unconditional call. Since mineru_table_enable defaults to True, TEXT / CODE / EQUATION blocks are now tag-stripped, which they never were before on the default path.

Reproduced by running _transfer_to_sections(outputs, "raw", table_enable=True) on both branches with the same input:

input : "Use List<String> and a<b. 5 &lt; 6"  /  "template<typename T> void f();"

main  : ('Use List<String> and a<b. 5 &lt; 6', '@@1...##')
        ('template<typename T> void f();',      '@@1...##')

PR    : ('Use List and a<b. 5 < 6', '')
        ('template void f();',      '')

<String> and <typename T> are gone. Any technical PDF with generics, C++ templates, or LaTeX angle brackets loses content, with no warning. _sanitize_section_text was written to clean MinerU's table HTML — it should stay scoped to that. Either restore the if not table_enable: gate, or apply the sanitizer only in the TABLE branch of the match.

2. rag/flow/parser/parser.py:803 — markdown output can raise KeyError

The new media loop only sets the image key when the image is non-null:

if img is not None:
    box["image"] = img

but the markdown writer dereferences it unconditionally:

if b.get("layout_type", "") == "figure":
    mkdn += "\n![Image]({})".format(VLM.image2base64(b["image"]))

A MinerU image whose img_path fails to load and whose crop() fallback returns None — precisely the page-render-failure case this PR handles elsewhere — produces a figure box with no image, and markdown output blows up. Please use b.get("image") and skip rendering when it is None. (The same hazard exists on the pre-existing OpenDataLoader branch, so fixing it here covers both.)

3. The PR description no longer matches the change

The body says two files are touched (mineru_parser.py, rag/flow/parser/parser.py). The diff is 10 files / +712 −122 and includes several changes the description never mentions:

  • removal of _enhance_images_with_vlm, moving VLM enrichment to the callers (naive.py raw path, manual.py, paper.py, and flow's enhance_media_sections_with_vision)
  • __images__ now holds the process-global pdfplumber lock across open + full-document render (mineru_parser.py:366)
  • bbox projection falls back to page metadata on render failure, and returns None (dropping the position tag) when no page size is available
  • VisionFigureParser positions semantics changed to per-item alignment, allowing None / empty entries
  • empty-poss guard in rag/nlp/append_context2table_image4pdf
  • manual.py skips unpositioned media when folding tbls into sections

Please rewrite the description to cover the actual scope. Reviewers and anyone bisecting later will be reading it as the record of intent.

Separately: items 2–6 in that list are standalone robustness fixes with no coupling to table/image classification. Splitting them into a follow-up PR would make both easier to reason about and to bisect, though I won't block on that.

4. Add a regression test for a figure box with no image

The new tests are thorough on the parser side (render failure, shared lock, missing page size, empty positions), but nothing covers the consumer-side crash from item 2. Worth adding a case that feeds ((None, ["caption"]), []) through the media loop and asserts the markdown writer produces output instead of raising.

Once 1 and 2 are addressed this looks good to me. Happy to re-review.

@Aeovy

Aeovy commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Unexpected Import & Type Mismatch in rag/flow/parser
I noticed from litellm import logging in this file. However, the code evaluates logging as a boolean flag (e.g., if logging:). Given that the rest of the codebase exclusively uses Python’s standard logging module, this import appears to be unintended or incorrectly sourced. I’ve already updated it to use Python’s standard logging module. Could you confirm whether this change is acceptable, or if I should revert it?

@xugangqiang

Copy link
Copy Markdown
Contributor

Thanks for turning these around so quickly — I re-checked 95914ba31 and 6c4f30667 and both items 1 and 2 from my last round are properly resolved. Sanitization is now scoped to the table-as-text fallback, and the markdown writer degrades safely. Two new findings below, one of which I'd like to sort out before merge.

1. Media blocks break document order in the DSL flow path

This is the one thing I'd block on.

The mechanism

Four facts combine into the regression:

  1. _transfer_to_sections now skips media unconditionally: IMAGE always, TABLE whenever table_enable is true.
  2. The flow calls parse_pdf() at rag/flow/parser/parser.py:413 without parser_config, so enable_table = parser_cfg.get("mineru_table_enable", True) (deepdoc/parser/mineru_parser.py:942) evaluates to True. Both tables and images therefore leave lines on this path.
  3. The new media loop appends to bboxes after the for line in lines loop (parser.py:421-436) has fully drained.
  4. Nothing re-sorts bboxes afterwards. reorder_multi_column_bboxes is only reached from the DeepDOC branch (parser.py:381); the normalization loop at parser.py:746-769 preserves input order; remove_toc_pdf only trims.

Net result: the markdown writer at parser.py:782-791 emits the entire body text first, then every table and figure appended at the end, and the json output carries the same order into the downstream chunker.

Why this matters more than it might look

The markdown output is a straight concatenation, so a 40-page report becomes 40 pages of prose followed by an undifferentiated pile of tables — each one detached from the paragraph that introduced it. For the json path, the downstream chunker merges adjacent boxes, so proximity is semantics; moving all media to the tail changes which content ends up in which chunk.

Why the trade is specifically unfavourable here

The flow path was already classifying MinerU media correctly before this PR. parser.py:425 reads layout_type straight from line[1], which is MinerU's raw type string, so tables already became doc_type_kwd: table and images already became figure/image with an image mounted via crop(). The screenshots in the PR description are labelled v0.26.3 and no longer reflect main for this path.

So on the flow path the PR trades a real ordering regression for a marginal gain: MinerU's native img_path bitmap instead of a page-region crop. On the rag/app path the fix is genuine and valuable — _transfer_to_tables() returned [], so tokenize_table never ran and media really was landing as plain text. The two paths are not in the same situation, and the current change treats them as if they were.

Recommendation

Option A — smallest change, removes the regression entirely (my preference).
Scope the media-ownership skip in _transfer_to_sections to the rag/app parse methods (raw / manual / paper) and let pipeline keep emitting media inline as it does today. The function already branches on parse_method, so this costs a few lines. Then drop the media loop from rag/flow/parser/parser.py and keep only the b.get("image") null-guard from 6c4f30667. The flow keeps its current correct, correctly-ordered behaviour; rag/app gets the real fix; the diff shrinks.

Option B — if you want the flow to use MinerU's native images too.
Keep the flow consuming media blocks, but carry the source ordinal so the boxes can be merged back. _transfer_to_sections and _transfer_to_media_blocks both iterate the same outputs list in order, so an index is already implicitly available — return it alongside each block and have the flow build one list sorted by that index. Sorting by (page, top) from positions is a cheaper fallback, but it degrades exactly in the case this PR already handles specially, i.e. blocks whose position could not be projected.

Either way, please add a test asserting that a text → table → text input produces boxes in that order. That is the assertion that would have caught this.

2. from litellm import logging

Your instinct was right, and it's more than a style problem — it's a live crash.

litellm/__init__.py:339 declares logging: bool = True. So from litellm import logging at rag/flow/parser/parser.py:23 binds the name to the boolean True, not to a module. Three call sites then dereference it:

  • parser.py:916 and parser.py:924 — the .doc fallback path. The intent is "log a warning and degrade gracefully when tika is unavailable or returns empty content". What actually happens is AttributeError: 'bool' object has no attribute 'warning', turning a graceful degradation into a hard failure.
  • parser.py:1440 — the exception handler in _invoke. logging.error raises first, so t.cancel() and the follow-up asyncio.gather never execute: the original exception is masked and the pending tasks leak.

Reproducible today by uploading a .doc in an environment without tika.

One correction to your description: the code does not do if logging: anywhere — it calls logging.warning(...) / logging.error(...). The consequence is therefore worse than a type mismatch; it is an unconditional runtime crash on those branches.

Recommendation: do not revert — but please pull it out into its own one-line hotfix PR. It is unrelated to MinerU, independently reproducible, and shouldn't be gated on the discussion in this PR. It will also be far easier to backport that way. While you're there, a quick grep -rn "from litellm import" --include=*.py is worth it: this is a classic IDE-autocomplete accident, ruff cannot flag it because the syntax is perfectly valid, and these usually come in pairs.

3. Remaining items — who files them?

Three things are worth tracking outside this PR. Could you let us know whether you'd like to open these yourself, or whether you'd prefer someone on the team to file them?

  1. MinerU CODE path caption/body ordering — the one you identified. You mentioned documenting it as a known issue; a full fix needs an agreed ordering contract for code_caption / code_body / code_footnote, likely driven by child-block ordering in the intermediate JSON, so it's genuinely design work.
  2. manual chunk method duplicates table content — manual.py:243 folds tbls into sections as text chunks while manual.py:273 also runs tokenize_table(tbls). This is pre-existing DeepDOC behaviour, but MinerU only starts hitting it once this PR makes tbls non-empty, so table HTML will now appear both as a table chunk and inside a text chunk.
  3. Replacing the AST-based tests — test_parser_media_classification.py and test_naive_mineru.py extract loops out of the production source with ast.parse and re-exec them. That asserts on source text rather than behaviour: renaming bboxes or mineru_media_blocks makes next(...) raise StopIteration with no usable diagnostic, and because the namespace is synthetic, swapping the real VLM or logging implementation would not be detected. I understand the motivation — rag/flow/parser/parser.py has a heavy import chain — but that is an argument for extracting the loop into a pure helper in rag/flow/parser/utils.py (which already hosts enhance_media_sections_with_vision) and importing it directly. by_mineru can use monkeypatch instead of AST replay.

Two smaller items I'd rather see handled inside this PR than deferred:

  • Empty media chunks. _build_image_texts(keep_placeholder=True) returns [""] for a caption-less image. With no VISION model configured, vision_figure_parser_pdf_wrapper returns tbls untouched and tokenize_table (rag/nlp/__init__.py:485-494) emits a chunk with content_with_weight="". Worse, when _resolve_output_image also comes back empty you get ((None, [""]), poss); if img: is false, so doc_type_kwd stays "table" and you get an empty table chunk. Neither existed before the PR. Dropping media blocks where the image is None and the texts are all empty should cover it.
  • The PR description. Still lists two files against a 10-file, +844/−130 diff. Raised last round and still outstanding — it's the record of intent for anyone bisecting later.

For the record, the incidental fixes in here are good and should survive whichever option you pick: the per-item positions alignment in VisionFigureParser, the empty-poss guard in append_context2table_image4pdf, _line_tag no longer raising KeyError when page_idx is absent, and _content_bbox_to_page_space falling back to pdfplumber page metadata instead of silently emitting unscaled 1000-basis coordinates.

Happy to re-review once the ordering question is settled.

@Aeovy

Aeovy commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for turning these around so quickly — I re-checked 95914ba31 and 6c4f30667 and both items 1 and 2 from my last round are properly resolved. Sanitization is now scoped to the table-as-text fallback, and the markdown writer degrades safely. Two new findings below, one of which I'd like to sort out before merge.

1. Media blocks break document order in the DSL flow path

This is the one thing I'd block on.

The mechanism

Four facts combine into the regression:

  1. _transfer_to_sections now skips media unconditionally: IMAGE always, TABLE whenever table_enable is true.
  2. The flow calls parse_pdf() at rag/flow/parser/parser.py:413 without parser_config, so enable_table = parser_cfg.get("mineru_table_enable", True) (deepdoc/parser/mineru_parser.py:942) evaluates to True. Both tables and images therefore leave lines on this path.
  3. The new media loop appends to bboxes after the for line in lines loop (parser.py:421-436) has fully drained.
  4. Nothing re-sorts bboxes afterwards. reorder_multi_column_bboxes is only reached from the DeepDOC branch (parser.py:381); the normalization loop at parser.py:746-769 preserves input order; remove_toc_pdf only trims.

Net result: the markdown writer at parser.py:782-791 emits the entire body text first, then every table and figure appended at the end, and the json output carries the same order into the downstream chunker.

Why this matters more than it might look

The markdown output is a straight concatenation, so a 40-page report becomes 40 pages of prose followed by an undifferentiated pile of tables — each one detached from the paragraph that introduced it. For the json path, the downstream chunker merges adjacent boxes, so proximity is semantics; moving all media to the tail changes which content ends up in which chunk.

Why the trade is specifically unfavourable here

The flow path was already classifying MinerU media correctly before this PR. parser.py:425 reads layout_type straight from line[1], which is MinerU's raw type string, so tables already became doc_type_kwd: table and images already became figure/image with an image mounted via crop(). The screenshots in the PR description are labelled v0.26.3 and no longer reflect main for this path.

So on the flow path the PR trades a real ordering regression for a marginal gain: MinerU's native img_path bitmap instead of a page-region crop. On the rag/app path the fix is genuine and valuable — _transfer_to_tables() returned [], so tokenize_table never ran and media really was landing as plain text. The two paths are not in the same situation, and the current change treats them as if they were.

Recommendation

Option A — smallest change, removes the regression entirely (my preference). Scope the media-ownership skip in _transfer_to_sections to the rag/app parse methods (raw / manual / paper) and let pipeline keep emitting media inline as it does today. The function already branches on parse_method, so this costs a few lines. Then drop the media loop from rag/flow/parser/parser.py and keep only the b.get("image") null-guard from 6c4f30667. The flow keeps its current correct, correctly-ordered behaviour; rag/app gets the real fix; the diff shrinks.

Option B — if you want the flow to use MinerU's native images too. Keep the flow consuming media blocks, but carry the source ordinal so the boxes can be merged back. _transfer_to_sections and _transfer_to_media_blocks both iterate the same outputs list in order, so an index is already implicitly available — return it alongside each block and have the flow build one list sorted by that index. Sorting by (page, top) from positions is a cheaper fallback, but it degrades exactly in the case this PR already handles specially, i.e. blocks whose position could not be projected.

Either way, please add a test asserting that a text → table → text input produces boxes in that order. That is the assertion that would have caught this.

2. from litellm import logging

Your instinct was right, and it's more than a style problem — it's a live crash.

litellm/__init__.py:339 declares logging: bool = True. So from litellm import logging at rag/flow/parser/parser.py:23 binds the name to the boolean True, not to a module. Three call sites then dereference it:

  • parser.py:916 and parser.py:924 — the .doc fallback path. The intent is "log a warning and degrade gracefully when tika is unavailable or returns empty content". What actually happens is AttributeError: 'bool' object has no attribute 'warning', turning a graceful degradation into a hard failure.
  • parser.py:1440 — the exception handler in _invoke. logging.error raises first, so t.cancel() and the follow-up asyncio.gather never execute: the original exception is masked and the pending tasks leak.

Reproducible today by uploading a .doc in an environment without tika.

One correction to your description: the code does not do if logging: anywhere — it calls logging.warning(...) / logging.error(...). The consequence is therefore worse than a type mismatch; it is an unconditional runtime crash on those branches.

Recommendation: do not revert — but please pull it out into its own one-line hotfix PR. It is unrelated to MinerU, independently reproducible, and shouldn't be gated on the discussion in this PR. It will also be far easier to backport that way. While you're there, a quick grep -rn "from litellm import" --include=*.py is worth it: this is a classic IDE-autocomplete accident, ruff cannot flag it because the syntax is perfectly valid, and these usually come in pairs.

3. Remaining items — who files them?

Three things are worth tracking outside this PR. Could you let us know whether you'd like to open these yourself, or whether you'd prefer someone on the team to file them?

  1. MinerU CODE path caption/body ordering — the one you identified. You mentioned documenting it as a known issue; a full fix needs an agreed ordering contract for code_caption / code_body / code_footnote, likely driven by child-block ordering in the intermediate JSON, so it's genuinely design work.
  2. manual chunk method duplicates table content — manual.py:243 folds tbls into sections as text chunks while manual.py:273 also runs tokenize_table(tbls). This is pre-existing DeepDOC behaviour, but MinerU only starts hitting it once this PR makes tbls non-empty, so table HTML will now appear both as a table chunk and inside a text chunk.
  3. Replacing the AST-based tests — test_parser_media_classification.py and test_naive_mineru.py extract loops out of the production source with ast.parse and re-exec them. That asserts on source text rather than behaviour: renaming bboxes or mineru_media_blocks makes next(...) raise StopIteration with no usable diagnostic, and because the namespace is synthetic, swapping the real VLM or logging implementation would not be detected. I understand the motivation — rag/flow/parser/parser.py has a heavy import chain — but that is an argument for extracting the loop into a pure helper in rag/flow/parser/utils.py (which already hosts enhance_media_sections_with_vision) and importing it directly. by_mineru can use monkeypatch instead of AST replay.

Two smaller items I'd rather see handled inside this PR than deferred:

  • Empty media chunks. _build_image_texts(keep_placeholder=True) returns [""] for a caption-less image. With no VISION model configured, vision_figure_parser_pdf_wrapper returns tbls untouched and tokenize_table (rag/nlp/__init__.py:485-494) emits a chunk with content_with_weight="". Worse, when _resolve_output_image also comes back empty you get ((None, [""]), poss); if img: is false, so doc_type_kwd stays "table" and you get an empty table chunk. Neither existed before the PR. Dropping media blocks where the image is None and the texts are all empty should cover it.
  • The PR description. Still lists two files against a 10-file, +844/−130 diff. Raised last round and still outstanding — it's the record of intent for anyone bisecting later.

For the record, the incidental fixes in here are good and should survive whichever option you pick: the per-item positions alignment in VisionFigureParser, the empty-poss guard in append_context2table_image4pdf, _line_tag no longer raising KeyError when page_idx is absent, and _content_bbox_to_page_space falling back to pdfplumber page metadata instead of silently emitting unscaled 1000-basis coordinates.

Happy to re-review once the ordering question is settled.

Implementing this feature has been significantly more difficult than I initially expected, as I didn’t fully account for several production-specific details. Thank you for your review! While it may take some time, I’ll keep working on it. As for the logging module issue, I’ve already opened a new PR (#17722).

@xugangqiang

Copy link
Copy Markdown
Contributor

Please help to resolve conflicts. Thank you.

@Aeovy

Aeovy commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Please help to resolve conflicts. Thank you.

I've been very busy with work these days, can someone take over this task, or can it be done in a few days?

@xugangqiang

Copy link
Copy Markdown
Contributor

@Aeovy Fine to wait.

@Aeovy
Aeovy force-pushed the aeovy/feat-mineruparser branch 2 times, most recently from f701497 to c003c77 Compare August 13, 2026 03:42
@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 13, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

@Aeovy Seems like CI issues - Lefthook

@Aeovy
Aeovy force-pushed the aeovy/feat-mineruparser branch 3 times, most recently from c18fd5d to 149beb4 Compare August 13, 2026 09:06
@Aeovy
Aeovy force-pushed the aeovy/feat-mineruparser branch from 149beb4 to d01f283 Compare August 14, 2026 09:34
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Aug 14, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM @yuzhichang Please have a second eye.

@yuzhichang
yuzhichang merged commit b27623a into infiniflow:main Aug 19, 2026
3 checks passed
@Aeovy

Aeovy commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

LGTM @yuzhichang Please have a second eye.

I’ll continue testing and addressing the Mineru parsing issues. After this PR, I’ll be submitting a few more as there are still some bugs left to fix

@yuzhichang

Copy link
Copy Markdown
Member

@Aeovy Appreciate for your contribution! We're actively porting RAGFlow from python to golang. Suggest submit golang part change (if necessary) in the same PR in future work.

@Aeovy

Aeovy commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@yuzhichang I haven't learned Go yet, but once the Python version stabilizes, I might take the opportunity to learn it or use AI to migrate the feat to Go.

@Aeovy
Aeovy deleted the aeovy/feat-mineruparser branch August 21, 2026 02:55
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 🌈 python Pull requests that update Python code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants