Repository navigation
Feat: add OpenDataLoader PDF parser backend (#14058) - #14097
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughIntroduces 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
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[]
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 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 |
|
Hi, @ZhenhangTung |
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
deepdoc/parser/opendataloader_parser.pydocker/entrypoint.shdocs/guides/dataset/select_pdf_parser.mdrag/app/naive.pyrag/flow/parser/parser.pyweb/src/components/layout-recognize-form-field.tsx
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
… flip, per-request workdir, forward all env flags (infiniflow#14058)
8cc0c5a to
6d4be1d
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (1)
docker/entrypoint.sh (1)
241-247:⚠️ Potential issue | 🟠 MajorReject unsupported Java versions here too.
This gate only checks that
javaexists. With Java 8 on PATH the container still installs OpenDataLoader, butOpenDataLoaderParser.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
📒 Files selected for processing (6)
deepdoc/parser/opendataloader_parser.pydocker/entrypoint.shdocs/guides/dataset/select_pdf_parser.mdrag/app/naive.pyrag/flow/parser/parser.pyweb/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
…layout types, capture odl_tables, robust env bool parsing (infiniflow#14058)
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
deepdoc/parser/opendataloader_parser.py (1)
391-399:⚠️ Potential issue | 🟠 MajorAlways tear down the request-scoped workdir in
finally.
workdiris already unique per parse, sodelete_output=Truecan safely remove that subtree even whenoutput_diris configured. The currentcleanup_workdir = output_dir is Nonesplit leaves empty request dirs behind on the happy path and skips cleanup entirely for any exception afterconvert().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
📒 Files selected for processing (2)
deepdoc/parser/opendataloader_parser.pyrag/flow/parser/parser.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/flow/parser/parser.py
|
@wdeveloper16 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:
|
|
@wdeveloper16 |
|
Okay, no problem at all. |
|
Just done! @xugangqiang |
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
deepdoc/parser/opendataloader_parser.py (1)
184-191:⚠️ Potential issue | 🟡 MinorUpdate regex to handle potential negative coordinates.
The regex
r"@@[0-9-]+\t[0-9.\t]+##"only matches positive floats for coordinates. Ifbbox.y1 > page_height, the computedtopwould be negative, and the tag would be silently skipped byextract_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
📒 Files selected for processing (11)
common/constants.pydeepdoc/parser/opendataloader_parser.pydocker/.envdocker/docker-compose.ymldocker/entrypoint.shdocker/opendataloader-service/Dockerfiledocker/opendataloader-service/app.pydocker/opendataloader-service/requirements.txtdocs/guides/dataset/select_pdf_parser.mdrag/app/naive.pyrag/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
There was a problem hiding this comment.
Actionable comments posted: 8
♻️ Duplicate comments (1)
rag/flow/parser/parser.py (1)
461-466:⚠️ Potential issue | 🟡 Minor
hybrid/image_output/sanitizeare not forwarded toparse_pdfhere.
OpenDataLoaderParser.parse_pdfstill exposeshybrid,image_output, andsanitizeas keyword arguments, andrag/app/naive.py:by_opendataloaderpropagates them via**kwargs. The flow branch ignores them, so flow-mode parses can't applysanitizeor select a non-defaulthybrid/image_outputeven 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 theOPENDATALOADER_*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.Sessionwithurllib3.util.Retryfor a backoff on the/file_parsePOST).🔧 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:listendpoint also lists OCR/OpenDataLoader models — consider addingensure_opendataloader_from_envthere too.
my_llmsnow callsensure_opendataloader_from_env(line 396), butlist_appbelow (line 446) only callsensure_mineru_from_env. Tenants with onlyOPENDATALOADER_*env vars set will not see an auto-provisioned model via/listuntil 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_namenot forwarded fromchunk()call site.Unlike
mineru_llm_nameandpaddleocr_llm_name, thechunk()dispatcher does not passopendataloader_llm_name=parser_model_nameto the parser. As a result,by_opendataloaderalways falls back to theTenantLLMService.querypath and never receives the model name resolved fromnormalize_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: Unnecessaryas anycast.
valuesis already typedOpenDataLoaderFormValues, which matchesTinIModalProps<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
📒 Files selected for processing (13)
api/apps/llm_app.pyapi/db/services/tenant_llm_service.pyconf/llm_factories.jsondeepdoc/parser/opendataloader_parser.pydocs/guides/dataset/select_pdf_parser.mdrag/app/naive.pyrag/flow/parser/parser.pyrag/llm/ocr_model.pytest/unit_test/deepdoc/parser/test_opendataloader_parser.pyweb/src/constants/llm.tsweb/src/pages/user-setting/setting-model/hooks.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/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
|
Hi, @yingfeng 23.04.2026_09.10.43_REC.mp4 |
|
Hi, @yingfeng |
|
I meant to remove content from documentation because those environment variable settings are not used any more. |
|
Hi, @yingfeng |
|
I can still see lots of contents required to be deleted |
Hi, @yingfeng |
|
@CodeRabbit |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainLet me check the current state of the relevant files to identify what still needs to be removed. 🏁 Script executed: Length of output: 6439
Remaining item:
|
|
Hi, @yingfeng. |
|
Hi, @yingfeng |
I've asked you to recover the documentation but received no responses. |
Sorry for the inconvenience. |
|
|
Hi, @yingfeng |
|
Hi, @yingfeng |

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
Changes
Backend
deepdoc/parser/opendataloader_parser.py— newOpenDataLoaderParserclass inheritingRAGFlowPdfParser. Implementscheck_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— newby_opendataloader()wrapper, registered inPARSERSdict, added tochunk_token_num=0override 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 viaUSE_OPENDATALOADER=true, skips gracefully if Java is not on PATH.Frontend
web/src/components/layout-recognize-form-field.tsx—OpenDataLoaderadded toParseDocumentTypeenum 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
USE_OPENDATALOADERfalsetrueto installopendataloader-pdfon container startupOPENDATALOADER_VERSION==2.2.1)OPENDATALOADER_HYBRIDdocling-fast)OPENDATALOADER_IMAGE_OUTPUToff/embedded/externalOPENDATALOADER_OUTPUT_DIROPENDATALOADER_DELETE_OUTPUT10to retain intermediate files for debuggingOPENDATALOADER_SANITIZE1to filter prompt-injection patterns from outputDependencies
opendataloader-pdf(PyPI, Apache 2.0) — opt-in, not added topyproject.tomlcore deps. Installed byensure_opendataloader()at container startup whenUSE_OPENDATALOADER=true.javais not found.How to test
Standalone parser:
Benchmark vs Docling