mirror of
https://github.com/infiniflow/ragflow.git
synced 2026-05-26 18:57:20 +08:00
### 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](https://github.com/opendataloader-project/opendataloader-pdf)) as a new optional backend, giving users a deterministic, local-first alternative with competitive table extraction accuracy. ### Type of change - [x] New Feature (non-breaking change which adds functionality) - [x] 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:** ```bash 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 ```
206 lines
8.3 KiB
Python
206 lines
8.3 KiB
Python
#
|
|
# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
#
|
|
import json
|
|
import logging
|
|
import os
|
|
from typing import Any, Optional
|
|
|
|
from deepdoc.parser.mineru_parser import MinerUParser
|
|
from deepdoc.parser.opendataloader_parser import OpenDataLoaderParser
|
|
from deepdoc.parser.paddleocr_parser import PaddleOCRParser
|
|
|
|
|
|
class Base:
|
|
def __init__(self, key: str | dict, model_name: str, **kwargs):
|
|
self.model_name = model_name
|
|
|
|
def parse_pdf(self, filepath: str, binary=None, **kwargs) -> tuple[Any, Any]:
|
|
raise NotImplementedError("Please implement parse_pdf!")
|
|
|
|
|
|
class MinerUOcrModel(Base, MinerUParser):
|
|
_FACTORY_NAME = "MinerU"
|
|
|
|
def __init__(self, key: str | dict, model_name: str, **kwargs):
|
|
Base.__init__(self, key, model_name, **kwargs)
|
|
raw_config = {}
|
|
if key:
|
|
try:
|
|
raw_config = json.loads(key)
|
|
except Exception:
|
|
raw_config = {}
|
|
|
|
# nested {"api_key": {...}} from UI
|
|
# flat {"MINERU_*": "..."} payload auto-provisioned from env vars
|
|
config = raw_config.get("api_key", raw_config)
|
|
if not isinstance(config, dict):
|
|
config = {}
|
|
|
|
def _resolve_config(key: str, env_key: str, default=""):
|
|
# lower-case keys (UI), upper-case MINERU_* (env auto-provision), env vars
|
|
return config.get(key, config.get(env_key, os.environ.get(env_key, default)))
|
|
|
|
self.mineru_api = _resolve_config("mineru_apiserver", "MINERU_APISERVER", "")
|
|
self.mineru_output_dir = _resolve_config("mineru_output_dir", "MINERU_OUTPUT_DIR", "")
|
|
self.mineru_backend = _resolve_config("mineru_backend", "MINERU_BACKEND", "pipeline")
|
|
self.mineru_server_url = _resolve_config("mineru_server_url", "MINERU_SERVER_URL", "")
|
|
self.mineru_delete_output = bool(int(_resolve_config("mineru_delete_output", "MINERU_DELETE_OUTPUT", 1)))
|
|
|
|
# Redact sensitive config keys before logging
|
|
redacted_config = {}
|
|
for k, v in config.items():
|
|
if any(sensitive_word in k.lower() for sensitive_word in ("key", "password", "token", "secret")):
|
|
redacted_config[k] = "[REDACTED]"
|
|
else:
|
|
redacted_config[k] = v
|
|
logging.info(f"Parsed MinerU config (sensitive fields redacted): {redacted_config}")
|
|
|
|
MinerUParser.__init__(self, mineru_api=self.mineru_api, mineru_server_url=self.mineru_server_url)
|
|
|
|
def check_available(self, backend: Optional[str] = None, server_url: Optional[str] = None) -> tuple[bool, str]:
|
|
backend = backend or self.mineru_backend
|
|
server_url = server_url or self.mineru_server_url
|
|
return self.check_installation(backend=backend, server_url=server_url)
|
|
|
|
def parse_pdf(self, filepath: str, binary=None, callback=None, parse_method: str = "raw", **kwargs):
|
|
ok, reason = self.check_available()
|
|
if not ok:
|
|
raise RuntimeError(f"MinerU server not accessible: {reason}")
|
|
|
|
sections, tables = MinerUParser.parse_pdf(
|
|
self,
|
|
filepath=filepath,
|
|
binary=binary,
|
|
callback=callback,
|
|
output_dir=self.mineru_output_dir,
|
|
backend=self.mineru_backend,
|
|
server_url=self.mineru_server_url,
|
|
delete_output=self.mineru_delete_output,
|
|
parse_method=parse_method,
|
|
**kwargs,
|
|
)
|
|
return sections, tables
|
|
|
|
|
|
class PaddleOCROcrModel(Base, PaddleOCRParser):
|
|
_FACTORY_NAME = "PaddleOCR"
|
|
|
|
def __init__(self, key: str | dict, model_name: str, **kwargs):
|
|
Base.__init__(self, key, model_name, **kwargs)
|
|
raw_config = {}
|
|
if key:
|
|
try:
|
|
raw_config = json.loads(key)
|
|
except Exception:
|
|
raw_config = {}
|
|
|
|
# nested {"api_key": {...}} from UI
|
|
# flat {"PADDLEOCR_*": "..."} payload auto-provisioned from env vars
|
|
config = raw_config.get("api_key", raw_config)
|
|
if not isinstance(config, dict):
|
|
config = {}
|
|
|
|
def _resolve_config(key: str, env_key: str, default=""):
|
|
# lower-case keys (UI), upper-case PADDLEOCR_* (env auto-provision), env vars
|
|
return config.get(key, config.get(env_key, os.environ.get(env_key, default)))
|
|
|
|
self.paddleocr_api_url = _resolve_config("paddleocr_api_url", "PADDLEOCR_API_URL", "")
|
|
self.paddleocr_algorithm = _resolve_config("paddleocr_algorithm", "PADDLEOCR_ALGORITHM", "PaddleOCR-VL")
|
|
self.paddleocr_access_token = _resolve_config("paddleocr_access_token", "PADDLEOCR_ACCESS_TOKEN", None)
|
|
|
|
# Redact sensitive config keys before logging
|
|
redacted_config = {}
|
|
for k, v in config.items():
|
|
if any(sensitive_word in k.lower() for sensitive_word in ("key", "password", "token", "secret")):
|
|
redacted_config[k] = "[REDACTED]"
|
|
else:
|
|
redacted_config[k] = v
|
|
logging.info(f"Parsed PaddleOCR config (sensitive fields redacted): {redacted_config}")
|
|
|
|
PaddleOCRParser.__init__(
|
|
self,
|
|
api_url=self.paddleocr_api_url,
|
|
access_token=self.paddleocr_access_token,
|
|
algorithm=self.paddleocr_algorithm,
|
|
)
|
|
|
|
def check_available(self) -> tuple[bool, str]:
|
|
return self.check_installation()
|
|
|
|
def parse_pdf(self, filepath: str, binary=None, callback=None, parse_method: str = "raw", **kwargs):
|
|
ok, reason = self.check_available()
|
|
if not ok:
|
|
raise RuntimeError(f"PaddleOCR server not accessible: {reason}")
|
|
|
|
sections, tables = PaddleOCRParser.parse_pdf(self, filepath=filepath, binary=binary, callback=callback, parse_method=parse_method, **kwargs)
|
|
return sections, tables
|
|
|
|
|
|
class OpenDataLoaderOcrModel(Base, OpenDataLoaderParser):
|
|
_FACTORY_NAME = "OpenDataLoader"
|
|
|
|
def __init__(self, key: str | dict, model_name: str, **kwargs):
|
|
Base.__init__(self, key, model_name, **kwargs)
|
|
raw_config = {}
|
|
if key:
|
|
try:
|
|
raw_config = json.loads(key)
|
|
except Exception:
|
|
raw_config = {}
|
|
|
|
config = raw_config.get("api_key", raw_config)
|
|
if not isinstance(config, dict):
|
|
config = {}
|
|
|
|
def _resolve_config(key: str, env_key: str, default=""):
|
|
return config.get(key, config.get(env_key, os.environ.get(env_key, default)))
|
|
|
|
redacted_config = {}
|
|
for k, v in config.items():
|
|
if any(s in k.lower() for s in ("key", "password", "token", "secret")):
|
|
redacted_config[k] = "[REDACTED]"
|
|
else:
|
|
redacted_config[k] = v
|
|
logging.info(f"Parsed OpenDataLoader config (sensitive fields redacted): {redacted_config}")
|
|
|
|
OpenDataLoaderParser.__init__(self)
|
|
self.api_url = _resolve_config("opendataloader_apiserver", "OPENDATALOADER_APISERVER", "").rstrip("/")
|
|
self.api_key = _resolve_config("opendataloader_api_key", "OPENDATALOADER_API_KEY", "").strip()
|
|
timeout_val = _resolve_config("opendataloader_timeout", "OPENDATALOADER_TIMEOUT", "600") or "600"
|
|
try:
|
|
self.timeout = int(timeout_val)
|
|
except (TypeError, ValueError):
|
|
self.timeout = 600
|
|
|
|
def check_available(self) -> tuple[bool, str]:
|
|
ok = self.check_installation()
|
|
return ok, "" if ok else "OpenDataLoader service not reachable"
|
|
|
|
def parse_pdf(self, filepath: str, binary=None, callback=None, parse_method: str = "raw", **kwargs):
|
|
ok, reason = self.check_available()
|
|
if not ok:
|
|
raise RuntimeError(f"OpenDataLoader service not accessible: {reason}")
|
|
|
|
sections, tables = OpenDataLoaderParser.parse_pdf(
|
|
self,
|
|
filepath=filepath,
|
|
binary=binary,
|
|
callback=callback,
|
|
parse_method=parse_method,
|
|
**kwargs,
|
|
)
|
|
return sections, tables
|