2024-08-15 09:17:36 +08:00
|
|
|
|
#
|
2025-01-21 20:52:28 +08:00
|
|
|
|
# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
|
2024-08-15 09:17:36 +08:00
|
|
|
|
#
|
|
|
|
|
|
# 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.
|
|
|
|
|
|
#
|
|
|
|
|
|
|
2024-11-14 17:13:48 +08:00
|
|
|
|
import logging
|
2024-08-15 09:17:36 +08:00
|
|
|
|
import copy
|
|
|
|
|
|
import re
|
|
|
|
|
|
|
Fix: Remove hardcoded page limits causing parsing failures on large PDFs (>300 pages) (#14382)
### What problem does this PR solve?
Fixes #14196
## Problem
When using DeepDOC to parse large PDFs (over 1000 pages), the parser
silently truncated processing at 300 pages due to a hardcoded default
`page_to=299` in `RAGFlowPdfParser.__images__()`. This caused:
- **Errors** on pages beyond the limit
- **Poor image quality** as the parser attempted to compensate with
missing page data
- **Inconsistent chunk splitting** between full PDF imports and partial
imports
Additionally, the codebase scattered magic numbers (`299`, `600`,
`10000`, `100000`, `100000000`, `10000000000`, `10**9`) across 22 files
as sentinel values for "parse all pages", making future maintenance
error-prone.
## Root Cause
```python
# deepdoc/parser/pdf_parser.py (before)
def __images__(self, fnm, zoomin=3, page_from=0, page_to=299, callback=None):
# Only the first 300 pages were rendered; everything beyond was silently dropped
```
While most callers in `rag/app/*.py` correctly passed `to_page=100000`,
the base class `RAGFlowPdfParser.__call__()` and `parse_into_bboxes()`
invoked `__images__` **without** forwarding `page_from`/`page_to`,
falling back to the restrictive default of 299.
## Solution
### 1. Define constants in `common/constants.py`
```python
MAXIMUM_PAGE_NUMBER = 100000 # Used by the parsing layer
MAXIMUM_TASK_PAGE_NUMBER = MAXIMUM_PAGE_NUMBER * 1000 # Used by the task/DB layer
```
### 2. Replace all hardcoded sentinel values
| Layer | Files Changed | Old Values | New Value |
|---|---|---|---|
| **Deepdoc parsers** | `pdf_parser.py`, `mineru_parser.py`,
`docling_parser.py`, `opendataloader_parser.py`, `paddleocr_parser.py`,
`docx_parser.py` | `299`, `600`, `10**9`, `100000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Chunk parsers** | `naive.py`, `book.py`, `qa.py`, `one.py`,
`manual.py`, `paper.py`, `presentation.py`, `laws.py`, `resume.py`,
`email.py`, `table.py` | `100000`, `10000`, `10000000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Task/DB layer** | `db_models.py`, `task_service.py`,
`document_service.py`, `file_service.py` | `100000000` |
`MAXIMUM_TASK_PAGE_NUMBER` |
### 3. Fix `parse_into_bboxes()` missing parameters
Added `from_page`/`to_page` parameters to `parse_into_bboxes()` so that
the `rag/flow/parser/parser.py` DeepDOC path no longer falls back to the
restrictive default.
## Files Changed (22)
- `common/constants.py`
- `deepdoc/parser/pdf_parser.py`
- `deepdoc/parser/mineru_parser.py`
- `deepdoc/parser/docling_parser.py`
- `deepdoc/parser/opendataloader_parser.py`
- `deepdoc/parser/paddleocr_parser.py`
- `deepdoc/parser/docx_parser.py`
- `rag/app/naive.py`
- `rag/app/book.py`
- `rag/app/qa.py`
- `rag/app/one.py`
- `rag/app/manual.py`
- `rag/app/paper.py`
- `rag/app/presentation.py`
- `rag/app/laws.py`
- `rag/app/resume.py`
- `rag/app/email.py`
- `rag/app/table.py`
- `api/db/db_models.py`
- `api/db/services/task_service.py`
- `api/db/services/document_service.py`
- `api/db/services/file_service.py`
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
---------
Signed-off-by: noob <yixiao121314@outlook.com>
2026-04-27 06:57:20 +00:00
|
|
|
|
from common.constants import ParserType, MAXIMUM_PAGE_NUMBER
|
2024-08-15 09:17:36 +08:00
|
|
|
|
from io import BytesIO
|
2026-04-03 19:26:45 +08:00
|
|
|
|
from deepdoc.parser.utils import extract_pdf_outlines
|
Refa: implement unified lazy image loading for Docx parsers (qa/manual) (#13329)
## Summary
This PR is the direct successor to the previous `docx` lazy-loading
implementation. It addresses the technical debt intentionally left out
in the last PR by fully migrating the `qa` and `manual` parsing
strategies to the new lazy-loading model.
Additionally, this PR comprehensively refactors the underlying `docx`
parsing pipeline to eliminate significant code redundancy and introduces
robust fallback mechanisms to handle completely corrupted image streams
safely.
## What's Changed
* **Centralized Abstraction (`docx_parser.py`)**: Moved the
`get_picture` extraction logic up to the `RAGFlowDocxParser` base class.
Previously, `naive`, `qa`, and `manual` parsers maintained separate,
redundant copies of this method. All downstream strategies now natively
gather raw blobs and return `LazyDocxImage` objects automatically.
* **Robust Corrupted Image Fallback (`docx_parser.py`)**: Handled edge
cases where `python-docx` encounters critically malformed magic headers.
Implemented an explicit `try-except` structure that safely intercepts
`UnrecognizedImageError` (and similar exceptions) and seamlessly falls
back to retrieving the raw binary via `getattr(related_part, "blob",
None)`, preventing parser crashes on damaged documents.
* **Legacy Code & Redundancy Purge**:
* Removed the duplicate `get_picture` methods from `naive.py`, `qa.py`,
and `manual.py`.
* Removed the standalone, immediate-decoding `concat_img` method in
`manual.py`. It has been completely replaced by the globally unified,
lazy-loading-compatible `rag.nlp.concat_img`.
* Cleaned up unused legacy imports (e.g., `PIL.Image`, docx exception
packages) across all updated strategy files.
## Scope
To keep this PR focused, I have restricted these changes strictly to the
unification of `docx` extraction logic and the lazy-load migration of
`qa` and `manual`.
## Validation & Testing
I've tested this to ensure no regressions and validated the fallback
logic:
* **Output Consistency**: Compared identical `.docx` inputs using `qa`
and `manual` strategies before and after this branch: chunk counts,
extracted text, table HTML, and attached images match perfectly.
* **Memory Footprint Drop**: Confirmed a noticeable drop in peak memory
usage when processing image-dense documents through the `qa` and
`manual` pipelines, bringing them up to parity with the `naive`
strategy's performance gains.
## Breaking Changes
* None.
2026-03-11 10:00:07 +08:00
|
|
|
|
from rag.nlp import rag_tokenizer, tokenize, tokenize_table, bullets_category, title_frequency, tokenize_chunks, docx_question_level, attach_media_context, concat_img
|
2025-11-03 08:50:05 +08:00
|
|
|
|
from common.token_utils import num_tokens_from_string
|
2025-11-05 13:00:42 +08:00
|
|
|
|
from deepdoc.parser import PdfParser, DocxParser
|
2025-12-29 12:01:18 +08:00
|
|
|
|
from deepdoc.parser.figure_parser import vision_figure_parser_pdf_wrapper, vision_figure_parser_docx_wrapper
|
2024-08-15 09:17:36 +08:00
|
|
|
|
from docx import Document
|
2025-11-06 15:20:35 +08:00
|
|
|
|
from rag.app.naive import by_plaintext, PARSERS
|
2025-12-17 19:48:24 +08:00
|
|
|
|
from common.parser_config_utils import normalize_layout_recognizer
|
2024-09-30 16:59:39 +08:00
|
|
|
|
|
2025-12-29 12:01:18 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
class Pdf(PdfParser):
|
|
|
|
|
|
def __init__(self):
|
2026-05-15 14:19:41 +08:00
|
|
|
|
self.model_species = ParserType.MANUAL.value
|
2024-08-15 09:17:36 +08:00
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
Fix: Remove hardcoded page limits causing parsing failures on large PDFs (>300 pages) (#14382)
### What problem does this PR solve?
Fixes #14196
## Problem
When using DeepDOC to parse large PDFs (over 1000 pages), the parser
silently truncated processing at 300 pages due to a hardcoded default
`page_to=299` in `RAGFlowPdfParser.__images__()`. This caused:
- **Errors** on pages beyond the limit
- **Poor image quality** as the parser attempted to compensate with
missing page data
- **Inconsistent chunk splitting** between full PDF imports and partial
imports
Additionally, the codebase scattered magic numbers (`299`, `600`,
`10000`, `100000`, `100000000`, `10000000000`, `10**9`) across 22 files
as sentinel values for "parse all pages", making future maintenance
error-prone.
## Root Cause
```python
# deepdoc/parser/pdf_parser.py (before)
def __images__(self, fnm, zoomin=3, page_from=0, page_to=299, callback=None):
# Only the first 300 pages were rendered; everything beyond was silently dropped
```
While most callers in `rag/app/*.py` correctly passed `to_page=100000`,
the base class `RAGFlowPdfParser.__call__()` and `parse_into_bboxes()`
invoked `__images__` **without** forwarding `page_from`/`page_to`,
falling back to the restrictive default of 299.
## Solution
### 1. Define constants in `common/constants.py`
```python
MAXIMUM_PAGE_NUMBER = 100000 # Used by the parsing layer
MAXIMUM_TASK_PAGE_NUMBER = MAXIMUM_PAGE_NUMBER * 1000 # Used by the task/DB layer
```
### 2. Replace all hardcoded sentinel values
| Layer | Files Changed | Old Values | New Value |
|---|---|---|---|
| **Deepdoc parsers** | `pdf_parser.py`, `mineru_parser.py`,
`docling_parser.py`, `opendataloader_parser.py`, `paddleocr_parser.py`,
`docx_parser.py` | `299`, `600`, `10**9`, `100000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Chunk parsers** | `naive.py`, `book.py`, `qa.py`, `one.py`,
`manual.py`, `paper.py`, `presentation.py`, `laws.py`, `resume.py`,
`email.py`, `table.py` | `100000`, `10000`, `10000000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Task/DB layer** | `db_models.py`, `task_service.py`,
`document_service.py`, `file_service.py` | `100000000` |
`MAXIMUM_TASK_PAGE_NUMBER` |
### 3. Fix `parse_into_bboxes()` missing parameters
Added `from_page`/`to_page` parameters to `parse_into_bboxes()` so that
the `rag/flow/parser/parser.py` DeepDOC path no longer falls back to the
restrictive default.
## Files Changed (22)
- `common/constants.py`
- `deepdoc/parser/pdf_parser.py`
- `deepdoc/parser/mineru_parser.py`
- `deepdoc/parser/docling_parser.py`
- `deepdoc/parser/opendataloader_parser.py`
- `deepdoc/parser/paddleocr_parser.py`
- `deepdoc/parser/docx_parser.py`
- `rag/app/naive.py`
- `rag/app/book.py`
- `rag/app/qa.py`
- `rag/app/one.py`
- `rag/app/manual.py`
- `rag/app/paper.py`
- `rag/app/presentation.py`
- `rag/app/laws.py`
- `rag/app/resume.py`
- `rag/app/email.py`
- `rag/app/table.py`
- `api/db/db_models.py`
- `api/db/services/task_service.py`
- `api/db/services/document_service.py`
- `api/db/services/file_service.py`
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
---------
Signed-off-by: noob <yixiao121314@outlook.com>
2026-04-27 06:57:20 +00:00
|
|
|
|
def __call__(self, filename, binary=None, from_page=0, to_page=MAXIMUM_PAGE_NUMBER, zoomin=3, callback=None):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
from timeit import default_timer as timer
|
2026-01-09 17:48:45 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
start = timer()
|
2024-11-30 18:48:06 +08:00
|
|
|
|
callback(msg="OCR started")
|
2026-01-09 17:48:45 +08:00
|
|
|
|
self.__images__(filename if not binary else binary, zoomin, from_page, to_page, callback)
|
2024-11-30 18:48:06 +08:00
|
|
|
|
callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
|
2024-11-14 17:13:48 +08:00
|
|
|
|
logging.debug("OCR: {}".format(timer() - start))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
2024-11-30 18:48:06 +08:00
|
|
|
|
start = timer()
|
2024-08-15 09:17:36 +08:00
|
|
|
|
self._layouts_rec(zoomin)
|
2024-11-30 18:48:06 +08:00
|
|
|
|
callback(0.65, "Layout analysis ({:.2f}s)".format(timer() - start))
|
2024-11-14 17:13:48 +08:00
|
|
|
|
logging.debug("layouts: {}".format(timer() - start))
|
2024-11-30 18:48:06 +08:00
|
|
|
|
|
|
|
|
|
|
start = timer()
|
2024-08-15 09:17:36 +08:00
|
|
|
|
self._table_transformer_job(zoomin)
|
2024-11-30 18:48:06 +08:00
|
|
|
|
callback(0.67, "Table analysis ({:.2f}s)".format(timer() - start))
|
|
|
|
|
|
|
|
|
|
|
|
start = timer()
|
2024-08-15 09:17:36 +08:00
|
|
|
|
self._text_merge()
|
|
|
|
|
|
tbls = self._extract_table_figure(True, zoomin, True, True)
|
|
|
|
|
|
self._concat_downward()
|
|
|
|
|
|
self._filter_forpages()
|
2024-11-30 18:48:06 +08:00
|
|
|
|
callback(0.68, "Text merged ({:.2f}s)".format(timer() - start))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
# clean mess
|
|
|
|
|
|
for b in self.boxes:
|
|
|
|
|
|
b["text"] = re.sub(r"([\t ]|\u3000){2,}", " ", b["text"].strip())
|
|
|
|
|
|
|
2026-01-09 17:48:45 +08:00
|
|
|
|
return [(b["text"], b.get("layoutno", ""), self.get_position(b, zoomin)) for i, b in enumerate(self.boxes)], tbls
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
2024-10-22 15:25:23 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
class Docx(DocxParser):
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
pass
|
2024-10-22 15:25:23 +08:00
|
|
|
|
|
Fix: Remove hardcoded page limits causing parsing failures on large PDFs (>300 pages) (#14382)
### What problem does this PR solve?
Fixes #14196
## Problem
When using DeepDOC to parse large PDFs (over 1000 pages), the parser
silently truncated processing at 300 pages due to a hardcoded default
`page_to=299` in `RAGFlowPdfParser.__images__()`. This caused:
- **Errors** on pages beyond the limit
- **Poor image quality** as the parser attempted to compensate with
missing page data
- **Inconsistent chunk splitting** between full PDF imports and partial
imports
Additionally, the codebase scattered magic numbers (`299`, `600`,
`10000`, `100000`, `100000000`, `10000000000`, `10**9`) across 22 files
as sentinel values for "parse all pages", making future maintenance
error-prone.
## Root Cause
```python
# deepdoc/parser/pdf_parser.py (before)
def __images__(self, fnm, zoomin=3, page_from=0, page_to=299, callback=None):
# Only the first 300 pages were rendered; everything beyond was silently dropped
```
While most callers in `rag/app/*.py` correctly passed `to_page=100000`,
the base class `RAGFlowPdfParser.__call__()` and `parse_into_bboxes()`
invoked `__images__` **without** forwarding `page_from`/`page_to`,
falling back to the restrictive default of 299.
## Solution
### 1. Define constants in `common/constants.py`
```python
MAXIMUM_PAGE_NUMBER = 100000 # Used by the parsing layer
MAXIMUM_TASK_PAGE_NUMBER = MAXIMUM_PAGE_NUMBER * 1000 # Used by the task/DB layer
```
### 2. Replace all hardcoded sentinel values
| Layer | Files Changed | Old Values | New Value |
|---|---|---|---|
| **Deepdoc parsers** | `pdf_parser.py`, `mineru_parser.py`,
`docling_parser.py`, `opendataloader_parser.py`, `paddleocr_parser.py`,
`docx_parser.py` | `299`, `600`, `10**9`, `100000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Chunk parsers** | `naive.py`, `book.py`, `qa.py`, `one.py`,
`manual.py`, `paper.py`, `presentation.py`, `laws.py`, `resume.py`,
`email.py`, `table.py` | `100000`, `10000`, `10000000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Task/DB layer** | `db_models.py`, `task_service.py`,
`document_service.py`, `file_service.py` | `100000000` |
`MAXIMUM_TASK_PAGE_NUMBER` |
### 3. Fix `parse_into_bboxes()` missing parameters
Added `from_page`/`to_page` parameters to `parse_into_bboxes()` so that
the `rag/flow/parser/parser.py` DeepDOC path no longer falls back to the
restrictive default.
## Files Changed (22)
- `common/constants.py`
- `deepdoc/parser/pdf_parser.py`
- `deepdoc/parser/mineru_parser.py`
- `deepdoc/parser/docling_parser.py`
- `deepdoc/parser/opendataloader_parser.py`
- `deepdoc/parser/paddleocr_parser.py`
- `deepdoc/parser/docx_parser.py`
- `rag/app/naive.py`
- `rag/app/book.py`
- `rag/app/qa.py`
- `rag/app/one.py`
- `rag/app/manual.py`
- `rag/app/paper.py`
- `rag/app/presentation.py`
- `rag/app/laws.py`
- `rag/app/resume.py`
- `rag/app/email.py`
- `rag/app/table.py`
- `api/db/db_models.py`
- `api/db/services/task_service.py`
- `api/db/services/document_service.py`
- `api/db/services/file_service.py`
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
---------
Signed-off-by: noob <yixiao121314@outlook.com>
2026-04-27 06:57:20 +00:00
|
|
|
|
def __call__(self, filename, binary=None, from_page=0, to_page=MAXIMUM_PAGE_NUMBER, callback=None):
|
2026-01-09 17:48:45 +08:00
|
|
|
|
self.doc = Document(filename) if not binary else Document(BytesIO(binary))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
pn = 0
|
|
|
|
|
|
last_answer, last_image = "", None
|
|
|
|
|
|
question_stack, level_stack = [], []
|
|
|
|
|
|
ti_list = []
|
|
|
|
|
|
for p in self.doc.paragraphs:
|
|
|
|
|
|
if pn > to_page:
|
|
|
|
|
|
break
|
2026-01-09 17:48:45 +08:00
|
|
|
|
question_level, p_text = 0, ""
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if from_page <= pn < to_page and p.text.strip():
|
|
|
|
|
|
question_level, p_text = docx_question_level(p)
|
2025-12-29 12:01:18 +08:00
|
|
|
|
if not question_level or question_level > 6: # not a question
|
2026-01-09 17:48:45 +08:00
|
|
|
|
last_answer = f"{last_answer}\n{p_text}"
|
2024-08-15 09:17:36 +08:00
|
|
|
|
current_image = self.get_picture(self.doc, p)
|
Refa: implement unified lazy image loading for Docx parsers (qa/manual) (#13329)
## Summary
This PR is the direct successor to the previous `docx` lazy-loading
implementation. It addresses the technical debt intentionally left out
in the last PR by fully migrating the `qa` and `manual` parsing
strategies to the new lazy-loading model.
Additionally, this PR comprehensively refactors the underlying `docx`
parsing pipeline to eliminate significant code redundancy and introduces
robust fallback mechanisms to handle completely corrupted image streams
safely.
## What's Changed
* **Centralized Abstraction (`docx_parser.py`)**: Moved the
`get_picture` extraction logic up to the `RAGFlowDocxParser` base class.
Previously, `naive`, `qa`, and `manual` parsers maintained separate,
redundant copies of this method. All downstream strategies now natively
gather raw blobs and return `LazyDocxImage` objects automatically.
* **Robust Corrupted Image Fallback (`docx_parser.py`)**: Handled edge
cases where `python-docx` encounters critically malformed magic headers.
Implemented an explicit `try-except` structure that safely intercepts
`UnrecognizedImageError` (and similar exceptions) and seamlessly falls
back to retrieving the raw binary via `getattr(related_part, "blob",
None)`, preventing parser crashes on damaged documents.
* **Legacy Code & Redundancy Purge**:
* Removed the duplicate `get_picture` methods from `naive.py`, `qa.py`,
and `manual.py`.
* Removed the standalone, immediate-decoding `concat_img` method in
`manual.py`. It has been completely replaced by the globally unified,
lazy-loading-compatible `rag.nlp.concat_img`.
* Cleaned up unused legacy imports (e.g., `PIL.Image`, docx exception
packages) across all updated strategy files.
## Scope
To keep this PR focused, I have restricted these changes strictly to the
unification of `docx` extraction logic and the lazy-load migration of
`qa` and `manual`.
## Validation & Testing
I've tested this to ensure no regressions and validated the fallback
logic:
* **Output Consistency**: Compared identical `.docx` inputs using `qa`
and `manual` strategies before and after this branch: chunk counts,
extracted text, table HTML, and attached images match perfectly.
* **Memory Footprint Drop**: Confirmed a noticeable drop in peak memory
usage when processing image-dense documents through the `qa` and
`manual` pipelines, bringing them up to parity with the `naive`
strategy's performance gains.
## Breaking Changes
* None.
2026-03-11 10:00:07 +08:00
|
|
|
|
last_image = concat_img(last_image, current_image)
|
2025-12-29 12:01:18 +08:00
|
|
|
|
else: # is a question
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if last_answer or last_image:
|
2026-01-09 17:48:45 +08:00
|
|
|
|
sum_question = "\n".join(question_stack)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if sum_question:
|
2026-01-09 17:48:45 +08:00
|
|
|
|
ti_list.append((f"{sum_question}\n{last_answer}", last_image))
|
|
|
|
|
|
last_answer, last_image = "", None
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
i = question_level
|
|
|
|
|
|
while question_stack and i <= level_stack[-1]:
|
|
|
|
|
|
question_stack.pop()
|
|
|
|
|
|
level_stack.pop()
|
|
|
|
|
|
question_stack.append(p_text)
|
|
|
|
|
|
level_stack.append(question_level)
|
|
|
|
|
|
for run in p.runs:
|
2026-01-09 17:48:45 +08:00
|
|
|
|
if "lastRenderedPageBreak" in run._element.xml:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
pn += 1
|
|
|
|
|
|
continue
|
2026-01-09 17:48:45 +08:00
|
|
|
|
if "w:br" in run._element.xml and 'type="page"' in run._element.xml:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
pn += 1
|
|
|
|
|
|
if last_answer:
|
2026-01-09 17:48:45 +08:00
|
|
|
|
sum_question = "\n".join(question_stack)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if sum_question:
|
2026-01-09 17:48:45 +08:00
|
|
|
|
ti_list.append((f"{sum_question}\n{last_answer}", last_image))
|
2025-11-27 10:21:44 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
tbls = []
|
|
|
|
|
|
for tb in self.doc.tables:
|
2025-12-29 12:01:18 +08:00
|
|
|
|
html = "<table>"
|
2024-08-15 09:17:36 +08:00
|
|
|
|
for r in tb.rows:
|
|
|
|
|
|
html += "<tr>"
|
|
|
|
|
|
i = 0
|
|
|
|
|
|
while i < len(r.cells):
|
|
|
|
|
|
span = 1
|
|
|
|
|
|
c = r.cells[i]
|
2025-12-29 12:01:18 +08:00
|
|
|
|
for j in range(i + 1, len(r.cells)):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if c.text == r.cells[j].text:
|
|
|
|
|
|
span += 1
|
|
|
|
|
|
i = j
|
2025-04-14 11:00:11 +08:00
|
|
|
|
else:
|
|
|
|
|
|
break
|
2024-08-15 09:17:36 +08:00
|
|
|
|
i += 1
|
|
|
|
|
|
html += f"<td>{c.text}</td>" if span == 1 else f"<td colspan='{span}'>{c.text}</td>"
|
|
|
|
|
|
html += "</tr>"
|
|
|
|
|
|
html += "</table>"
|
|
|
|
|
|
tbls.append(((None, html), ""))
|
|
|
|
|
|
return ti_list, tbls
|
|
|
|
|
|
|
2024-10-22 15:25:23 +08:00
|
|
|
|
|
Fix: Remove hardcoded page limits causing parsing failures on large PDFs (>300 pages) (#14382)
### What problem does this PR solve?
Fixes #14196
## Problem
When using DeepDOC to parse large PDFs (over 1000 pages), the parser
silently truncated processing at 300 pages due to a hardcoded default
`page_to=299` in `RAGFlowPdfParser.__images__()`. This caused:
- **Errors** on pages beyond the limit
- **Poor image quality** as the parser attempted to compensate with
missing page data
- **Inconsistent chunk splitting** between full PDF imports and partial
imports
Additionally, the codebase scattered magic numbers (`299`, `600`,
`10000`, `100000`, `100000000`, `10000000000`, `10**9`) across 22 files
as sentinel values for "parse all pages", making future maintenance
error-prone.
## Root Cause
```python
# deepdoc/parser/pdf_parser.py (before)
def __images__(self, fnm, zoomin=3, page_from=0, page_to=299, callback=None):
# Only the first 300 pages were rendered; everything beyond was silently dropped
```
While most callers in `rag/app/*.py` correctly passed `to_page=100000`,
the base class `RAGFlowPdfParser.__call__()` and `parse_into_bboxes()`
invoked `__images__` **without** forwarding `page_from`/`page_to`,
falling back to the restrictive default of 299.
## Solution
### 1. Define constants in `common/constants.py`
```python
MAXIMUM_PAGE_NUMBER = 100000 # Used by the parsing layer
MAXIMUM_TASK_PAGE_NUMBER = MAXIMUM_PAGE_NUMBER * 1000 # Used by the task/DB layer
```
### 2. Replace all hardcoded sentinel values
| Layer | Files Changed | Old Values | New Value |
|---|---|---|---|
| **Deepdoc parsers** | `pdf_parser.py`, `mineru_parser.py`,
`docling_parser.py`, `opendataloader_parser.py`, `paddleocr_parser.py`,
`docx_parser.py` | `299`, `600`, `10**9`, `100000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Chunk parsers** | `naive.py`, `book.py`, `qa.py`, `one.py`,
`manual.py`, `paper.py`, `presentation.py`, `laws.py`, `resume.py`,
`email.py`, `table.py` | `100000`, `10000`, `10000000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Task/DB layer** | `db_models.py`, `task_service.py`,
`document_service.py`, `file_service.py` | `100000000` |
`MAXIMUM_TASK_PAGE_NUMBER` |
### 3. Fix `parse_into_bboxes()` missing parameters
Added `from_page`/`to_page` parameters to `parse_into_bboxes()` so that
the `rag/flow/parser/parser.py` DeepDOC path no longer falls back to the
restrictive default.
## Files Changed (22)
- `common/constants.py`
- `deepdoc/parser/pdf_parser.py`
- `deepdoc/parser/mineru_parser.py`
- `deepdoc/parser/docling_parser.py`
- `deepdoc/parser/opendataloader_parser.py`
- `deepdoc/parser/paddleocr_parser.py`
- `deepdoc/parser/docx_parser.py`
- `rag/app/naive.py`
- `rag/app/book.py`
- `rag/app/qa.py`
- `rag/app/one.py`
- `rag/app/manual.py`
- `rag/app/paper.py`
- `rag/app/presentation.py`
- `rag/app/laws.py`
- `rag/app/resume.py`
- `rag/app/email.py`
- `rag/app/table.py`
- `api/db/db_models.py`
- `api/db/services/task_service.py`
- `api/db/services/document_service.py`
- `api/db/services/file_service.py`
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
---------
Signed-off-by: noob <yixiao121314@outlook.com>
2026-04-27 06:57:20 +00:00
|
|
|
|
def chunk(filename, binary=None, from_page=0, to_page=MAXIMUM_PAGE_NUMBER, lang="Chinese", callback=None, **kwargs):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
"""
|
2026-01-09 17:48:45 +08:00
|
|
|
|
Only pdf is supported.
|
2024-08-15 09:17:36 +08:00
|
|
|
|
"""
|
2026-01-09 17:48:45 +08:00
|
|
|
|
parser_config = kwargs.get("parser_config", {"chunk_token_num": 512, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
|
2024-08-15 09:17:36 +08:00
|
|
|
|
pdf_parser = None
|
2026-01-09 17:48:45 +08:00
|
|
|
|
doc = {"docnm_kwd": filename}
|
2024-08-15 09:17:36 +08:00
|
|
|
|
doc["title_tks"] = rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
|
|
|
|
|
|
doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
|
|
|
|
|
|
# is it English
|
|
|
|
|
|
eng = lang.lower() == "english" # pdf_parser.is_english
|
|
|
|
|
|
if re.search(r"\.pdf$", filename, re.IGNORECASE):
|
2026-01-09 17:48:45 +08:00
|
|
|
|
layout_recognizer, parser_model_name = normalize_layout_recognizer(parser_config.get("layout_recognize", "DeepDOC"))
|
2025-11-05 13:00:42 +08:00
|
|
|
|
|
|
|
|
|
|
if isinstance(layout_recognizer, bool):
|
|
|
|
|
|
layout_recognizer = "DeepDOC" if layout_recognizer else "Plain Text"
|
|
|
|
|
|
|
|
|
|
|
|
name = layout_recognizer.strip().lower()
|
2025-11-06 15:20:35 +08:00
|
|
|
|
pdf_parser = PARSERS.get(name, by_plaintext)
|
2025-11-05 13:00:42 +08:00
|
|
|
|
callback(0.1, "Start to parse.")
|
|
|
|
|
|
|
2025-12-17 19:48:24 +08:00
|
|
|
|
kwargs.pop("parse_method", None)
|
|
|
|
|
|
kwargs.pop("mineru_llm_name", None)
|
2025-11-05 13:00:42 +08:00
|
|
|
|
sections, tbls, pdf_parser = pdf_parser(
|
2025-12-29 12:01:18 +08:00
|
|
|
|
filename=filename,
|
|
|
|
|
|
binary=binary,
|
|
|
|
|
|
from_page=from_page,
|
|
|
|
|
|
to_page=to_page,
|
|
|
|
|
|
lang=lang,
|
|
|
|
|
|
callback=callback,
|
|
|
|
|
|
pdf_cls=Pdf,
|
|
|
|
|
|
layout_recognizer=layout_recognizer,
|
2025-12-17 19:48:24 +08:00
|
|
|
|
mineru_llm_name=parser_model_name,
|
2026-01-09 17:48:45 +08:00
|
|
|
|
paddleocr_llm_name=parser_model_name,
|
2025-12-29 12:01:18 +08:00
|
|
|
|
parse_method="manual",
|
2026-01-09 17:48:45 +08:00
|
|
|
|
**kwargs,
|
2025-11-05 13:00:42 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-11-18 15:22:52 +08:00
|
|
|
|
def _normalize_section(section):
|
2025-12-09 19:21:52 +08:00
|
|
|
|
# pad section to length 3: (txt, sec_id, poss)
|
|
|
|
|
|
if len(section) == 1:
|
2025-11-18 15:22:52 +08:00
|
|
|
|
section = (section[0], "", [])
|
|
|
|
|
|
elif len(section) == 2:
|
|
|
|
|
|
section = (section[0], "", section[1])
|
2025-12-09 19:21:52 +08:00
|
|
|
|
elif len(section) != 3:
|
|
|
|
|
|
raise ValueError(f"Unexpected section length: {len(section)} (value={section!r})")
|
2025-11-18 15:22:52 +08:00
|
|
|
|
|
2025-11-20 19:07:17 +08:00
|
|
|
|
txt, layoutno, poss = section
|
2025-11-18 15:22:52 +08:00
|
|
|
|
if isinstance(poss, str):
|
2026-04-28 14:21:30 +08:00
|
|
|
|
poss = (getattr(pdf_parser, "extract_positions", lambda _: [])(poss) or [[0, 0, 0, 0, 0]])
|
2025-12-05 19:25:45 +08:00
|
|
|
|
if poss:
|
2025-12-29 12:01:18 +08:00
|
|
|
|
first = poss[0] # tuple: ([pn], x1, x2, y1, y2)
|
2025-12-17 19:48:24 +08:00
|
|
|
|
pn = first[0]
|
2025-12-05 19:25:45 +08:00
|
|
|
|
if isinstance(pn, list) and pn:
|
2025-12-29 12:01:18 +08:00
|
|
|
|
pn = pn[0] # [pn] -> pn
|
2025-12-09 19:21:52 +08:00
|
|
|
|
poss[0] = (pn, *first[1:])
|
2025-11-18 15:22:52 +08:00
|
|
|
|
|
2025-11-20 19:07:17 +08:00
|
|
|
|
return (txt, layoutno, poss)
|
2025-11-27 10:21:44 +08:00
|
|
|
|
|
2025-11-18 15:22:52 +08:00
|
|
|
|
sections = [_normalize_section(sec) for sec in sections]
|
|
|
|
|
|
|
2025-11-05 13:00:42 +08:00
|
|
|
|
if not sections and not tbls:
|
|
|
|
|
|
return []
|
|
|
|
|
|
|
2026-01-09 17:48:45 +08:00
|
|
|
|
if name in ["tcadp", "docling", "mineru", "paddleocr"]:
|
2025-11-05 13:00:42 +08:00
|
|
|
|
parser_config["chunk_token_num"] = 0
|
2025-11-27 10:21:44 +08:00
|
|
|
|
|
2025-11-05 13:00:42 +08:00
|
|
|
|
callback(0.8, "Finish parsing.")
|
2026-04-03 19:26:45 +08:00
|
|
|
|
outlines = extract_pdf_outlines(binary if binary is not None else filename)
|
2025-11-05 13:00:42 +08:00
|
|
|
|
|
2026-04-03 19:26:45 +08:00
|
|
|
|
if len(sections) > 0 and len(outlines) / len(sections) > 0.03:
|
|
|
|
|
|
max_lvl = max([lvl for _, lvl, _ in outlines])
|
2024-08-15 09:17:36 +08:00
|
|
|
|
most_level = max(0, max_lvl - 1)
|
|
|
|
|
|
levels = []
|
|
|
|
|
|
for txt, _, _ in sections:
|
2026-04-03 19:26:45 +08:00
|
|
|
|
for t, lvl, _ in outlines:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
tks = set([t[i] + t[i + 1] for i in range(len(t) - 1)])
|
2026-01-09 17:48:45 +08:00
|
|
|
|
tks_ = set([txt[i] + txt[i + 1] for i in range(min(len(t), len(txt) - 1))])
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if len(set(tks & tks_)) / max([len(tks), len(tks_), 1]) > 0.8:
|
|
|
|
|
|
levels.append(lvl)
|
|
|
|
|
|
break
|
|
|
|
|
|
else:
|
|
|
|
|
|
levels.append(max_lvl + 1)
|
|
|
|
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
bull = bullets_category([txt for txt, _, _ in sections])
|
2026-01-09 17:48:45 +08:00
|
|
|
|
most_level, levels = title_frequency(bull, [(txt, lvl) for txt, lvl, _ in sections])
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
assert len(sections) == len(levels)
|
|
|
|
|
|
sec_ids = []
|
|
|
|
|
|
sid = 0
|
|
|
|
|
|
for i, lvl in enumerate(levels):
|
|
|
|
|
|
if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
|
|
|
|
|
|
sid += 1
|
|
|
|
|
|
sec_ids.append(sid)
|
|
|
|
|
|
|
2026-01-09 17:48:45 +08:00
|
|
|
|
sections = [(txt, sec_ids[i], poss) for i, (txt, _, poss) in enumerate(sections)]
|
2024-08-15 09:17:36 +08:00
|
|
|
|
for (img, rows), poss in tbls:
|
2024-12-08 14:21:12 +08:00
|
|
|
|
if not rows:
|
|
|
|
|
|
continue
|
2026-01-09 17:48:45 +08:00
|
|
|
|
sections.append((rows if isinstance(rows, str) else rows[0], -1, [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
def tag(pn, left, right, top, bottom):
|
|
|
|
|
|
if pn + left + right + top + bottom == 0:
|
|
|
|
|
|
return ""
|
2026-01-09 17:48:45 +08:00
|
|
|
|
return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##".format(pn, left, right, top, bottom)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
chunks = []
|
|
|
|
|
|
last_sid = -2
|
|
|
|
|
|
tk_cnt = 0
|
2026-01-09 17:48:45 +08:00
|
|
|
|
for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
poss = "\t".join([tag(*pos) for pos in poss])
|
|
|
|
|
|
if tk_cnt < 32 or (tk_cnt < 1024 and (sec_id == last_sid or sec_id == -1)):
|
|
|
|
|
|
if chunks:
|
|
|
|
|
|
chunks[-1] += "\n" + txt + poss
|
|
|
|
|
|
tk_cnt += num_tokens_from_string(txt)
|
|
|
|
|
|
continue
|
|
|
|
|
|
chunks.append(txt + poss)
|
|
|
|
|
|
tk_cnt = num_tokens_from_string(txt)
|
|
|
|
|
|
if sec_id > -1:
|
|
|
|
|
|
last_sid = sec_id
|
2026-01-05 09:55:43 +08:00
|
|
|
|
tbls = vision_figure_parser_pdf_wrapper(
|
|
|
|
|
|
tbls=tbls,
|
|
|
|
|
|
sections=sections,
|
|
|
|
|
|
callback=callback,
|
|
|
|
|
|
**kwargs,
|
|
|
|
|
|
)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
res = tokenize_table(tbls, doc, eng)
|
|
|
|
|
|
res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
|
2025-11-27 10:21:44 +08:00
|
|
|
|
table_ctx = max(0, int(parser_config.get("table_context_size", 0) or 0))
|
|
|
|
|
|
image_ctx = max(0, int(parser_config.get("image_context_size", 0) or 0))
|
|
|
|
|
|
if table_ctx or image_ctx:
|
|
|
|
|
|
attach_media_context(res, table_ctx, image_ctx)
|
feat: persist PDF bookmark outline as document metadata (#13287)
## Summary
PDF files often contain a bookmark/outline tree (table of contents built
into the file by the authoring tool). RAGFlow's `pdf_parser.outlines`
already extracts these `(title, depth)` tuples via pypdf, but they are
used ephemerally during chunking (`manual` parser uses them for
hierarchy detection) and then discarded.
This PR persists the outline as `doc.meta_fields["outline"]` — a JSON
array of `{"title": str, "depth": int}` objects — so downstream features
can use the structural information.
### Why this matters
- **Complementary to `toc_extraction`** — the existing `toc_extraction`
feature uses LLM calls to generate a TOC and only works for the `naive`
parser. The raw PDF outline is free (already extracted by pypdf), works
for all parsers, and captures the author's original document structure.
- **Document navigation** — frontends can render a clickable TOC from
the outline
- **Entity extraction** — the outline provides a structural map for
identifying document sections and key topics
- **Search result context** — knowing which section a chunk belongs to
helps users evaluate relevance
### Changes
| File | Change | LOC |
|------|--------|-----|
| `rag/app/naive.py` | Attach `pdf_parser.outlines` as `__outline__` on
first chunk dict | ~7 |
| `rag/app/manual.py` | Same for the manual parser | ~5 |
| `rag/svr/task_executor.py` | Extract `__outline__`, persist via
`DocMetadataService.update_document_metadata()` | ~12 |
### Design decisions
- **Transient key pattern**: The outline is passed from parser →
task_executor via `__outline__` on the first chunk dict, then removed
before indexing. This follows the same pattern as `metadata_obj` for
LLM-generated metadata.
- **No schema changes**: Uses the existing `meta_fields` JSON column on
the document table.
- **Graceful degradation**: If a PDF has no outline (common for scanned
docs), nothing is stored. If persistence fails, it logs a warning and
continues — parsing is not interrupted.
### Backward compatibility
- **Fully backward compatible** — no existing fields, behavior, or
schemas changed
- PDFs without outlines are unaffected
- Existing `meta_fields` data is preserved (merged, not overwritten)
## Test plan
- [ ] Parse a PDF with bookmarks (e.g. any multi-chapter document),
verify `meta_fields["outline"]` is populated
- [ ] Parse a PDF without bookmarks, verify no errors and no outline key
in meta_fields
- [ ] Verify existing `meta_fields` data is preserved (not overwritten)
when outline is added
- [ ] Verify `manual` parser also persists outlines
- [ ] Verify outline JSON structure: `[{"title": "Chapter 1", "depth":
0}, ...]`
Related: #9921 (Deterministic Document Access Layer)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: yuch85 <yuch85.1@gmail.com>
Co-authored-by: Wang Qi <wangq8@outlook.com>
2026-04-27 11:57:06 +08:00
|
|
|
|
if res and pdf_parser and getattr(pdf_parser, "outlines", None):
|
|
|
|
|
|
res[0]["__outline__"] = [
|
|
|
|
|
|
{"title": title, "depth": depth}
|
2026-04-30 11:55:02 +08:00
|
|
|
|
for title, depth, *_ in pdf_parser.outlines
|
feat: persist PDF bookmark outline as document metadata (#13287)
## Summary
PDF files often contain a bookmark/outline tree (table of contents built
into the file by the authoring tool). RAGFlow's `pdf_parser.outlines`
already extracts these `(title, depth)` tuples via pypdf, but they are
used ephemerally during chunking (`manual` parser uses them for
hierarchy detection) and then discarded.
This PR persists the outline as `doc.meta_fields["outline"]` — a JSON
array of `{"title": str, "depth": int}` objects — so downstream features
can use the structural information.
### Why this matters
- **Complementary to `toc_extraction`** — the existing `toc_extraction`
feature uses LLM calls to generate a TOC and only works for the `naive`
parser. The raw PDF outline is free (already extracted by pypdf), works
for all parsers, and captures the author's original document structure.
- **Document navigation** — frontends can render a clickable TOC from
the outline
- **Entity extraction** — the outline provides a structural map for
identifying document sections and key topics
- **Search result context** — knowing which section a chunk belongs to
helps users evaluate relevance
### Changes
| File | Change | LOC |
|------|--------|-----|
| `rag/app/naive.py` | Attach `pdf_parser.outlines` as `__outline__` on
first chunk dict | ~7 |
| `rag/app/manual.py` | Same for the manual parser | ~5 |
| `rag/svr/task_executor.py` | Extract `__outline__`, persist via
`DocMetadataService.update_document_metadata()` | ~12 |
### Design decisions
- **Transient key pattern**: The outline is passed from parser →
task_executor via `__outline__` on the first chunk dict, then removed
before indexing. This follows the same pattern as `metadata_obj` for
LLM-generated metadata.
- **No schema changes**: Uses the existing `meta_fields` JSON column on
the document table.
- **Graceful degradation**: If a PDF has no outline (common for scanned
docs), nothing is stored. If persistence fails, it logs a warning and
continues — parsing is not interrupted.
### Backward compatibility
- **Fully backward compatible** — no existing fields, behavior, or
schemas changed
- PDFs without outlines are unaffected
- Existing `meta_fields` data is preserved (merged, not overwritten)
## Test plan
- [ ] Parse a PDF with bookmarks (e.g. any multi-chapter document),
verify `meta_fields["outline"]` is populated
- [ ] Parse a PDF without bookmarks, verify no errors and no outline key
in meta_fields
- [ ] Verify existing `meta_fields` data is preserved (not overwritten)
when outline is added
- [ ] Verify `manual` parser also persists outlines
- [ ] Verify outline JSON structure: `[{"title": "Chapter 1", "depth":
0}, ...]`
Related: #9921 (Deterministic Document Access Layer)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: yuch85 <yuch85.1@gmail.com>
Co-authored-by: Wang Qi <wangq8@outlook.com>
2026-04-27 11:57:06 +08:00
|
|
|
|
]
|
2024-08-15 09:17:36 +08:00
|
|
|
|
return res
|
2024-10-22 15:25:23 +08:00
|
|
|
|
|
2025-01-02 13:44:44 +08:00
|
|
|
|
elif re.search(r"\.docx?$", filename, re.IGNORECASE):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
docx_parser = Docx()
|
Fix: Remove hardcoded page limits causing parsing failures on large PDFs (>300 pages) (#14382)
### What problem does this PR solve?
Fixes #14196
## Problem
When using DeepDOC to parse large PDFs (over 1000 pages), the parser
silently truncated processing at 300 pages due to a hardcoded default
`page_to=299` in `RAGFlowPdfParser.__images__()`. This caused:
- **Errors** on pages beyond the limit
- **Poor image quality** as the parser attempted to compensate with
missing page data
- **Inconsistent chunk splitting** between full PDF imports and partial
imports
Additionally, the codebase scattered magic numbers (`299`, `600`,
`10000`, `100000`, `100000000`, `10000000000`, `10**9`) across 22 files
as sentinel values for "parse all pages", making future maintenance
error-prone.
## Root Cause
```python
# deepdoc/parser/pdf_parser.py (before)
def __images__(self, fnm, zoomin=3, page_from=0, page_to=299, callback=None):
# Only the first 300 pages were rendered; everything beyond was silently dropped
```
While most callers in `rag/app/*.py` correctly passed `to_page=100000`,
the base class `RAGFlowPdfParser.__call__()` and `parse_into_bboxes()`
invoked `__images__` **without** forwarding `page_from`/`page_to`,
falling back to the restrictive default of 299.
## Solution
### 1. Define constants in `common/constants.py`
```python
MAXIMUM_PAGE_NUMBER = 100000 # Used by the parsing layer
MAXIMUM_TASK_PAGE_NUMBER = MAXIMUM_PAGE_NUMBER * 1000 # Used by the task/DB layer
```
### 2. Replace all hardcoded sentinel values
| Layer | Files Changed | Old Values | New Value |
|---|---|---|---|
| **Deepdoc parsers** | `pdf_parser.py`, `mineru_parser.py`,
`docling_parser.py`, `opendataloader_parser.py`, `paddleocr_parser.py`,
`docx_parser.py` | `299`, `600`, `10**9`, `100000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Chunk parsers** | `naive.py`, `book.py`, `qa.py`, `one.py`,
`manual.py`, `paper.py`, `presentation.py`, `laws.py`, `resume.py`,
`email.py`, `table.py` | `100000`, `10000`, `10000000000` |
`MAXIMUM_PAGE_NUMBER` |
| **Task/DB layer** | `db_models.py`, `task_service.py`,
`document_service.py`, `file_service.py` | `100000000` |
`MAXIMUM_TASK_PAGE_NUMBER` |
### 3. Fix `parse_into_bboxes()` missing parameters
Added `from_page`/`to_page` parameters to `parse_into_bboxes()` so that
the `rag/flow/parser/parser.py` DeepDOC path no longer falls back to the
restrictive default.
## Files Changed (22)
- `common/constants.py`
- `deepdoc/parser/pdf_parser.py`
- `deepdoc/parser/mineru_parser.py`
- `deepdoc/parser/docling_parser.py`
- `deepdoc/parser/opendataloader_parser.py`
- `deepdoc/parser/paddleocr_parser.py`
- `deepdoc/parser/docx_parser.py`
- `rag/app/naive.py`
- `rag/app/book.py`
- `rag/app/qa.py`
- `rag/app/one.py`
- `rag/app/manual.py`
- `rag/app/paper.py`
- `rag/app/presentation.py`
- `rag/app/laws.py`
- `rag/app/resume.py`
- `rag/app/email.py`
- `rag/app/table.py`
- `api/db/db_models.py`
- `api/db/services/task_service.py`
- `api/db/services/document_service.py`
- `api/db/services/file_service.py`
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Refactoring
---------
Signed-off-by: noob <yixiao121314@outlook.com>
2026-04-27 06:57:20 +00:00
|
|
|
|
ti_list, tbls = docx_parser(filename, binary, from_page=0, to_page=MAXIMUM_PAGE_NUMBER, callback=callback)
|
2025-12-29 12:01:18 +08:00
|
|
|
|
tbls = vision_figure_parser_docx_wrapper(sections=ti_list, tbls=tbls, callback=callback, **kwargs)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
res = tokenize_table(tbls, doc, eng)
|
|
|
|
|
|
for text, image in ti_list:
|
|
|
|
|
|
d = copy.deepcopy(doc)
|
2025-05-13 14:30:36 +08:00
|
|
|
|
if image:
|
2026-01-09 17:48:45 +08:00
|
|
|
|
d["image"] = image
|
2025-05-13 14:30:36 +08:00
|
|
|
|
d["doc_type_kwd"] = "image"
|
2024-08-15 09:17:36 +08:00
|
|
|
|
tokenize(d, text, eng)
|
|
|
|
|
|
res.append(d)
|
2025-11-27 10:21:44 +08:00
|
|
|
|
table_ctx = max(0, int(parser_config.get("table_context_size", 0) or 0))
|
|
|
|
|
|
image_ctx = max(0, int(parser_config.get("image_context_size", 0) or 0))
|
|
|
|
|
|
if table_ctx or image_ctx:
|
|
|
|
|
|
attach_media_context(res, table_ctx, image_ctx)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
return res
|
|
|
|
|
|
else:
|
|
|
|
|
|
raise NotImplementedError("file type not supported yet(pdf and docx supported)")
|
2025-11-27 10:21:44 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
import sys
|
|
|
|
|
|
|
|
|
|
|
|
def dummy(prog=None, msg=""):
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
2025-01-02 13:44:44 +08:00
|
|
|
|
chunk(sys.argv[1], callback=dummy)
|