Skip to content

Feat: add OpenDataLoader PDF parser backend (#14058) - #14097

Merged
yingfeng merged 32 commits into
infiniflow:mainfrom
wdeveloper16:feat/opendataloader-pdf-parser
Apr 24, 2026
Merged

yingfeng merged 32 commits into
infiniflow:mainfrom
wdeveloper16:feat/opendataloader-pdf-parser

Conversation

@wdeveloper16

@wdeveloper16 wdeveloper16 commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Closes #14058.

RAGFlow supports multiple PDF parsing backends (DeepDOC, MinerU, Docling, TCADP, PaddleOCR). This PR adds OpenDataLoader (opendataloader-project/opendataloader-pdf) as a new optional backend, giving users a deterministic, local-first alternative with competitive table extraction accuracy.

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Documentation Update

Changes

Backend

  • deepdoc/parser/opendataloader_parser.py — new OpenDataLoaderParser class inheriting RAGFlowPdfParser. Implements check_installation() (guards Python package + Java 11+ runtime), parse_pdf() with JSON-first extraction (heading/paragraph/table/list/image/formula) and Markdown fallback, position-tag generation compatible with the shared @@page\tx0\tx1\ty0\ty1## format, and temp-dir lifecycle with cleanup.
  • rag/app/naive.py — new by_opendataloader() wrapper, registered in PARSERS dict, added to chunk_token_num=0 override list.
  • rag/flow/parser/parser.py — "opendataloader" branch in the pipeline PDF handler + check validation list.

Infrastructure

  • docker/entrypoint.sh — ensure_opendataloader() function: opt-in via USE_OPENDATALOADER=true, skips gracefully if Java is not on PATH.

Frontend

  • web/src/components/layout-recognize-form-field.tsx — OpenDataLoader added to ParseDocumentType enum and parser dropdown. Cascades automatically to the pipeline editor's Parser component.

Docs

  • docs/guides/dataset/select_pdf_parser.md — added OpenDataLoader entry and full env-var reference.

Environment variables

Variable Default Description
USE_OPENDATALOADER false Set true to install opendataloader-pdf on container startup
OPENDATALOADER_VERSION latest Pin the PyPI release (e.g. ==2.2.1)
OPENDATALOADER_HYBRID (unset) Enable hybrid AI mode (e.g. docling-fast)
OPENDATALOADER_IMAGE_OUTPUT (unset) off / embedded / external
OPENDATALOADER_OUTPUT_DIR (tmp) Persistent output dir; temp dir used + cleaned if unset
OPENDATALOADER_DELETE_OUTPUT 1 0 to retain intermediate files for debugging
OPENDATALOADER_SANITIZE (unset) 1 to filter prompt-injection patterns from output

Dependencies

  • Runtime: opendataloader-pdf (PyPI, Apache 2.0) — opt-in, not added to pyproject.toml core deps. Installed by ensure_opendataloader() at container startup when USE_OPENDATALOADER=true.
  • System: Java 11+ on PATH (JVM is the underlying engine). The installer skips with a warning if java is not found.

How to test

Standalone parser:

source .venv/bin/activate
uv pip install opendataloader-pdf
python3 -c "
import sys; sys.path.insert(0, '.')
from deepdoc.parser.opendataloader_parser import OpenDataLoaderParser
p = OpenDataLoaderParser()
print('available:', p.check_installation())
s, t = p.parse_pdf('path/to/test.pdf', parse_method='pipeline')
print(f'sections={len(s)} tables={len(t)}')
"

Benchmark vs Docling

file                      parser            secs  sections  tables
----------------------------------------------------------------------
text-heavy.pdf            docling           45.29       148      10
text-heavy.pdf            opendataloader     3.14       559       0
table-heavy.pdf           docling           7.05        76       3
table-heavy.pdf           opendataloader     3.71        90       0
complex.pdf               docling            42.67       114       8
complex.pdf               opendataloader     3.51       180       0

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. 📖 documentation Improvements or additions to documentation labels Apr 14, 2026
@coderabbitai

coderabbitai Bot commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

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

Introduces OpenDataLoader as a new PDF parsing backend by implementing a parser module that communicates with an external OpenDataLoader service via HTTP, plus integration layers across RAGFlow's PDF pipeline, database services, LLM factory configuration, and frontend UI components for configuration and parser selection.

Changes

Cohort / File(s) Summary
Core Parser Implementation
deepdoc/parser/opendataloader_parser.py
New OpenDataLoader parser extending RAGFlowPdfParser: initializes from environment variables, performs health checks via HTTP GET, uploads PDFs to external service via multipart POST with retry logic, parses JSON/markdown responses into sections/tables, extracts bounding box positions with coordinate conversion, and provides crop/image stitching utilities.
OCR Model Integration
rag/llm/ocr_model.py
New OpenDataLoaderOcrModel class wrapping the parser, extracting credentials from config, validating service availability via check_available(), and delegating parse_pdf() calls to the OpenDataLoaderParser instance.
Pipeline Integration
rag/app/naive.py, rag/flow/parser/parser.py
New by_opendataloader entrypoint resolving OCR model via TenantLLMService, parsing PDFs with optional parse method, and returning standardized results. Pipeline layer transforms returned tuples into bboxes with positions and images, appends table/figure blocks with offset conversion.
Tenant LLM Service
api/db/services/tenant_llm_service.py
New methods to collect OpenDataLoader config from environment variables, search/create tenant OpenDataLoader models with retry-on-collision logic to avoid name conflicts.
Configuration & Constants
common/constants.py, conf/llm_factories.json, api/apps/llm_app.py
Added OpenDataLoader environment key lists and default config constants; registered OpenDataLoader as OCR factory in LLM configuration; extended LLM app to serialize/initialize OpenDataLoader credentials.
Frontend Enum & Parser Selection
web/src/constants/llm.ts, web/src/components/layout-recognize-form-field.tsx
Added OpenDataLoader enum member to LLMFactory; extended parser selection options to include OpenDataLoader in the form field dropdown.
Frontend Modal & Hooks
web/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsx, web/src/pages/user-setting/setting-model/hooks.tsx, web/src/pages/user-setting/setting-model/index.tsx
New OpenDataLoaderModal component with Zod schema for llm_name, opendataloader_apiserver, and optional opendataloader_api_key; new useSubmitOpenDataLoader hook managing submit/verify logic; integration into settings model page with modal visibility and callback wiring.
Documentation & Tests
docs/guides/dataset/select_pdf_parser.md, test/unit_test/deepdoc/parser/test_opendataloader_parser.py
Added Docker Compose setup guide for OpenDataLoader service and environment variable documentation; comprehensive unit tests stubbing external dependencies and validating health checks, multipart uploads, JSON/markdown parsing, retry behavior, and crop operations.

Sequence Diagram(s)

sequenceDiagram
    participant Client as RAGFlow<br/>Application
    participant Service as TenantLLMService
    participant ODL as OpenDataLoader<br/>Service
    participant Parser as OpenDataLoaderParser

    Client->>Service: ensure_opendataloader_from_env(tenant_id)
    Service-->>Service: collect config from env
    Service->>Service: search/create tenant model
    Service-->>Client: llm_name

    Client->>Parser: __init__(api_url, api_key, timeout)
    Client->>Parser: check_installation()
    Parser->>ODL: GET /health (with Bearer auth)
    ODL-->>Parser: 200 OK / error response
    Parser-->>Client: bool

    Client->>Parser: parse_pdf(filepath, binary, parse_method, hybrid, ...)
    Parser->>Parser: extract PDF outline & render images
    Parser->>ODL: POST /file_parse (multipart: file, hybrid, ...)
    ODL-->>Parser: json_doc + md_text + tables
    
    Parser->>Parser: _iter_elements() traverse JSON
    Parser->>Parser: extract_positions() → bbox tags
    Parser->>Parser: crop() stitch image strips
    Parser-->>Client: sections[], tables[], images[]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 A new backend hops into place,
OpenDataLoader joins the parsing race!
PDFs fly to the service so bright,
Cropped images, sections—all formatted right! 📄✨
Coordinates dance, positions transform,
Our RAGFlow now learns a new form!

🚥 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 PR title clearly and concisely describes the main change: adding OpenDataLoader as a new PDF parser backend. It is specific, relates directly to the changeset, and accurately summarizes the primary objective without being vague or off-topic.
Description check ✅ Passed The PR description is comprehensive and well-structured. It includes the linked issue (#14058), a clear problem statement, the type of change (New Feature + Documentation), detailed backend/infrastructure/frontend/docs changes, environment variables, dependencies, and testing instructions. All required template sections are addressed.
Linked Issues check ✅ Passed The PR successfully implements all key coding requirements from issue #14058: OpenDataLoader integrated as optional PDF parser backend, structured extraction (headings/paragraphs/tables/lists/images/formulas) with Markdown fallback, position-tag generation, competitive performance, UI exposure via ParseDocumentType enum, comprehensive documentation, and opt-in installation with manageable dependencies (Java 11+ only when using service; refactored to HTTP client pattern).
Out of Scope Changes check ✅ Passed All changes are directly aligned with integrating OpenDataLoader as a PDF parser. No out-of-scope modifications detected. Changes span: core parser implementation, infrastructure setup, LLM/OCR model integration, frontend UI updates, documentation, and unit tests—all supporting the core objective of adding OpenDataLoader as an optional backend.

✏️ 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.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @ZhenhangTung
Would you please review the PR when you have a chance?

@yingfeng
yingfeng requested a review from xugangqiang April 14, 2026 04:17
@yingfeng yingfeng added the ci Continue Integration label Apr 14, 2026
@yingfeng
yingfeng marked this pull request as draft April 14, 2026 04:17
@yingfeng
yingfeng marked this pull request as ready for review April 14, 2026 04:17

@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: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 348-355: When output_dir is provided, don’t reuse a single shared
workdir — create a unique request-scoped subdirectory under output_dir and only
clean that subtree; update the workdir creation in the function that currently
sets workdir/cleanup_workdir (replace the block that sets workdir =
Path(output_dir) vs tempfile.mkdtemp) so it instead makes workdir =
Path(output_dir) / f"req_{uuid4().hex}" (or similar unique name) and
mkdir(parents=True), set cleanup_workdir = True only for this request subdir,
and ensure any tear-down only deletes that subdirectory; also verify callers
such as _read_outputs() and any logic that references the `_in_<name>` file or
out/ folder read from workdir use this new request-scoped workdir to avoid
cross-request contamination.
- Around line 167-176: In _make_line_tag, the image-space Y coordinates are
inverted: when flipping for page_images you should derive top from bbox.y1 and
bottom from bbox.y0 (i.e., set top, bott = page_height - bbox.y1, page_height -
bbox.y0) so that top <= bottom; update the branch in _make_line_tag (referencing
bbox.y0, bbox.y1, top, bott, page_height, and self.page_images) to compute
flipped top/bott using bbox.y1 and bbox.y0 before formatting the tag.
- Around line 134-147: In check_installation(), enhance the Java check to run
"java -version", parse its stderr/stdout to extract the major Java version and
return False (with the existing logger.warning) when the major version is less
than 11; keep the other checks for opendataloader_pdf and the convert() entry
point unchanged. Specifically, inside the check_installation method (referencing
opendataloader_pdf and the convert symbol) call shutil.which("java") to get the
binary path, execute "java -version", parse the version string to an integer
major version (handle "1.x" legacy format and modern "11", "17", etc.), and log
the same Java runtime warning when version < 11. Also update
docker/entrypoint.sh's Java validation logic to use the same
parsing/major-version rule so both places remain in sync.

In `@docs/guides/dataset/select_pdf_parser.md`:
- Line 80: The sentence describing OPENDATALOADER_OUTPUT_DIR uses British-style
“afterwards”; update the phrasing to use US English by replacing “removed
afterwards” with “removed afterward” in the sentence that mentions
OPENDATALOADER_OUTPUT_DIR so it matches the rest of the docs.

In `@rag/flow/parser/parser.py`:
- Around line 433-441: The call to pdf_parser.parse_pdf in parser.py (the lines
assigning lines, _ = pdf_parser.parse_pdf(...)) omits forwarding
OPENDATALOADER_IMAGE_OUTPUT and OPENDATALOADER_SANITIZE, so flow-based parsing
differs from by_opendataloader; fix by reading those environment variables the
same way as in rag/app/naive.py.by_opendataloader (e.g., derive image_output
from OPENDATALOADER_IMAGE_OUTPUT and sanitize from OPENDATALOADER_SANITIZE) and
pass them into pdf_parser.parse_pdf as the image_output and sanitize (or
similarly named) keyword arguments so parse_pdf receives the same flags in this
branch.
🪄 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: 9fb7de67-59f5-4bc9-969a-8efb049ce0fc

📥 Commits

Reviewing files that changed from the base of the PR and between c22811f and 8cc0c5a.

📒 Files selected for processing (6)
  • deepdoc/parser/opendataloader_parser.py
  • docker/entrypoint.sh
  • docs/guides/dataset/select_pdf_parser.md
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • web/src/components/layout-recognize-form-field.tsx

Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread rag/flow/parser/parser.py Resolved
@codecov

codecov Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (d5d162b) to head (653ee1c).
⚠️ Report is 47 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14097      +/-   ##
==========================================
- Coverage   95.97%   95.30%   -0.67%     
==========================================
  Files          10       10              
  Lines         695      703       +8     
  Branches      111      112       +1     
==========================================
+ Hits          667      670       +3     
- Misses         11       16       +5     
  Partials       17       17              

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

@wdeveloper16
wdeveloper16 force-pushed the feat/opendataloader-pdf-parser branch from 8cc0c5a to 6d4be1d Compare April 14, 2026 04:29

@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: 4

♻️ Duplicate comments (1)
docker/entrypoint.sh (1)

241-247: ⚠️ Potential issue | 🟠 Major

Reject unsupported Java versions here too.

This gate only checks that java exists. With Java 8 on PATH the container still installs OpenDataLoader, but OpenDataLoaderParser.check_installation() later rejects the runtime and the first parse fails instead of being skipped up front.

🔧 Suggested fix
     if ! command -v java >/dev/null 2>&1; then
         echo "[opendataloader] Java runtime not found; OpenDataLoader requires Java 11+. Skipping."
         return 0
     fi
+    java_version="$(java -version 2>&1 | head -n1)"
+    if [[ "$java_version" =~ \"([0-9]+)(\.([0-9]+))? ]]; then
+        java_major="${BASH_REMATCH[1]}"
+        if [[ "$java_major" == "1" ]]; then
+            java_major="${BASH_REMATCH[3]:-0}"
+        fi
+        if (( java_major < 11 )); then
+            echo "[opendataloader] Java ${java_major} detected; Java 11+ is required. Skipping."
+            return 0
+        fi
+    else
+        echo "[opendataloader] Could not determine Java version. Skipping."
+        return 0
+    fi
     OPENDATALOADER_PIN="${OPENDATALOADER_VERSION:-}"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docker/entrypoint.sh` around lines 241 - 247, The current entrypoint.sh only
checks for existence of the java command and can let Java 8 through; update the
java check block to run "java -version" (or equivalent) and parse the major
version, and if the detected Java major version is less than 11 then print the
existing skip message and return 0 (so installation is skipped up front); keep
using OPENDATALOADER_PIN for the installer line and ensure the behavior matches
OpenDataLoaderParser.check_installation() which expects Java 11+. Locate the
check around the existing java existence test in entrypoint.sh and add the
version parse/compare before attempting to install opendataloader-pdf.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 178-188: The bug is that __images__() only fills self.page_images
for pages page_from..page_to (default 0..600) and may leave it empty on render
failures, but _make_line_tag() still emits crop tags which later cause crop() to
index self.page_images out of range; update _make_line_tag() (and any other
tag-producing helpers that reference pages) to first validate that a page index
exists in self.page_images before emitting a crop tag (e.g. check bounds using
page_from/page_to and that self.page_images[pos[0][-1]] is present), and if the
image is missing either skip emitting the crop tag or emit a safe placeholder
tag; also ensure __images__() handles render failures by leaving a clear
sentinel or logging and that code paths that call crop() guard against missing
images.
- Around line 288-296: The _classify function currently collapses many source
element types into OpenDataLoaderContentType.TEXT, losing distinctions like
"heading"/"title"/"paragraph"/"list"/"caption"; update _classify (and its usage)
to preserve the original structural type: normalize el_type to lowercase and
return it (or map it to a matching OpenDataLoaderContentType value only for
types that truly correspond to TABLE/IMAGE/EQUATION), otherwise return the
normalized structural string (e.g., "title", "heading", "paragraph", "list",
"caption") instead of OpenDataLoaderContentType.TEXT.value so downstream parsers
can see the original layout_type.

In `@rag/flow/parser/parser.py`:
- Around line 433-460: The code calls pdf_parser.parse_pdf and only unpacks the
first return (lines) so any tables/images returned by
OpenDataLoaderParser.parse_pdf are discarded; change the call to capture both
returns (e.g., lines, extras or lines, odldata), then merge entries from that
second value into bboxes (create boxes for tables and images using the same
schema as text boxes, preserving "text"/"layout_type"/"positions"/"image" keys).
Update references around pdf_parser.parse_pdf, the loop over lines, and where
bboxes is populated so flow mode includes table and image items from the second
return instead of dropping them. Ensure you still handle None/empty cases and
keep existing logic for position/image extraction via
pdf_parser.extract_positions and pdf_parser.crop.
- Around line 438-442: The environment boolean parsing is too strict and
drops/raises on common values; update the parsing for
OPENDATALOADER_DELETE_OUTPUT and OPENDATALOADER_SANITIZE (and any similar flags
around output_dir, hybrid, image_output, sanitize) to accept common truthy/falsy
strings ("true"/"false", "1"/"0", "yes"/"no") as well as integers, converting
them to proper bools rather than using bool(int(...)) which raises on "false"
and using "or None" which discards explicit False; implement a small helper
(e.g., parse_env_bool) and use it for delete_output and sanitize so False
reaches parse_pdf() and invalid values fall back to a safe default.

---

Duplicate comments:
In `@docker/entrypoint.sh`:
- Around line 241-247: The current entrypoint.sh only checks for existence of
the java command and can let Java 8 through; update the java check block to run
"java -version" (or equivalent) and parse the major version, and if the detected
Java major version is less than 11 then print the existing skip message and
return 0 (so installation is skipped up front); keep using OPENDATALOADER_PIN
for the installer line and ensure the behavior matches
OpenDataLoaderParser.check_installation() which expects Java 11+. Locate the
check around the existing java existence test in entrypoint.sh and add the
version parse/compare before attempting to install opendataloader-pdf.
🪄 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: 4220b858-ca03-431a-95e6-34257fdb60ef

📥 Commits

Reviewing files that changed from the base of the PR and between 8cc0c5a and 2889c7f.

📒 Files selected for processing (6)
  • deepdoc/parser/opendataloader_parser.py
  • docker/entrypoint.sh
  • docs/guides/dataset/select_pdf_parser.md
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • web/src/components/layout-recognize-form-field.tsx
✅ Files skipped from review due to trivial changes (1)
  • docs/guides/dataset/select_pdf_parser.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • web/src/components/layout-recognize-form-field.tsx
  • rag/app/naive.py

Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread rag/flow/parser/parser.py Resolved
Comment thread rag/flow/parser/parser.py Resolved
…layout types, capture odl_tables, robust env bool parsing (infiniflow#14058)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
deepdoc/parser/opendataloader_parser.py (1)

391-399: ⚠️ Potential issue | 🟠 Major

Always tear down the request-scoped workdir in finally.

workdir is already unique per parse, so delete_output=True can safely remove that subtree even when output_dir is configured. The current cleanup_workdir = output_dir is None split leaves empty request dirs behind on the happy path and skips cleanup entirely for any exception after convert().

Also applies to: 439-470

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@deepdoc/parser/opendataloader_parser.py` around lines 391 - 399, The current
logic sets cleanup_workdir = output_dir is None and can skip removing
per-request workdir on success or after exceptions; change to always mark the
per-request workdir for teardown (e.g., set cleanup_workdir = True or remove
that conditional) and ensure the workdir Path created by workdir =
Path(tempfile.mkdtemp(...)) is always removed in a finally block after convert()
and downstream processing (wrap the convert()/processing steps in try/finally
and use workdir.rmtree or equivalent cleanup), and apply the same fix to the
later similar block around the code referenced at lines 439-470 so no
request-scoped directories are left behind on success or error.
🧹 Nitpick comments (1)
deepdoc/parser/opendataloader_parser.py (1)

417-473: Add logger info on the happy path, not just callbacks.

Start/success/fallback states are callback-only today, so service logs will not show when this backend ran, whether Line 455 fell back to Markdown, or how many sections/tables were emitted. As per coding guidelines, "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@deepdoc/parser/opendataloader_parser.py` around lines 417 - 473, Add
informational logging for the main happy-path steps in the OpenDataLoader flow:
log at start of conversion (before calling self.__images__ /
opendataloader_pdf.convert), log successful convert/read outputs (after
opendataloader_pdf.convert and after json_doc, md_text =
self._read_outputs(out_sub)), log whether the code fell back to markdown (when
executing the _sections_from_markdown branch or when json_doc is None), and log
the final counts of sections and tables (using the sections and tables
variables) before cleanup/Done. Use the existing logger (self.logger.info) and
reference the unique symbols __images__, opendataloader_pdf.convert,
_read_outputs, _transfer_from_json, and _sections_from_markdown so the messages
clearly indicate which step succeeded or which branch (JSON vs Markdown)
produced the sections.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 386-389: Reorder the installation check so the backend is
validated before attempting PDF work: call self.check_installation() and raise
the existing RuntimeError("OpenDataLoader not available, please install
`opendataloader-pdf`") if it returns False, before invoking
extract_pdf_outlines(...) to set self.outlines; this prevents
extract_pdf_outlines from running when OpenDataLoader/Java is missing and makes
failures deterministic.
- Around line 196-221: The issue is that _make_line_tag() can emit negative
coordinates but extract_positions()'s regex only matches positive floats so
signed values get ignored; update the regex in extract_positions() (the
re.findall pattern) to accept optional leading minus signs for numeric fields
(e.g. change the numeric character class from [0-9.\t] to [-0-9.\t] or
equivalent) so tags emitted by _make_line_tag() (and later used by crop()) are
properly matched and converted to floats; keep the rest of the parsing logic
(split and float/int conversions) intact.

---

Duplicate comments:
In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 391-399: The current logic sets cleanup_workdir = output_dir is
None and can skip removing per-request workdir on success or after exceptions;
change to always mark the per-request workdir for teardown (e.g., set
cleanup_workdir = True or remove that conditional) and ensure the workdir Path
created by workdir = Path(tempfile.mkdtemp(...)) is always removed in a finally
block after convert() and downstream processing (wrap the convert()/processing
steps in try/finally and use workdir.rmtree or equivalent cleanup), and apply
the same fix to the later similar block around the code referenced at lines
439-470 so no request-scoped directories are left behind on success or error.

---

Nitpick comments:
In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 417-473: Add informational logging for the main happy-path steps
in the OpenDataLoader flow: log at start of conversion (before calling
self.__images__ / opendataloader_pdf.convert), log successful convert/read
outputs (after opendataloader_pdf.convert and after json_doc, md_text =
self._read_outputs(out_sub)), log whether the code fell back to markdown (when
executing the _sections_from_markdown branch or when json_doc is None), and log
the final counts of sections and tables (using the sections and tables
variables) before cleanup/Done. Use the existing logger (self.logger.info) and
reference the unique symbols __images__, opendataloader_pdf.convert,
_read_outputs, _transfer_from_json, and _sections_from_markdown so the messages
clearly indicate which step succeeded or which branch (JSON vs Markdown)
produced the sections.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8e01afc3-4bc2-4972-bd75-593fe43a024f

📥 Commits

Reviewing files that changed from the base of the PR and between 2889c7f and 36a9eeb.

📒 Files selected for processing (2)
  • deepdoc/parser/opendataloader_parser.py
  • rag/flow/parser/parser.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rag/flow/parser/parser.py

Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread deepdoc/parser/opendataloader_parser.py Resolved
@xugangqiang xugangqiang self-assigned this Apr 14, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

@wdeveloper16
Apprecaite your contribution.

As we don't want to add a dependency for JRE, may I ask for your help to separate "opendataloader" as a standalone service (like in a docker) and then invoke that service? You can check how "minerU" is integrated.

Thank you.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

@wdeveloper16 Apprecaite your contribution.

As we don't want to add a dependency for JRE, may I ask for your help to separate "opendataloader" as a standalone service (like in a docker) and then invoke that service? You can check how "minerU" is integrated.

Thank you.

@xugangqiang Thank you for the direction — this is exactly the right call. I'll refactor OpenDataLoader to follow the MinerU pattern: a standalone HTTP service that owns the Java/JRE dependency, with RAGFlow becoming a thin HTTP client.

Planned changes:

  • Standalone service: a small FastAPI app wrapping the opendataloader_pdf Java library. RAGFlow calls POST {OPENDATALOADER_APISERVER}/file_parse with the PDF as multipart form data and receives parsed JSON back. No JRE on the RAGFlow host.

  • RAGFlow parser becomes an HTTP client: mirrors deepdoc/parser/mineru_parser.py: reads OPENDATALOADER_APISERVER from env/config, POSTs the document, converts the JSON response into RAGFlow sections. The subprocess/shutil.which("java") code is removed entirely.

  • Docker: an optional opendataloader service in docker-compose.yml (similar to how MinerU is documented as a separately-run container), with OPENDATALOADER_APISERVER env var pointing to it.

  • Docs: update the parser selection guide to explain how to run the service and configure the env var, matching the MinerU setup guide.

@xugangqiang

Copy link
Copy Markdown
Contributor

@wdeveloper16
That's a very good idea. I am looking forward to see it happens.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Okay, no problem at all.
In the meantime, I'd be happy if you review my another contribution.
#14098

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Just done! @xugangqiang
I've implemented them as we discussed.
Would you review the PR, please?

@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

♻️ Duplicate comments (1)
deepdoc/parser/opendataloader_parser.py (1)

184-191: ⚠️ Potential issue | 🟡 Minor

Update regex to handle potential negative coordinates.

The regex r"@@[0-9-]+\t[0-9.\t]+##" only matches positive floats for coordinates. If bbox.y1 > page_height, the computed top would be negative, and the tag would be silently skipped by extract_positions().

🔧 Suggested fix
     `@staticmethod`
     def extract_positions(txt: str) -> list[tuple[list[int], float, float, float, float]]:
         poss = []
-        for tag in re.findall(r"@@[0-9-]+\t[0-9.\t]+##", txt):
+        for tag in re.findall(r"@@[0-9-]+\t[-0-9.\t]+##", txt):
             pn, left, right, top, bottom = tag.strip("#").strip("@").split("\t")
             left, right, top, bottom = float(left), float(right), float(top), float(bottom)
             poss.append(([int(p) - 1 for p in pn.split("-")], left, right, top, bottom))
         return poss
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@deepdoc/parser/opendataloader_parser.py` around lines 184 - 191,
extract_positions currently uses the regex r"@@[0-9-]+\t[0-9.\t]+##" which skips
negative coordinate values; update the regex used in re.findall inside
extract_positions to explicitly allow optional leading minus signs for each
numeric coordinate (e.g. require four tab-separated numbers with optional '-'
and decimals: page numbers part remains [0-9-]+ and coordinates use -?[0-9.]+
for each of left,right,top,bottom) so negative top/bottom values are matched,
and keep the existing split and conversion logic the same.
🧹 Nitpick comments (2)
docker/opendataloader-service/Dockerfile (1)

1-19: Consider running the container as a non-root user.

Running containers as root increases the attack surface. Adding a non-root user is a security best practice, especially for network-facing services.

🔒 Suggested fix to add a non-root user
 FROM python:3.12-slim

 # Install JRE — OpenDataLoader requires Java 11+.
 # This keeps the JRE dependency isolated inside this container;
 # the RAGFlow host does not need Java installed.
 RUN apt-get update && apt-get install -y --no-install-recommends \
         default-jre-headless \
     && rm -rf /var/lib/apt/lists/*

+RUN useradd --create-home --shell /bin/bash appuser
+
 WORKDIR /app

 COPY requirements.txt .
 RUN pip install --no-cache-dir -r requirements.txt

 COPY app.py .

+USER appuser
+
 EXPOSE 9383

 CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "9383"]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docker/opendataloader-service/Dockerfile` around lines 1 - 19, Add a non-root
user and switch to it in the Dockerfile to avoid running the service as root:
create a user/group (e.g., appuser), create or chown the WORKDIR (/app) to that
user, set a sensible HOME if needed, and add a USER appuser line before the CMD
that runs uvicorn (the existing CMD ["uvicorn", "app:app", "--host", "0.0.0.0",
"--port", "9383"]). Ensure the created user has no password and minimal
privileges and that pip-installed files and the copied app.py are owned by that
user so the process can run without root.
docker/opendataloader-service/app.py (1)

89-94: Consider adding a timeout or progress indicator for long-running conversions.

The convert() call on line 91 has no timeout mechanism. For very large PDFs, this could block the worker thread indefinitely. While FastAPI's default timeout may help, consider adding explicit timeout handling or async processing for production use.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docker/opendataloader-service/app.py` around lines 89 - 94, The convert()
call in the request handler (the block logging "Converting '{filename}' ..." and
calling opendataloader_pdf.convert) needs a timeout/progress strategy to avoid
blocking the worker: either wrap the conversion in an asyncio timeout (e.g.,
asyncio.wait_for(opendataloader_pdf.convert(...), timeout=SECONDS)) if convert
is async, or run it in a ThreadPoolExecutor via
asyncio.get_running_loop().run_in_executor and call
future.result(timeout=SECONDS) if convert is sync; alternatively implement
background job processing (enqueue job, return job id, and expose a status
endpoint) for long-running conversions — pick one approach and update the
handler around opendataloader_pdf.convert, ensuring exceptions on timeout are
caught and return a 202 for background jobs or a 504/500 with a clear message on
timeout.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docker/.env`:
- Line 298: Remove the duplicate MYSQL_PORT declaration by deleting the
redundant line that sets MYSQL_PORT=3307 so the original MYSQL_PORT=3306 remains
in effect; ensure only one MYSQL_PORT variable exists (referencing MYSQL_PORT)
to avoid overriding the intended port for MySQL connectivity.

In `@docker/opendataloader-service/requirements.txt`:
- Around line 1-3: The requirements.txt currently lists unpinned packages
(fastapi, uvicorn[standard], opendataloader-pdf); pin fastapi to a version that
fixes CVE-2024-24762 (e.g., fastapi==0.109.1) and pin the other packages to
explicit, tested versions (for example uvicorn[standard]==0.22.0 and
opendataloader-pdf==<tested_version>) so builds are reproducible and the FastAPI
ReDoS fix is enforced; update the entries for fastapi, uvicorn[standard], and
opendataloader-pdf accordingly and run your dependency install/test workflow to
verify compatibility.

In `@docs/guides/dataset/select_pdf_parser.md`:
- Around line 77-84: The fenced code blocks containing the environment variable
lines for COMPOSE_PROFILES and OPENDATALOADER_APISERVER are missing language
specifiers; update the two backtick-fenced blocks that contain
"COMPOSE_PROFILES=${COMPOSE_PROFILES},opendataloader" and
"OPENDATALOADER_APISERVER=http://opendataloader:9383" to include a language tag
(e.g., ```bash) so they render with proper syntax highlighting and
accessibility.

---

Duplicate comments:
In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 184-191: extract_positions currently uses the regex
r"@@[0-9-]+\t[0-9.\t]+##" which skips negative coordinate values; update the
regex used in re.findall inside extract_positions to explicitly allow optional
leading minus signs for each numeric coordinate (e.g. require four tab-separated
numbers with optional '-' and decimals: page numbers part remains [0-9-]+ and
coordinates use -?[0-9.]+ for each of left,right,top,bottom) so negative
top/bottom values are matched, and keep the existing split and conversion logic
the same.

---

Nitpick comments:
In `@docker/opendataloader-service/app.py`:
- Around line 89-94: The convert() call in the request handler (the block
logging "Converting '{filename}' ..." and calling opendataloader_pdf.convert)
needs a timeout/progress strategy to avoid blocking the worker: either wrap the
conversion in an asyncio timeout (e.g.,
asyncio.wait_for(opendataloader_pdf.convert(...), timeout=SECONDS)) if convert
is async, or run it in a ThreadPoolExecutor via
asyncio.get_running_loop().run_in_executor and call
future.result(timeout=SECONDS) if convert is sync; alternatively implement
background job processing (enqueue job, return job id, and expose a status
endpoint) for long-running conversions — pick one approach and update the
handler around opendataloader_pdf.convert, ensuring exceptions on timeout are
caught and return a 202 for background jobs or a 504/500 with a clear message on
timeout.

In `@docker/opendataloader-service/Dockerfile`:
- Around line 1-19: Add a non-root user and switch to it in the Dockerfile to
avoid running the service as root: create a user/group (e.g., appuser), create
or chown the WORKDIR (/app) to that user, set a sensible HOME if needed, and add
a USER appuser line before the CMD that runs uvicorn (the existing CMD
["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "9383"]). Ensure the
created user has no password and minimal privileges and that pip-installed files
and the copied app.py are owned by that user so the process can run without
root.
🪄 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: 36f37a67-4110-4ad2-b442-adf164f9b7dc

📥 Commits

Reviewing files that changed from the base of the PR and between 36a9eeb and 0ffd4dc.

📒 Files selected for processing (11)
  • common/constants.py
  • deepdoc/parser/opendataloader_parser.py
  • docker/.env
  • docker/docker-compose.yml
  • docker/entrypoint.sh
  • docker/opendataloader-service/Dockerfile
  • docker/opendataloader-service/app.py
  • docker/opendataloader-service/requirements.txt
  • docs/guides/dataset/select_pdf_parser.md
  • rag/app/naive.py
  • rag/flow/parser/parser.py
✅ Files skipped from review due to trivial changes (2)
  • docker/entrypoint.sh
  • common/constants.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • rag/flow/parser/parser.py
  • rag/app/naive.py

Comment thread docker/.env Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 8

♻️ Duplicate comments (1)
rag/flow/parser/parser.py (1)

461-466: ⚠️ Potential issue | 🟡 Minor

hybrid/image_output/sanitize are not forwarded to parse_pdf here.

OpenDataLoaderParser.parse_pdf still exposes hybrid, image_output, and sanitize as keyword arguments, and rag/app/naive.py:by_opendataloader propagates them via **kwargs. The flow branch ignores them, so flow-mode parses can't apply sanitize or select a non-default hybrid/image_output even when the operator configures them. Consider either pulling them from the resolved OCR model config (since config has moved to the model-provider UI) or, at minimum, reading the OPENDATALOADER_* env vars here to stay consistent with the naive pipeline.

🧹 Nitpick comments (4)
deepdoc/parser/opendataloader_parser.py (1)

380-398: Add backoff between retry attempts.

The retry loop retries immediately on failure with no delay. For transient network issues (jitter, brief service restarts) this burns all 3 attempts in milliseconds and is effectively no retry at all. You mentioned exponential backoff was planned — please wire it in here (or use a requests.Session with urllib3.util.Retry for a backoff on the /file_parse POST).

🔧 Minimal fix
+        import time
         headers = {"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}
         last_exc: Exception | None = None
         for attempt in range(1, 4):
             try:
                 self.logger.info(f"[OpenDataLoader] POST {self.api_url}/file_parse for '{filename}' (attempt {attempt})")
                 resp = requests.post(
                     url=f"{self.api_url}/file_parse",
                     files={"file": (filename, pdf_bytes, "application/pdf")},
                     data=form_data,
                     headers=headers,
                     timeout=self.timeout,
                 )
                 resp.raise_for_status()
                 result = resp.json()
                 break
             except Exception as exc:
                 last_exc = exc
                 self.logger.warning(f"[OpenDataLoader] attempt {attempt} failed: {exc}")
+                if attempt < 3:
+                    time.sleep(2 ** (attempt - 1))
         else:
             raise RuntimeError(f"[OpenDataLoader] service call failed after 3 attempts: {last_exc}") from last_exc
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@deepdoc/parser/opendataloader_parser.py` around lines 380 - 398, The retry
loop for the POST to self.api_url/file_parse (inside the OpenDataLoader code
that logs via self.logger and currently calls requests.post) needs an
exponential backoff with jitter so retries aren’t immediate; either wrap the
POST in a backoff sleep (e.g., after a failed attempt sleep for base_delay *
2**(attempt-1) plus a small random jitter) inside the except before the next
loop iteration, or replace direct requests.post with a requests.Session
configured with urllib3.util.Retry (mounting an HTTPAdapter) to apply
exponential backoff and retry only on idempotent/expected errors; preserve
existing last_exc handling and the final RuntimeError raise-from behavior.
api/apps/llm_app.py (1)

396-396: list endpoint also lists OCR/OpenDataLoader models — consider adding ensure_opendataloader_from_env there too.

my_llms now calls ensure_opendataloader_from_env (line 396), but list_app below (line 446) only calls ensure_mineru_from_env. Tenants with only OPENDATALOADER_* env vars set will not see an auto-provisioned model via /list until they first hit /my_llms. This is the same gap PaddleOCR already has, so not a blocker, but worth fixing consistently for both OCR providers if the intent is env-based provisioning.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/llm_app.py` at line 396, The list endpoint (list_app) currently only
calls TenantLLMService.ensure_mineru_from_env, so tenants with only
OPENDATALOADER_* env vars won't get auto-provisioned until they hit my_llms; add
a call to TenantLLMService.ensure_opendataloader_from_env in the list_app flow
(the same place ensure_mineru_from_env is invoked) so both OCR providers are
provisioned from env vars when listing models.
rag/app/naive.py (1)

881-892: opendataloader_llm_name not forwarded from chunk() call site.

Unlike mineru_llm_name and paddleocr_llm_name, the chunk() dispatcher does not pass opendataloader_llm_name=parser_model_name to the parser. As a result, by_opendataloader always falls back to the TenantLLMService.query path and never receives the model name resolved from normalize_layout_recognizer. Consider adding it for consistency:

♻️ Proposed change
             mineru_llm_name=parser_model_name,
             paddleocr_llm_name=parser_model_name,
+            opendataloader_llm_name=parser_model_name,
             **kwargs,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rag/app/naive.py` around lines 881 - 892, The call to parser in chunk() is
missing the opendataloader_llm_name argument so the resolved model
(parser_model_name) isn't passed through; update the parser(...) invocation in
rag/app/naive.py (the line assigning sections, tables, pdf_parser) to include
opendataloader_llm_name=parser_model_name so by_opendataloader receives the
normalized model name, and verify any downstream uses of opendataloader_llm_name
(e.g., in by_opendataloader or TenantLLMService.query dispatch) consume that
value.
web/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsx (1)

61-66: Unnecessary as any cast.

values is already typed OpenDataLoaderFormValues, which matches T in IModalProps<OpenDataLoaderFormValues>. Drop the cast to keep type safety.

-    const ret = await onOk?.(values as any);
+    const ret = await onOk?.(values);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@web/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsx`
around lines 61 - 66, The handleOk function is casting values to any
unnecessarily—since values is already typed as OpenDataLoaderFormValues
(matching the modal generic IModalProps<OpenDataLoaderFormValues>), remove the
"as any" cast in the call to onOk and pass values directly; update the call site
inside handleOk (and ensure the onOk parameter/type in
IModalProps/OpenDataLoaderModal props is correctly typed to accept
OpenDataLoaderFormValues) so TypeScript preserves type safety while still hiding
the modal via hideModal when onOk returns truthy.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 170-184: The guard in _make_line_tag must also reject non-positive
bbox.page_no to avoid negative indexing and emitting invalid tags; update the
check in _make_line_tag to return "" if bbox.page_no is None or bbox.page_no <=
0 or bbox.page_no > len(self.page_images) (use self.page_images and bbox.page_no
symbols), so you never index self.page_images with an out-of-range or
non-positive index and you never emit a tag with an invalid page number that
extract_positions/crop would later mis-handle.
- Line 129: The assignment self.timeout =
int(os.environ.get("OPENDATALOADER_TIMEOUT", "600")) can raise ValueError for
non-integer env values; change it to read the env var into a temp (e.g., val =
os.environ.get("OPENDATALOADER_TIMEOUT")), attempt to convert with a try/except
around int(val), and on exception (or if val is empty) set self.timeout to the
default 600 and emit a warning/log (use the module/class logger or
warnings.warn) that includes the bad value and that the default is used; keep
the symbol self.timeout and OPENDATALOADER_TIMEOUT in the fix so it’s easy to
locate.

In `@rag/llm/ocr_model.py`:
- Around line 171-186: The constructor currently sets self.api_url, self.api_key
and self.timeout before calling OpenDataLoaderParser.__init__, then reassigns
them afterward, which clobbers UI-provided values; fix by calling
OpenDataLoaderParser.__init__(self) first and then performing the
resolved-config assignments for self.api_url, self.api_key and self.timeout
(using the existing _resolve_config logic and redaction logic over config) so
parent initialization cannot overwrite UI-provided attributes and you eliminate
the duplicate pre-parent assignments.
- Line 173: The int() call on the value returned by
_resolve_config("opendataloader_timeout", "OPENDATALOADER_TIMEOUT", "600") will
raise if the UI supplies an empty string; change the pattern to coerce an
empty/invalid string to the default before converting to int (e.g., read the raw
value into a temp, if temp is falsy or not a valid integer use "600" as the
fallback, then call int on that fallback) for the assignment to self.timeout;
apply the same defensive-fallback fix to the duplicate _resolve_config usage
referenced later in the file so both conversions never call int("").

In `@web/src/constants/llm.ts`:
- Line 65: The IconMap is missing an entry for the new factory name
OpenDataLoader which causes LlmIcon (which uses IconMap[name as keyof typeof
IconMap]) to return undefined; add an entry mapping the enum key to the asset
key like [LLMFactory.OpenDataLoader]: 'opendataloader' in the IconMap next to
the other mappings (e.g., alongside MinerU/PaddleOCR) and add the corresponding
icon asset files (including theme variants if your build expects e.g.
opendataloader-dark/opendataloader-bright) so the provider renders an icon
correctly.

In
`@web/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsx`:
- Around line 96-101: The opendataloader_api_key field is rendered as a plain
text Input exposing the secret; update the form item for name
"opendataloader_api_key" (RAGFlowFormItem) to use a password-style input instead
of plain text—either set the Input to type="password" or replace it with the
project's Password/SecretInput component (matching how other secret fields are
implemented) and preserve the placeholder/label translation keys.
- Around line 107-124: Replace the raw HTML buttons inside DialogFooter with the
project's shadcn UI button components: use the secondary Button (or plain
Button) for the cancel action and ButtonLoading for the submit so the loading
spinner is shown; keep the onClick={hideModal}, type and disabled={loading}
semantics but swap className="btn btn-secondary" / "btn btn-primary" for the
appropriate imported Button / ButtonLoading components and pass
loading={loading} to ButtonLoading and onClick={hideModal} to the cancel Button
to match other modals like bedrock-modal.
- Around line 14-30: The module-level call to t (imported from 'i18next') inside
FormSchema causes untranslated keys because it runs before i18n initialization;
remove the top-level t import and move construction of FormSchema into the React
component so it uses the t returned by useTranslation(), e.g. build the z.object
schema inside the component and wrap it with useMemo (depend on i18n or the t
function) so validation messages use translated strings; update any references
to the existing FormSchema to use the memoized schema instead.

---

Nitpick comments:
In `@api/apps/llm_app.py`:
- Line 396: The list endpoint (list_app) currently only calls
TenantLLMService.ensure_mineru_from_env, so tenants with only OPENDATALOADER_*
env vars won't get auto-provisioned until they hit my_llms; add a call to
TenantLLMService.ensure_opendataloader_from_env in the list_app flow (the same
place ensure_mineru_from_env is invoked) so both OCR providers are provisioned
from env vars when listing models.

In `@deepdoc/parser/opendataloader_parser.py`:
- Around line 380-398: The retry loop for the POST to self.api_url/file_parse
(inside the OpenDataLoader code that logs via self.logger and currently calls
requests.post) needs an exponential backoff with jitter so retries aren’t
immediate; either wrap the POST in a backoff sleep (e.g., after a failed attempt
sleep for base_delay * 2**(attempt-1) plus a small random jitter) inside the
except before the next loop iteration, or replace direct requests.post with a
requests.Session configured with urllib3.util.Retry (mounting an HTTPAdapter) to
apply exponential backoff and retry only on idempotent/expected errors; preserve
existing last_exc handling and the final RuntimeError raise-from behavior.

In `@rag/app/naive.py`:
- Around line 881-892: The call to parser in chunk() is missing the
opendataloader_llm_name argument so the resolved model (parser_model_name) isn't
passed through; update the parser(...) invocation in rag/app/naive.py (the line
assigning sections, tables, pdf_parser) to include
opendataloader_llm_name=parser_model_name so by_opendataloader receives the
normalized model name, and verify any downstream uses of opendataloader_llm_name
(e.g., in by_opendataloader or TenantLLMService.query dispatch) consume that
value.

In
`@web/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsx`:
- Around line 61-66: The handleOk function is casting values to any
unnecessarily—since values is already typed as OpenDataLoaderFormValues
(matching the modal generic IModalProps<OpenDataLoaderFormValues>), remove the
"as any" cast in the call to onOk and pass values directly; update the call site
inside handleOk (and ensure the onOk parameter/type in
IModalProps/OpenDataLoaderModal props is correctly typed to accept
OpenDataLoaderFormValues) so TypeScript preserves type safety while still hiding
the modal via hideModal when onOk returns truthy.
🪄 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: 363ef624-685f-4683-839a-e7b2943c6d7d

📥 Commits

Reviewing files that changed from the base of the PR and between 0ffd4dc and d5c6bc5.

📒 Files selected for processing (13)
  • api/apps/llm_app.py
  • api/db/services/tenant_llm_service.py
  • conf/llm_factories.json
  • deepdoc/parser/opendataloader_parser.py
  • docs/guides/dataset/select_pdf_parser.md
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • rag/llm/ocr_model.py
  • test/unit_test/deepdoc/parser/test_opendataloader_parser.py
  • web/src/constants/llm.ts
  • web/src/pages/user-setting/setting-model/hooks.tsx
  • web/src/pages/user-setting/setting-model/index.tsx
  • web/src/pages/user-setting/setting-model/modal/opendataloader-modal/index.tsx
✅ Files skipped from review due to trivial changes (2)
  • docs/guides/dataset/select_pdf_parser.md
  • conf/llm_factories.json

Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread deepdoc/parser/opendataloader_parser.py Resolved
Comment thread rag/llm/ocr_model.py Resolved
Comment thread rag/llm/ocr_model.py Resolved
Comment thread web/src/constants/llm.ts Resolved
@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
I've updated the PR as you wanted.
Would you review the PR again, please?

23.04.2026_09.10.43_REC.mp4

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
Would you please review the PR again?
I've re-triggered CI due to CI failure with slow server startup (connection refused).
I'd be happy my contribution will be merged if it's no need any updates for now.
Thanks.

@yingfeng

Copy link
Copy Markdown
Member

I meant to remove content from documentation because those environment variable settings are not used any more.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
Could you please review the PR once more?

@yingfeng

Copy link
Copy Markdown
Member

I can still see lots of contents required to be deleted

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

I can still see lots of contents required to be deleted

Hi, @yingfeng
Would you please clarify them, since I think there is no opendataloader service defined in any files?

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

@CodeRabbit
What is the remaining works relevant to opendataloader setting?

@coderabbitai

coderabbitai Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

Let me check the current state of the relevant files to identify what still needs to be removed.


🏁 Script executed:

#!/bin/bash
echo "=== docs/guides/dataset/select_pdf_parser.md ==="
fd "select_pdf_parser.md" --exec cat {}

echo ""
echo "=== docker/.env opendataloader references ==="
fd ".env" docker/ --exec grep -in "opendataloader" {} 2>/dev/null || echo "No .env found or no matches"

echo ""
echo "=== All files referencing OPENDATALOADER env vars ==="
rg -n "OPENDATALOADER_APISERVER|OPENDATALOADER_HYBRID|OPENDATALOADER_IMAGE_OUTPUT|OPENDATALOADER_SANITIZE|OPENDATALOADER_API_KEY|USE_OPENDATALOADER|OPENDATALOADER_VERSION|OPENDATALOADER_DELETE_OUTPUT|OPENDATALOADER_OUTPUT_DIR" --type-not=py --type-not=tsx --type-not=ts -l

echo ""
echo "=== Full content of those files ==="
rg -n "OPENDATALOADER_APISERVER|OPENDATALOADER_HYBRID|OPENDATALOADER_IMAGE_OUTPUT|OPENDATALOADER_SANITIZE|OPENDATALOADER_API_KEY|USE_OPENDATALOADER" --type-not=py --type-not=tsx --type-not=ts

echo ""
echo "=== docker-compose files with opendataloader ==="
fd "docker-compose" --exec grep -in "opendataloader" {} 2>/dev/null

echo ""
echo "=== entrypoint.sh opendataloader references ==="
fd "entrypoint.sh" --exec grep -in "opendataloader" {} 2>/dev/null

Length of output: 6439


@wdeveloper16: Based on my review of the current PR files, here is the specific remaining work that reviewer yingfeng is referring to:


Remaining item: docs/guides/dataset/select_pdf_parser.md

The documentation still contains an environment-variable-based setup section for OpenDataLoader that references the old approach (which has since been replaced by the UI-based Model Providers configuration). The following block needs to be removed or replaced:

To enable the OpenDataLoader parser, start it as a standalone service and point RAGFlow at it:

1. Add `opendataloader` to `COMPOSE_PROFILES` in `docker/.env`:
   COMPOSE_PROFILES=${COMPOSE_PROFILES},opendataloader

2. Set the API endpoint so RAGFlow knows where to reach the service:
   OPENDATALOADER_APISERVER=http://opendataloader:9383

3. Build and start the service:
   docker compose up -d --build opendataloader

The `opendataloader` container bundles Java 11+ via `default-jre-headless`; the RAGFlow host does not need a JRE installed.

What to do

Since configuration is now handled via the Model Providers page in the UI (the OpenDataLoaderModal you added), this env-var section in the docs should be deleted and replaced with instructions similar to MinerU's — telling users to configure the OPENDATALOADER_APISERVER and optional OPENDATALOADER_API_KEY from the Model providers page in the web UI, rather than through environment variables in docker/.env.

The good news is:

  • ✅ docker/.env — already clean (no OpenDataLoader env vars)
  • ✅ docker-compose files — already clean (no OpenDataLoader profile)
  • ✅ docker/entrypoint.sh — already clean
  • ❌ docs/guides/dataset/select_pdf_parser.md — still has the old env-var block that needs removal/update

That appears to be the only remaining content yingfeng is asking you to delete.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng.
I've removed all docs relevant to opendataloader env settings.
Could you please review the PR, please?
Thanks.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
Would be able to review this PR?

@yingfeng

Copy link
Copy Markdown
Member

Hi, @yingfeng Would be able to review this PR?

I've asked you to recover the documentation but received no responses.

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng Would be able to review this PR?

I've asked you to recover the documentation but received no responses.

Sorry for the inconvenience.
I've already done it.
Could you please review it again?

@yingfeng

Copy link
Copy Markdown
Member

Hi, @yingfeng Would be able to review this PR?

I've asked you to recover the documentation but received no responses.

Sorry for the inconvenience. I've already done it. Could you please review it again?

screenshot 2026-04-24 20 28 53

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
Just done!
Would you please review it once more?
Thanks., ❤️

@wdeveloper16

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng
All done! CI is green.
Could you review the PR, please?

@yingfeng
yingfeng merged commit 78188ce into infiniflow:main Apr 24, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 2, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 📖 documentation Improvements or additions to documentation 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: implementation of opendataloader

3 participants