Repository navigation
Feat: VLM image descriptions in MinerU parser (#14869) - #14946
Conversation
📝 WalkthroughWalkthroughThis 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. ChangesVLM-based image semantic enrichment
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
deepdoc/parser/mineru_parser.py (2)
691-691: 💤 Low valueMinor: use
self.loggerfor consistency with the rest of the class.
MinerUParserinitializesself.loggerand uses it everywhere else (e.g. line 786). Mixing module-levellogging.warninghere 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 valueConsider making the worker count configurable.
max_workers=10is hardcoded. The motivating scenario in#14869is 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 fromparser_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
📒 Files selected for processing (2)
deepdoc/parser/mineru_parser.pyrag/app/naive.py
| 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 |
There was a problem hiding this comment.
🧩 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=pyRepository: 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=pyRepository: 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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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_captionandimage_footnotestrings from MinerU'sJSON. 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/*.jsonthemselves.The deepdoc parser already solves this via
VisionFigureParser: when thetenant has an
IMAGE2TEXTmodel configured, each figure gets asemantic description merged into its chunk. This PR brings the same
behavior to MinerU.
What changed
deepdoc/parser/mineru_parser.py_enhance_images_with_vlm(outputs, vision_model, callback=None)—collects every
IMAGEblock with a readableimg_path, runsrag.app.picture.vision_llm_chunkin a 10-workerThreadPoolExecutorusing the existingvision_llm_figure_describe_prompt, and writes the result back asvlm_description. Per-image failures are logged and skipped — theynever abort the run.
_transfer_to_sections(IMAGE branch) — foldsvlm_descriptioninto 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_modelkwarg is supplied. Wrapped intry / exceptso 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.IMAGE2TEXTmodel viaget_tenant_default_model_by_type, wraps it in anLLMBundle, andinjects it as
kwargs["vision_model"]before delegating toparse_pdf.Behavior
IMAGE2TEXTmodel configuredcaption + footnote + VLM description. Retrieval against figures now actually works.IMAGE2TEXTmodel configuredvision_modelin kwargsif "vision_model" not in kwargsguards the lookup.Files
deepdoc/parser/mineru_parser.py(+56)rag/app/naive.py(+13)Test plan
IMAGE2TEXTmodel →re-parse a PDF with figures and confirm chunks are unchanged
(caption + footnote only, no error in logs).
IMAGE2TEXTmodel (e.g. Gemma-4-31B viaOpenAI-API-Compatible) → re-parse the same PDF and confirm
image chunks now contain a
(caption + footnote + VLM description)payload. Verify retrieval against a query aboutfigure content returns the right chunk.
IMAGE2TEXTat an unreachable URL → confirm parsingstill succeeds and the warning
[MinerU] VLM description failed for image #Nis logged per image; chunks fall back to caption+ footnote.
image_jobslist,
_enhance_images_with_vlmreturns early).respects the worker cap; total wall time scales with provider
latency / 10, not linearly per image.