Skip to content

Feat: VLM image descriptions in MinerU parser (#14869) - #14946

Merged
KevinHuSh merged 1 commit into
infiniflow:mainfrom
Rene0422:feat/mineru-vlm-image-descriptions
May 19, 2026
Merged

KevinHuSh merged 1 commit into
infiniflow:mainfrom
Rene0422:feat/mineru-vlm-image-descriptions

Conversation

@Rene0422

Copy link
Copy Markdown
Contributor

Summary

Closes #14869.

Adds VLM-based semantic descriptions to image chunks produced by the
MinerU parser
, closing a long-standing parity gap with the deepdoc
parser's VisionFigureParser. A maintainer flagged this in #13342
("We may add the VLM enhancement to MinerU parser as well") and an
earlier proposal exists in #13824; this PR lands the change end-to-end
inside the existing parser plumbing.

Why

Today the MinerU parser returns image chunks containing only the
native image_caption and image_footnote strings from MinerU's
JSON. When neither is present (or when both are sparse), the chunk
carries effectively no searchable content for the figure and
retrieval misses it entirely. Users who configured a local VLM
(reporter's case: Gemma-4-31B) had to post-process MinerU's
tmp/*.json themselves.

The deepdoc parser already solves this via
VisionFigureParser: when the
tenant has an IMAGE2TEXT model configured, each figure gets a
semantic description merged into its chunk. This PR brings the same
behavior to MinerU.

What changed

deepdoc/parser/mineru_parser.py

  • New method _enhance_images_with_vlm(outputs, vision_model, callback=None) —
    collects every IMAGE block with a readable img_path, runs
    rag.app.picture.vision_llm_chunk in a 10-worker
    ThreadPoolExecutor using the existing
    vision_llm_figure_describe_prompt, and writes the result back as
    vlm_description. Per-image failures are logged and skipped — they
    never abort the run.
  • _transfer_to_sections (IMAGE branch) — folds
    vlm_description into the section text alongside caption +
    footnote, so the description becomes part of the chunk and is
    searchable / retrievable.
  • parse_pdf — after _read_output, calls
    _enhance_images_with_vlm(outputs, vision_model, callback=callback)
    when a vision_model kwarg is supplied. Wrapped in try / except
    so a VLM outage cannot break parsing.

rag/app/naive.py (by_mineru)

After successfully resolving the MinerU OCR parser, also resolves the
tenant's default LLMType.IMAGE2TEXT model via
get_tenant_default_model_by_type, wraps it in an LLMBundle, and
injects it as kwargs["vision_model"] before delegating to
parse_pdf.

Behavior

Tenant config Behavior
IMAGE2TEXT model configured MinerU image chunks contain caption + footnote + VLM description. Retrieval against figures now actually works.
No IMAGE2TEXT model configured Exact same output as today (caption + footnote only). Lookup fails silently with an info log; no error, no regression.
VLM call fails for a single image That image silently falls back to caption + footnote; other images proceed.
Caller already passes vision_model in kwargs We don't override it — if "vision_model" not in kwargs guards the lookup.

Files

  • deepdoc/parser/mineru_parser.py (+56)
  • rag/app/naive.py (+13)

Test plan

  • Configure a MinerU OCR provider and no IMAGE2TEXT model →
    re-parse a PDF with figures and confirm chunks are unchanged
    (caption + footnote only, no error in logs).
  • Configure a tenant IMAGE2TEXT model (e.g. Gemma-4-31B via
    OpenAI-API-Compatible) → re-parse the same PDF and confirm
    image chunks now contain a (caption + footnote + VLM description) payload. Verify retrieval against a query about
    figure content returns the right chunk.
  • Point IMAGE2TEXT at an unreachable URL → confirm parsing
    still succeeds and the warning [MinerU] VLM description failed for image #N is logged per image; chunks fall back to caption
    + footnote.
  • Parse a doc with no images → no VLM calls (empty image_jobs
    list, _enhance_images_with_vlm returns early).
  • Parse a doc with many images (>10) → ThreadPoolExecutor
    respects the worker cap; total wall time scales with provider
    latency / 10, not linearly per image.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 15, 2026
@coderabbitai

coderabbitai Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds VLM-powered semantic enrichment to MinerU's IMAGE parsing. When a vision_model is provided, the parser generates descriptions for images via concurrent VLM inference, stores them, and appends them to chunk text. Vision model provisioning is best-effort at the app level.

Changes

VLM-based image semantic enrichment

Layer / File(s) Summary
VLM enhancement implementation and integration
deepdoc/parser/mineru_parser.py
New _enhance_images_with_vlm method loads images, runs concurrent VLM figure-description inference, and stores trimmed descriptions to outputs. parse_pdf calls this method when vision_model is present in kwargs, with exception handling to log warnings and continue parsing on failure.
Chunk text enrichment with VLM descriptions
deepdoc/parser/mineru_parser.py
_transfer_to_sections now appends the vlm_description field (when present on output items) to IMAGE chunk text, making semantic descriptions part of searchable content.
Vision model provisioning at app level
rag/app/naive.py
by_mineru conditionally loads tenant's default IMAGE2TEXT model and injects it as vision_model in kwargs to enable MinerU enrichment; gracefully logs and continues if model unavailable.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

📸 A rabbit draws wisdom from every frame,
Running the vision-llm's semantic flame,
Image chunks now whisper their story and name,
Concurrent enrichment—no two are the same! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% 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 accurately describes the main feature being added: VLM-based semantic descriptions integrated into MinerU parser image chunks.
Description check ✅ Passed The description is comprehensive and well-structured, covering problem statement, rationale, implementation details, behavior matrix, files changed, and test plan.
Linked Issues check ✅ Passed The changes directly address issue #14869 by implementing automated VLM semantic descriptions for MinerU image chunks, eliminating the need for manual post-processing.
Out of Scope Changes check ✅ Passed All changes are focused on adding VLM image enrichment to MinerU parser and are directly aligned with the stated objectives in the linked issue.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

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

691-691: 💤 Low value

Minor: use self.logger for consistency with the rest of the class.

MinerUParser initializes self.logger and uses it everywhere else (e.g. line 786). Mixing module-level logging.warning here makes filtering/searching MinerU logs less consistent.

♻️ Suggested change
-            except Exception as e:
-                logging.warning(f"[MinerU] VLM description failed for image #{idx}: {e}")
-                return idx, ""
+            except Exception as e:
+                self.logger.warning(f"[MinerU] VLM description failed for image #{idx}: {e}")
+                return idx, ""
🤖 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 691, The log call inside
MinerUParser that currently uses module-level logging.warning should be replaced
with the instance logger: call self.logger.warning(...) instead of
logging.warning(...) in the VLM description error path (the message " [MinerU]
VLM description failed for image #{idx}: {e}" referenced in the method where
images are described). Update that call to use self.logger.warning and ensure
the exception text is included (or use exc_info=True if preferred) so logs
remain consistent with the rest of the class.

694-694: 💤 Low value

Consider making the worker count configurable.

max_workers=10 is hardcoded. The motivating scenario in #14869 is a local VLM (Gemma-4-31B) on a single GPU, where 10 concurrent requests will queue or thrash. For hosted VLMs it's often fine, but on-prem/local setups can suffer. Sourcing from parser_config (e.g. mineru_vlm_concurrency) or an env var with a small default (e.g. 4) would help avoid surprises.

♻️ Suggested change
-        with ThreadPoolExecutor(max_workers=10) as executor:
+        max_workers = int(os.environ.get("MINERU_VLM_CONCURRENCY", "4"))
+        with ThreadPoolExecutor(max_workers=max(1, max_workers)) as executor:
🤖 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 694, The ThreadPoolExecutor in
mineru_parser.py currently hardcodes max_workers=10; change it to read a
configurable concurrency value (e.g., from parser_config key
"mineru_vlm_concurrency" or an env var like MINERU_VLM_CONCURRENCY) with a sane
default (e.g., 4). Update the code that creates the executor (the with
ThreadPoolExecutor(...) call) to parse the config/env into an int, apply bounds
checking (min 1, optional max cap), and pass that value to ThreadPoolExecutor;
ensure any config lookup uses existing parser_config access patterns and falls
back to the env var and then to the default.
🤖 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 684-699: The worker function invokes vision_llm_chunk (which
ultimately calls LLMBundle.describe_with_prompt) concurrently causing
thread-safety issues; define a module-level threading.Lock (e.g., vision_lock)
and acquire it around the vision_llm_chunk call inside worker (or alternatively
replace the ThreadPoolExecutor with a serialized loop) so all calls to
vision_llm_chunk/LLMBundle.describe_with_prompt are serialized; update worker to
obtain the lock before calling vision_llm_chunk and release it immediately after
to prevent concurrent access to the shared HTTP client.

---

Nitpick comments:
In `@deepdoc/parser/mineru_parser.py`:
- Line 691: The log call inside MinerUParser that currently uses module-level
logging.warning should be replaced with the instance logger: call
self.logger.warning(...) instead of logging.warning(...) in the VLM description
error path (the message " [MinerU] VLM description failed for image #{idx}: {e}"
referenced in the method where images are described). Update that call to use
self.logger.warning and ensure the exception text is included (or use
exc_info=True if preferred) so logs remain consistent with the rest of the
class.
- Line 694: The ThreadPoolExecutor in mineru_parser.py currently hardcodes
max_workers=10; change it to read a configurable concurrency value (e.g., from
parser_config key "mineru_vlm_concurrency" or an env var like
MINERU_VLM_CONCURRENCY) with a sane default (e.g., 4). Update the code that
creates the executor (the with ThreadPoolExecutor(...) call) to parse the
config/env into an int, apply bounds checking (min 1, optional max cap), and
pass that value to ThreadPoolExecutor; ensure any config lookup uses existing
parser_config access patterns and falls back to the env var and then to the
default.
🪄 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: 21c833a2-9191-439f-8056-8eb72140df19

📥 Commits

Reviewing files that changed from the base of the PR and between 547b8cf and 18016a5.

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

Comment on lines +684 to +699
def worker(idx, item):
try:
with Image.open(item["img_path"]) as img:
img.load()
desc = vision_llm_chunk(binary=img, vision_model=vision_model, prompt=prompt)
return idx, (desc or "").strip()
except Exception as e:
logging.warning(f"[MinerU] VLM description failed for image #{idx}: {e}")
return idx, ""

with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(worker, idx, item) for idx, item in image_jobs]
for fut in as_completed(futures):
idx, desc = fut.result()
if desc:
outputs[idx]["vlm_description"] = desc

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# 1) Inspect vision_llm_chunk signature and how `binary` is consumed.
ast-grep --pattern $'def vision_llm_chunk($$$):
  $$$'

# Fallback in case ast-grep misses it:
rg -nP -C2 '\bdef\s+vision_llm_chunk\s*\(' --type=py

# 2) Look at LLMBundle.chat / describe / describe_with_prompt to see if it
#    uses any per-call mutable state or a session that should be guarded.
ast-grep --pattern $'class LLMBundle:
  $$$
  def describe($$$):
    $$$
  $$$'

ast-grep --pattern $'class LLMBundle:
  $$$
  def describe_with_prompt($$$):
    $$$
  $$$'

rg -nP -C3 'class\s+LLMBundle\b' --type=py

Repository: infiniflow/ragflow

Length of output: 2734


🏁 Script executed:

# Get full LLMBundle class definition and describe_with_prompt method
rg -nP 'class\s+LLMBundle' -A 100 --type=py | head -200

# Search specifically for describe_with_prompt implementation
rg -nP 'def\s+describe_with_prompt\s*\(' -B 2 -A 15 --type=py

# Check for any thread locks or synchronization in LLMBundle
rg -nP '(Lock|RLock|Semaphore|threading)' api/db/services/llm_service.py --type=py

Repository: infiniflow/ragflow

Length of output: 21333


Use a lock when calling LLMBundle.describe_with_prompt from concurrent workers, or serialize vision model calls.

LLMBundle shares a single HTTP client across all workers without synchronization. Most vision model clients (OpenAI, Anthropic, Google, etc.) maintain internal state (connection pools, session handles) that is not thread-safe. Concurrent calls from 10 workers will cause race conditions and intermittent failures.

Wrap the vision_llm_chunk call in worker() with a lock:

vision_lock = threading.Lock()  # At module level
# In worker():
with vision_lock:
    desc = vision_llm_chunk(binary=img, vision_model=vision_model, prompt=prompt)

Or serialize the loop instead of using ThreadPoolExecutor.

🤖 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 684 - 699, The worker function
invokes vision_llm_chunk (which ultimately calls LLMBundle.describe_with_prompt)
concurrently causing thread-safety issues; define a module-level threading.Lock
(e.g., vision_lock) and acquire it around the vision_llm_chunk call inside
worker (or alternatively replace the ThreadPoolExecutor with a serialized loop)
so all calls to vision_llm_chunk/LLMBundle.describe_with_prompt are serialized;
update worker to obtain the lock before calling vision_llm_chunk and release it
immediately after to prevent concurrent access to the shared HTTP client.

@KevinHuSh KevinHuSh added the ci Continue Integration label May 19, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 19, 2026 07:42
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 19, 2026 07:42
@codecov

codecov Bot commented May 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (5a5bbee) to head (18016a5).
⚠️ Report is 54 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14946      +/-   ##
==========================================
- Coverage   95.59%   94.16%   -1.43%     
==========================================
  Files          10       10              
  Lines         703      703              
  Branches      112      112              
==========================================
- Hits          672      662      -10     
- Misses         21       25       +4     
- Partials       10       16       +6     

☔ View full report in Codecov by Sentry.
📢 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.

@KevinHuSh
KevinHuSh merged commit f58e0b3 into infiniflow:main May 19, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

[Question]: did ragflow provide the feature : Serialize image content into semantic descriptions and embed them into the original image chunks.

2 participants