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.
|
|
|
|
|
|
#
|
2025-01-21 20:52:28 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
import copy
|
2025-12-10 16:44:06 +08:00
|
|
|
|
import csv
|
|
|
|
|
|
import io
|
2025-10-28 09:40:37 +08:00
|
|
|
|
import logging
|
2024-08-15 09:17:36 +08:00
|
|
|
|
import re
|
|
|
|
|
|
from io import BytesIO
|
|
|
|
|
|
from xpinyin import Pinyin
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
|
import pandas as pd
|
2025-06-10 10:16:38 +08:00
|
|
|
|
from collections import Counter
|
|
|
|
|
|
|
2025-03-05 11:55:27 +08:00
|
|
|
|
# from openpyxl import load_workbook, Workbook
|
2024-08-15 09:17:36 +08:00
|
|
|
|
from dateutil.parser import parse as datetime_parse
|
|
|
|
|
|
|
|
|
|
|
|
from api.db.services.knowledgebase_service import KnowledgebaseService
|
2025-12-22 10:17:44 +08:00
|
|
|
|
from deepdoc.parser.figure_parser import vision_figure_parser_figure_xlsx_wrapper
|
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 MAXIMUM_TASK_PAGE_NUMBER
|
2024-09-29 10:29:56 +08:00
|
|
|
|
from deepdoc.parser.utils import get_text
|
2025-12-22 10:17:44 +08:00
|
|
|
|
from rag.nlp import rag_tokenizer, tokenize, tokenize_table
|
2024-08-15 09:17:36 +08:00
|
|
|
|
from deepdoc.parser import ExcelParser
|
2026-01-19 19:35:14 +08:00
|
|
|
|
from common import settings
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Excel(ExcelParser):
|
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, fnm, binary=None, from_page=0, to_page=MAXIMUM_TASK_PAGE_NUMBER, callback=None, **kwargs):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if not binary:
|
2025-03-05 11:55:27 +08:00
|
|
|
|
wb = Excel._load_excel_to_workbook(fnm)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
else:
|
2025-03-05 11:55:27 +08:00
|
|
|
|
wb = Excel._load_excel_to_workbook(BytesIO(binary))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
total = 0
|
2025-12-30 15:04:09 +08:00
|
|
|
|
for sheet_name in wb.sheetnames:
|
2026-02-06 14:43:52 +08:00
|
|
|
|
total += Excel._get_actual_row_count(wb[sheet_name])
|
2024-08-15 09:17:36 +08:00
|
|
|
|
res, fails, done = [], [], 0
|
|
|
|
|
|
rn = 0
|
2025-12-22 10:17:44 +08:00
|
|
|
|
flow_images = []
|
|
|
|
|
|
pending_cell_images = []
|
|
|
|
|
|
tables = []
|
2025-12-30 15:04:09 +08:00
|
|
|
|
for sheet_name in wb.sheetnames:
|
|
|
|
|
|
ws = wb[sheet_name]
|
|
|
|
|
|
images = Excel._extract_images_from_worksheet(ws, sheetname=sheet_name)
|
2025-12-22 10:17:44 +08:00
|
|
|
|
if images:
|
2025-12-29 12:01:18 +08:00
|
|
|
|
image_descriptions = vision_figure_parser_figure_xlsx_wrapper(images=images, callback=callback,
|
|
|
|
|
|
**kwargs)
|
2025-12-22 10:17:44 +08:00
|
|
|
|
if image_descriptions and len(image_descriptions) == len(images):
|
|
|
|
|
|
for i, bf in enumerate(image_descriptions):
|
|
|
|
|
|
images[i]["image_description"] = "\n".join(bf[0][1])
|
|
|
|
|
|
for img in images:
|
2025-12-30 15:04:09 +08:00
|
|
|
|
if img["span_type"] == "single_cell" and img.get("image_description"):
|
2025-12-22 10:17:44 +08:00
|
|
|
|
pending_cell_images.append(img)
|
|
|
|
|
|
else:
|
|
|
|
|
|
flow_images.append(img)
|
|
|
|
|
|
|
2025-10-28 09:40:37 +08:00
|
|
|
|
try:
|
2026-02-06 14:43:52 +08:00
|
|
|
|
rows = Excel._get_rows_limited(ws)
|
2025-10-28 09:40:37 +08:00
|
|
|
|
except Exception as e:
|
2025-12-30 15:04:09 +08:00
|
|
|
|
logging.warning(f"Skip sheet '{sheet_name}' due to rows access error: {e}")
|
2025-10-28 09:40:37 +08:00
|
|
|
|
continue
|
2024-12-08 14:21:12 +08:00
|
|
|
|
if not rows:
|
|
|
|
|
|
continue
|
2025-08-11 17:17:56 +08:00
|
|
|
|
headers, header_rows = self._parse_headers(ws, rows)
|
2024-12-08 14:21:12 +08:00
|
|
|
|
if not headers:
|
|
|
|
|
|
continue
|
2024-08-15 09:17:36 +08:00
|
|
|
|
data = []
|
2025-08-11 17:17:56 +08:00
|
|
|
|
for i, r in enumerate(rows[header_rows:]):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
rn += 1
|
|
|
|
|
|
if rn - 1 < from_page:
|
|
|
|
|
|
continue
|
|
|
|
|
|
if rn - 1 >= to_page:
|
|
|
|
|
|
break
|
2025-08-11 17:17:56 +08:00
|
|
|
|
row_data = self._extract_row_data(ws, r, header_rows + i, len(headers))
|
|
|
|
|
|
if row_data is None:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
fails.append(str(i))
|
|
|
|
|
|
continue
|
2025-08-11 17:17:56 +08:00
|
|
|
|
if self._is_empty_row(row_data):
|
|
|
|
|
|
continue
|
|
|
|
|
|
data.append(row_data)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
done += 1
|
2025-08-11 17:17:56 +08:00
|
|
|
|
if len(data) == 0:
|
2024-12-19 17:30:26 +08:00
|
|
|
|
continue
|
2025-08-11 17:17:56 +08:00
|
|
|
|
df = pd.DataFrame(data, columns=headers)
|
2025-12-22 10:17:44 +08:00
|
|
|
|
for img in pending_cell_images:
|
|
|
|
|
|
excel_row = img["row_from"] - 1
|
|
|
|
|
|
excel_col = img["col_from"] - 1
|
|
|
|
|
|
|
|
|
|
|
|
df_row_idx = excel_row - header_rows
|
|
|
|
|
|
if df_row_idx < 0 or df_row_idx >= len(df):
|
|
|
|
|
|
flow_images.append(img)
|
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
|
|
if excel_col < 0 or excel_col >= len(df.columns):
|
|
|
|
|
|
flow_images.append(img)
|
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
|
|
col_name = df.columns[excel_col]
|
|
|
|
|
|
|
|
|
|
|
|
if not df.iloc[df_row_idx][col_name]:
|
|
|
|
|
|
df.iat[df_row_idx, excel_col] = img["image_description"]
|
2025-08-11 17:17:56 +08:00
|
|
|
|
res.append(df)
|
2025-12-22 10:17:44 +08:00
|
|
|
|
for img in flow_images:
|
|
|
|
|
|
tables.append(
|
|
|
|
|
|
(
|
|
|
|
|
|
(
|
2026-03-23 21:24:40 +08:00
|
|
|
|
img["image"], # Image.Image or LazyImage
|
2025-12-29 12:01:18 +08:00
|
|
|
|
[img["image_description"]] # description list (must be list)
|
2025-12-22 10:17:44 +08:00
|
|
|
|
),
|
|
|
|
|
|
[
|
2025-12-29 12:01:18 +08:00
|
|
|
|
(0, 0, 0, 0, 0) # dummy position
|
2025-12-22 10:17:44 +08:00
|
|
|
|
]
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
2025-12-29 12:01:18 +08:00
|
|
|
|
callback(0.3, ("Extract records: {}~{}".format(from_page + 1, min(to_page, from_page + rn)) + (
|
|
|
|
|
|
f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
|
|
|
|
|
|
return res, tables
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
2025-08-11 17:17:56 +08:00
|
|
|
|
def _parse_headers(self, ws, rows):
|
|
|
|
|
|
if len(rows) == 0:
|
|
|
|
|
|
return [], 0
|
|
|
|
|
|
has_complex_structure = self._has_complex_header_structure(ws, rows)
|
|
|
|
|
|
if has_complex_structure:
|
|
|
|
|
|
return self._parse_multi_level_headers(ws, rows)
|
|
|
|
|
|
else:
|
|
|
|
|
|
return self._parse_simple_headers(rows)
|
|
|
|
|
|
|
|
|
|
|
|
def _has_complex_header_structure(self, ws, rows):
|
|
|
|
|
|
if len(rows) < 1:
|
|
|
|
|
|
return False
|
|
|
|
|
|
merged_ranges = list(ws.merged_cells.ranges)
|
|
|
|
|
|
# 检查前两行是否涉及合并单元格
|
|
|
|
|
|
for rng in merged_ranges:
|
|
|
|
|
|
if rng.min_row <= 2: # 只要合并区域涉及第1或第2行
|
|
|
|
|
|
return True
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def _row_looks_like_header(self, row):
|
|
|
|
|
|
header_like_cells = 0
|
|
|
|
|
|
data_like_cells = 0
|
|
|
|
|
|
non_empty_cells = 0
|
|
|
|
|
|
for cell in row:
|
|
|
|
|
|
if cell.value is not None:
|
|
|
|
|
|
non_empty_cells += 1
|
|
|
|
|
|
val = str(cell.value).strip()
|
|
|
|
|
|
if self._looks_like_header(val):
|
|
|
|
|
|
header_like_cells += 1
|
|
|
|
|
|
elif self._looks_like_data(val):
|
|
|
|
|
|
data_like_cells += 1
|
|
|
|
|
|
if non_empty_cells == 0:
|
|
|
|
|
|
return False
|
|
|
|
|
|
return header_like_cells >= data_like_cells
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_simple_headers(self, rows):
|
|
|
|
|
|
if not rows:
|
|
|
|
|
|
return [], 0
|
|
|
|
|
|
header_row = rows[0]
|
|
|
|
|
|
headers = []
|
|
|
|
|
|
for cell in header_row:
|
|
|
|
|
|
if cell.value is not None:
|
|
|
|
|
|
header_value = str(cell.value).strip()
|
|
|
|
|
|
if header_value:
|
|
|
|
|
|
headers.append(header_value)
|
|
|
|
|
|
else:
|
|
|
|
|
|
pass
|
|
|
|
|
|
final_headers = []
|
|
|
|
|
|
for i, cell in enumerate(header_row):
|
|
|
|
|
|
if cell.value is not None:
|
|
|
|
|
|
header_value = str(cell.value).strip()
|
|
|
|
|
|
if header_value:
|
|
|
|
|
|
final_headers.append(header_value)
|
|
|
|
|
|
else:
|
|
|
|
|
|
final_headers.append(f"Column_{i + 1}")
|
|
|
|
|
|
else:
|
|
|
|
|
|
final_headers.append(f"Column_{i + 1}")
|
|
|
|
|
|
return final_headers, 1
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_multi_level_headers(self, ws, rows):
|
|
|
|
|
|
if len(rows) < 2:
|
|
|
|
|
|
return [], 0
|
|
|
|
|
|
header_rows = self._detect_header_rows(rows)
|
|
|
|
|
|
if header_rows == 1:
|
|
|
|
|
|
return self._parse_simple_headers(rows)
|
|
|
|
|
|
else:
|
|
|
|
|
|
return self._build_hierarchical_headers(ws, rows, header_rows), header_rows
|
|
|
|
|
|
|
|
|
|
|
|
def _detect_header_rows(self, rows):
|
|
|
|
|
|
if len(rows) < 2:
|
|
|
|
|
|
return 1
|
|
|
|
|
|
header_rows = 1
|
|
|
|
|
|
max_check_rows = min(5, len(rows))
|
|
|
|
|
|
for i in range(1, max_check_rows):
|
|
|
|
|
|
row = rows[i]
|
|
|
|
|
|
if self._row_looks_like_header(row):
|
|
|
|
|
|
header_rows = i + 1
|
|
|
|
|
|
else:
|
|
|
|
|
|
break
|
|
|
|
|
|
return header_rows
|
|
|
|
|
|
|
|
|
|
|
|
def _looks_like_header(self, value):
|
|
|
|
|
|
if len(value) < 1:
|
|
|
|
|
|
return False
|
|
|
|
|
|
if any(ord(c) > 127 for c in value):
|
|
|
|
|
|
return True
|
|
|
|
|
|
if len([c for c in value if c.isalpha()]) >= 2:
|
|
|
|
|
|
return True
|
|
|
|
|
|
if any(c in value for c in ["(", ")", ":", ":", "(", ")", "_", "-"]):
|
|
|
|
|
|
return True
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def _looks_like_data(self, value):
|
|
|
|
|
|
if len(value) == 1 and value.upper() in ["Y", "N", "M", "X", "/", "-"]:
|
|
|
|
|
|
return True
|
|
|
|
|
|
if value.replace(".", "").replace("-", "").replace(",", "").isdigit():
|
|
|
|
|
|
return True
|
|
|
|
|
|
if value.startswith("0x") and len(value) <= 10:
|
|
|
|
|
|
return True
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def _build_hierarchical_headers(self, ws, rows, header_rows):
|
|
|
|
|
|
headers = []
|
|
|
|
|
|
max_col = max(len(row) for row in rows[:header_rows]) if header_rows > 0 else 0
|
|
|
|
|
|
merged_ranges = list(ws.merged_cells.ranges)
|
|
|
|
|
|
for col_idx in range(max_col):
|
|
|
|
|
|
header_parts = []
|
|
|
|
|
|
for row_idx in range(header_rows):
|
|
|
|
|
|
if col_idx < len(rows[row_idx]):
|
|
|
|
|
|
cell_value = rows[row_idx][col_idx].value
|
|
|
|
|
|
merged_value = self._get_merged_cell_value(ws, row_idx + 1, col_idx + 1, merged_ranges)
|
|
|
|
|
|
if merged_value is not None:
|
|
|
|
|
|
cell_value = merged_value
|
|
|
|
|
|
if cell_value is not None:
|
|
|
|
|
|
cell_value = str(cell_value).strip()
|
|
|
|
|
|
if cell_value and cell_value not in header_parts and self._is_valid_header_part(cell_value):
|
|
|
|
|
|
header_parts.append(cell_value)
|
|
|
|
|
|
if header_parts:
|
|
|
|
|
|
header = "-".join(header_parts)
|
|
|
|
|
|
headers.append(header)
|
|
|
|
|
|
else:
|
|
|
|
|
|
headers.append(f"Column_{col_idx + 1}")
|
|
|
|
|
|
final_headers = [h for h in headers if h and h != "-"]
|
|
|
|
|
|
return final_headers
|
|
|
|
|
|
|
|
|
|
|
|
def _is_valid_header_part(self, value):
|
|
|
|
|
|
if len(value) == 1 and value.upper() in ["Y", "N", "M", "X"]:
|
|
|
|
|
|
return False
|
|
|
|
|
|
if value.replace(".", "").replace("-", "").replace(",", "").isdigit():
|
|
|
|
|
|
return False
|
|
|
|
|
|
if value in ["/", "-", "+", "*", "="]:
|
|
|
|
|
|
return False
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
def _get_merged_cell_value(self, ws, row, col, merged_ranges):
|
|
|
|
|
|
for merged_range in merged_ranges:
|
|
|
|
|
|
if merged_range.min_row <= row <= merged_range.max_row and merged_range.min_col <= col <= merged_range.max_col:
|
|
|
|
|
|
return ws.cell(merged_range.min_row, merged_range.min_col).value
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def _extract_row_data(self, ws, row, absolute_row_idx, expected_cols):
|
|
|
|
|
|
row_data = []
|
|
|
|
|
|
merged_ranges = list(ws.merged_cells.ranges)
|
|
|
|
|
|
actual_row_num = absolute_row_idx + 1
|
|
|
|
|
|
for col_idx in range(expected_cols):
|
|
|
|
|
|
cell_value = None
|
|
|
|
|
|
actual_col_num = col_idx + 1
|
|
|
|
|
|
try:
|
|
|
|
|
|
cell_value = ws.cell(row=actual_row_num, column=actual_col_num).value
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
if col_idx < len(row):
|
|
|
|
|
|
cell_value = row[col_idx].value
|
|
|
|
|
|
if cell_value is None:
|
|
|
|
|
|
merged_value = self._get_merged_cell_value(ws, actual_row_num, actual_col_num, merged_ranges)
|
|
|
|
|
|
if merged_value is not None:
|
|
|
|
|
|
cell_value = merged_value
|
|
|
|
|
|
else:
|
|
|
|
|
|
cell_value = self._get_inherited_value(ws, actual_row_num, actual_col_num, merged_ranges)
|
|
|
|
|
|
row_data.append(cell_value)
|
|
|
|
|
|
return row_data
|
|
|
|
|
|
|
|
|
|
|
|
def _get_inherited_value(self, ws, row, col, merged_ranges):
|
|
|
|
|
|
for merged_range in merged_ranges:
|
|
|
|
|
|
if merged_range.min_row <= row <= merged_range.max_row and merged_range.min_col <= col <= merged_range.max_col:
|
|
|
|
|
|
return ws.cell(merged_range.min_row, merged_range.min_col).value
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
def _is_empty_row(self, row_data):
|
|
|
|
|
|
for val in row_data:
|
|
|
|
|
|
if val is not None and str(val).strip() != "":
|
|
|
|
|
|
return False
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
def trans_datatime(s):
|
|
|
|
|
|
try:
|
|
|
|
|
|
return datetime_parse(s.strip()).strftime("%Y-%m-%d %H:%M:%S")
|
2026-02-09 17:56:59 +08:00
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def trans_bool(s):
|
2025-06-10 10:16:38 +08:00
|
|
|
|
if re.match(r"(true|yes|是|\*|✓|✔|☑|✅|√)$", str(s).strip(), flags=re.IGNORECASE):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
return "yes"
|
|
|
|
|
|
if re.match(r"(false|no|否|⍻|×)$", str(s).strip(), flags=re.IGNORECASE):
|
|
|
|
|
|
return "no"
|
2025-12-30 15:04:09 +08:00
|
|
|
|
return None
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def column_data_type(arr):
|
|
|
|
|
|
arr = list(arr)
|
|
|
|
|
|
counts = {"int": 0, "float": 0, "text": 0, "datetime": 0, "bool": 0}
|
2025-12-29 12:01:18 +08:00
|
|
|
|
trans = {t: f for f, t in
|
|
|
|
|
|
[(int, "int"), (float, "float"), (trans_datatime, "datetime"), (trans_bool, "bool"), (str, "text")]}
|
2025-06-24 18:18:30 +08:00
|
|
|
|
float_flag = False
|
2024-08-15 09:17:36 +08:00
|
|
|
|
for a in arr:
|
|
|
|
|
|
if a is None:
|
|
|
|
|
|
continue
|
2025-07-14 17:51:26 +08:00
|
|
|
|
if re.match(r"[+-]?[0-9]+$", str(a).replace("%%", "")) and not str(a).replace("%%", "").startswith("0"):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
counts["int"] += 1
|
2025-12-29 12:01:18 +08:00
|
|
|
|
if int(str(a)) > 2 ** 63 - 1:
|
2025-06-24 18:18:30 +08:00
|
|
|
|
float_flag = True
|
|
|
|
|
|
break
|
2025-07-14 17:51:26 +08:00
|
|
|
|
elif re.match(r"[+-]?[0-9.]{,19}$", str(a).replace("%%", "")) and not str(a).replace("%%", "").startswith("0"):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
counts["float"] += 1
|
|
|
|
|
|
elif re.match(r"(true|yes|是|\*|✓|✔|☑|✅|√|false|no|否|⍻|×)$", str(a), flags=re.IGNORECASE):
|
|
|
|
|
|
counts["bool"] += 1
|
|
|
|
|
|
elif trans_datatime(str(a)):
|
|
|
|
|
|
counts["datetime"] += 1
|
|
|
|
|
|
else:
|
|
|
|
|
|
counts["text"] += 1
|
2025-06-24 18:18:30 +08:00
|
|
|
|
if float_flag:
|
|
|
|
|
|
ty = "float"
|
|
|
|
|
|
else:
|
|
|
|
|
|
counts = sorted(counts.items(), key=lambda x: x[1] * -1)
|
|
|
|
|
|
ty = counts[0][0]
|
2024-08-15 09:17:36 +08:00
|
|
|
|
for i in range(len(arr)):
|
|
|
|
|
|
if arr[i] is None:
|
|
|
|
|
|
continue
|
|
|
|
|
|
try:
|
|
|
|
|
|
arr[i] = trans[ty](str(arr[i]))
|
2025-12-30 15:04:09 +08:00
|
|
|
|
except Exception as e:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
arr[i] = None
|
2025-12-30 15:04:09 +08:00
|
|
|
|
logging.warning(f"Column {i}: {e}")
|
2024-08-15 09:17:36 +08:00
|
|
|
|
# if ty == "text":
|
|
|
|
|
|
# if len(arr) > 128 and uni / len(arr) < 0.1:
|
|
|
|
|
|
# ty = "keyword"
|
|
|
|
|
|
return arr, ty
|
|
|
|
|
|
|
|
|
|
|
|
|
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_TASK_PAGE_NUMBER, lang="Chinese", callback=None, **kwargs):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
"""
|
2025-06-10 10:16:38 +08:00
|
|
|
|
Excel and csv(txt) format files are supported.
|
|
|
|
|
|
For csv or txt file, the delimiter between columns is TAB.
|
|
|
|
|
|
The first line must be column headers.
|
|
|
|
|
|
Column headers must be meaningful terms inorder to make our NLP model understanding.
|
|
|
|
|
|
It's good to enumerate some synonyms using slash '/' to separate, and even better to
|
|
|
|
|
|
enumerate values using brackets like 'gender/sex(male, female)'.
|
|
|
|
|
|
Here are some examples for headers:
|
|
|
|
|
|
1. supplier/vendor\tcolor(yellow, red, brown)\tgender/sex(male, female)\tsize(M,L,XL,XXL)
|
|
|
|
|
|
2. 姓名/名字\t电话/手机/微信\t最高学历(高中,职高,硕士,本科,博士,初中,中技,中专,专科,专升本,MPA,MBA,EMBA)
|
|
|
|
|
|
|
|
|
|
|
|
Every row in table will be treated as a chunk.
|
2024-08-15 09:17:36 +08:00
|
|
|
|
"""
|
2025-12-22 10:17:44 +08:00
|
|
|
|
tbls = []
|
|
|
|
|
|
is_english = lang.lower() == "english"
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
|
|
|
|
|
|
callback(0.1, "Start to parse.")
|
|
|
|
|
|
excel_parser = Excel()
|
2025-12-29 12:01:18 +08:00
|
|
|
|
dfs, tbls = excel_parser(filename, binary, from_page=from_page, to_page=to_page, callback=callback, **kwargs)
|
2025-12-10 16:44:06 +08:00
|
|
|
|
elif re.search(r"\.txt$", filename, re.IGNORECASE):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
callback(0.1, "Start to parse.")
|
2024-09-29 10:29:56 +08:00
|
|
|
|
txt = get_text(filename, binary)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
lines = txt.split("\n")
|
|
|
|
|
|
fails = []
|
|
|
|
|
|
headers = lines[0].split(kwargs.get("delimiter", "\t"))
|
|
|
|
|
|
rows = []
|
|
|
|
|
|
for i, line in enumerate(lines[1:]):
|
|
|
|
|
|
if i < from_page:
|
|
|
|
|
|
continue
|
|
|
|
|
|
if i >= to_page:
|
|
|
|
|
|
break
|
2024-12-08 14:21:12 +08:00
|
|
|
|
row = [field for field in line.split(kwargs.get("delimiter", "\t"))]
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if len(row) != len(headers):
|
|
|
|
|
|
fails.append(str(i))
|
|
|
|
|
|
continue
|
|
|
|
|
|
rows.append(row)
|
|
|
|
|
|
|
2025-12-29 12:01:18 +08:00
|
|
|
|
callback(0.3, ("Extract records: {}~{}".format(from_page, min(len(lines), to_page)) + (
|
|
|
|
|
|
f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
dfs = [pd.DataFrame(np.array(rows), columns=headers)]
|
2025-12-10 16:44:06 +08:00
|
|
|
|
elif re.search(r"\.csv$", filename, re.IGNORECASE):
|
|
|
|
|
|
callback(0.1, "Start to parse.")
|
|
|
|
|
|
txt = get_text(filename, binary)
|
|
|
|
|
|
delimiter = kwargs.get("delimiter", ",")
|
|
|
|
|
|
|
|
|
|
|
|
reader = csv.reader(io.StringIO(txt), delimiter=delimiter)
|
|
|
|
|
|
all_rows = list(reader)
|
|
|
|
|
|
if not all_rows:
|
|
|
|
|
|
raise ValueError("Empty CSV file")
|
|
|
|
|
|
|
|
|
|
|
|
headers = all_rows[0]
|
|
|
|
|
|
fails = []
|
|
|
|
|
|
rows = []
|
|
|
|
|
|
|
2025-12-29 12:01:18 +08:00
|
|
|
|
for i, row in enumerate(all_rows[1 + from_page: 1 + to_page]):
|
2025-12-10 16:44:06 +08:00
|
|
|
|
if len(row) != len(headers):
|
|
|
|
|
|
fails.append(str(i + from_page))
|
|
|
|
|
|
continue
|
|
|
|
|
|
rows.append(row)
|
|
|
|
|
|
|
|
|
|
|
|
callback(
|
|
|
|
|
|
0.3,
|
|
|
|
|
|
(f"Extract records: {from_page}~{from_page + len(rows)}" +
|
2025-12-29 12:01:18 +08:00
|
|
|
|
(f"{len(fails)} failure, line: {','.join(fails[:3])}..." if fails else ""))
|
2025-12-10 16:44:06 +08:00
|
|
|
|
)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
2025-12-10 16:44:06 +08:00
|
|
|
|
dfs = [pd.DataFrame(rows, columns=headers)]
|
2024-08-15 09:17:36 +08:00
|
|
|
|
else:
|
2025-06-10 10:16:38 +08:00
|
|
|
|
raise NotImplementedError("file type not supported yet(excel, text, csv supported)")
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
res = []
|
|
|
|
|
|
PY = Pinyin()
|
2026-01-19 19:35:14 +08:00
|
|
|
|
# Field type suffixes for database columns
|
|
|
|
|
|
# Maps data types to their database field suffixes
|
|
|
|
|
|
fields_map = {"text": "_tks", "int": "_long", "keyword": "_kwd", "float": "_flt", "datetime": "_dt", "bool": "_kwd"}
|
2024-08-15 09:17:36 +08:00
|
|
|
|
for df in dfs:
|
2024-12-30 18:38:51 +08:00
|
|
|
|
for n in ["id", "_id", "index", "idx"]:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
if n in df.columns:
|
|
|
|
|
|
del df[n]
|
|
|
|
|
|
clmns = df.columns.values
|
2025-04-18 14:42:36 +08:00
|
|
|
|
if len(clmns) != len(set(clmns)):
|
2025-06-10 10:16:38 +08:00
|
|
|
|
col_counts = Counter(clmns)
|
|
|
|
|
|
duplicates = [col for col, count in col_counts.items() if count > 1]
|
|
|
|
|
|
if duplicates:
|
|
|
|
|
|
raise ValueError(f"Duplicate column names detected: {duplicates}\nFrom: {clmns}")
|
|
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
txts = list(copy.deepcopy(clmns))
|
2025-06-10 10:16:38 +08:00
|
|
|
|
py_clmns = [PY.get_pinyins(re.sub(r"(/.*|([^()]+?)|\([^()]+?\))", "", str(n)), "_")[0] for n in clmns]
|
2024-08-15 09:17:36 +08:00
|
|
|
|
clmn_tys = []
|
|
|
|
|
|
for j in range(len(clmns)):
|
|
|
|
|
|
cln, ty = column_data_type(df[clmns[j]])
|
|
|
|
|
|
clmn_tys.append(ty)
|
|
|
|
|
|
df[clmns[j]] = cln
|
|
|
|
|
|
if ty == "text":
|
|
|
|
|
|
txts.extend([str(c) for c in cln if c])
|
2026-01-19 19:35:14 +08:00
|
|
|
|
clmns_map = [(py_clmns[i].lower() + fields_map[clmn_tys[i]], str(clmns[i]).replace("_", " ")) for i in
|
2025-12-29 12:01:18 +08:00
|
|
|
|
range(len(clmns))]
|
2026-01-31 15:11:54 +08:00
|
|
|
|
# For Infinity/OceanBase: Use original column names as keys since they're stored in chunk_data JSON
|
2026-01-19 19:35:14 +08:00
|
|
|
|
# For ES/OS: Use full field names with type suffixes (e.g., url_kwd, body_tks)
|
2026-01-31 15:11:54 +08:00
|
|
|
|
if settings.DOC_ENGINE_INFINITY or settings.DOC_ENGINE_OCEANBASE:
|
|
|
|
|
|
# For Infinity/OceanBase: key = original column name, value = display name
|
2026-01-19 19:35:14 +08:00
|
|
|
|
field_map = {py_clmns[i].lower(): str(clmns[i]).replace("_", " ") for i in range(len(clmns))}
|
|
|
|
|
|
else:
|
|
|
|
|
|
# For ES/OS: key = typed field name, value = display name
|
|
|
|
|
|
field_map = {k: v for k, v in clmns_map}
|
|
|
|
|
|
logging.debug(f"Field map: {field_map}")
|
|
|
|
|
|
KnowledgebaseService.update_parser_config(kwargs["kb_id"], {"field_map": field_map})
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
eng = lang.lower() == "english" # is_english(txts)
|
|
|
|
|
|
for ii, row in df.iterrows():
|
2025-06-10 10:16:38 +08:00
|
|
|
|
d = {"docnm_kwd": filename, "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))}
|
2026-01-19 19:35:14 +08:00
|
|
|
|
row_fields = []
|
|
|
|
|
|
data_json = {} # For Infinity: Store all columns in a JSON object
|
2024-08-15 09:17:36 +08:00
|
|
|
|
for j in range(len(clmns)):
|
|
|
|
|
|
if row[clmns[j]] is None:
|
|
|
|
|
|
continue
|
|
|
|
|
|
if not str(row[clmns[j]]):
|
|
|
|
|
|
continue
|
2025-02-28 16:09:12 +08:00
|
|
|
|
if not isinstance(row[clmns[j]], pd.Series) and pd.isna(row[clmns[j]]):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
continue
|
2026-01-31 15:11:54 +08:00
|
|
|
|
# For Infinity/OceanBase: Store in chunk_data JSON column
|
2026-01-19 19:35:14 +08:00
|
|
|
|
# For Elasticsearch/OpenSearch: Store as individual fields with type suffixes
|
2026-01-31 15:11:54 +08:00
|
|
|
|
if settings.DOC_ENGINE_INFINITY or settings.DOC_ENGINE_OCEANBASE:
|
2026-01-19 19:35:14 +08:00
|
|
|
|
data_json[str(clmns[j])] = row[clmns[j]]
|
|
|
|
|
|
else:
|
|
|
|
|
|
fld = clmns_map[j][0]
|
|
|
|
|
|
d[fld] = row[clmns[j]] if clmn_tys[j] != "text" else rag_tokenizer.tokenize(row[clmns[j]])
|
|
|
|
|
|
row_fields.append((clmns[j], row[clmns[j]]))
|
|
|
|
|
|
if not row_fields:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
continue
|
2026-01-31 15:11:54 +08:00
|
|
|
|
# Add the data JSON field to the document (for Infinity/OceanBase)
|
|
|
|
|
|
if settings.DOC_ENGINE_INFINITY or settings.DOC_ENGINE_OCEANBASE:
|
2026-01-19 19:35:14 +08:00
|
|
|
|
d["chunk_data"] = data_json
|
|
|
|
|
|
# Format as a structured text for better LLM comprehension
|
|
|
|
|
|
# Format each field as "- Field Name: Value" on separate lines
|
|
|
|
|
|
formatted_text = "\n".join([f"- {field}: {value}" for field, value in row_fields])
|
|
|
|
|
|
tokenize(d, formatted_text, eng)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
res.append(d)
|
2025-12-22 10:17:44 +08:00
|
|
|
|
if tbls:
|
|
|
|
|
|
doc = {"docnm_kwd": filename, "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))}
|
|
|
|
|
|
res.extend(tokenize_table(tbls, doc, is_english))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
callback(0.35, "")
|
|
|
|
|
|
|
|
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
import sys
|
|
|
|
|
|
|
2025-12-29 12:01:18 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
def dummy(prog=None, msg=""):
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
2025-12-29 12:01:18 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
chunk(sys.argv[1], callback=dummy)
|