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
|
|
|
|
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
logger = logging.getLogger(__name__)
|
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 = []
|
|
|
|
|
|
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)
|
2026-05-11 13:17:14 +08:00
|
|
|
|
pending_cell_images = []
|
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
|
|
|
|
"""
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
_pc0 = kwargs.get("parser_config") or {}
|
|
|
|
|
|
logger.debug(f"[TABLE_PARSER_DEBUG] parser_config keys: {list(_pc0.keys())}")
|
|
|
|
|
|
logger.debug(f"[TABLE_PARSER_DEBUG] table_column_mode: {_pc0.get('table_column_mode')}")
|
|
|
|
|
|
logger.debug(f"[TABLE_PARSER_DEBUG] table_column_roles: {_pc0.get('table_column_roles')}")
|
|
|
|
|
|
|
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"}
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
parser_config = kwargs.get("parser_config") or {}
|
|
|
|
|
|
if parser_config.get("table_column_mode") == "manual":
|
|
|
|
|
|
column_roles = parser_config.get("table_column_roles") or {}
|
|
|
|
|
|
else:
|
|
|
|
|
|
column_roles = {}
|
|
|
|
|
|
logger.debug(
|
|
|
|
|
|
f"[TABLE_PARSER_DEBUG] effective table_column_mode={parser_config.get('table_column_mode')!r}, "
|
|
|
|
|
|
f"column_roles keys={list(column_roles.keys())}"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# Pass 1: infer columns per sheet (multi-sheet Excel => multiple DataFrames). Merge field_map and
|
|
|
|
|
|
# table_column_names, then update KB once so the UI role selector sees all columns, not only the last sheet.
|
|
|
|
|
|
sheet_specs = []
|
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))]
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
# field_map: only columns stored in chunk_data (metadata or both) — used for retrieval/SQL
|
|
|
|
|
|
stored_indices = [
|
|
|
|
|
|
i for i in range(len(clmns))
|
|
|
|
|
|
if column_roles.get(clmns[i], "both") in ("metadata", "both")
|
|
|
|
|
|
]
|
2026-01-31 15:11:54 +08:00
|
|
|
|
if settings.DOC_ENGINE_INFINITY or settings.DOC_ENGINE_OCEANBASE:
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
field_map = {
|
|
|
|
|
|
py_clmns[i].lower(): str(clmns[i]).replace("_", " ")
|
|
|
|
|
|
for i in stored_indices
|
|
|
|
|
|
}
|
2026-01-19 19:35:14 +08:00
|
|
|
|
else:
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
field_map = {
|
|
|
|
|
|
clmns_map[i][0]: clmns_map[i][1]
|
|
|
|
|
|
for i in stored_indices
|
|
|
|
|
|
}
|
|
|
|
|
|
logging.debug(f"Field map (sheet): {field_map}")
|
|
|
|
|
|
sheet_specs.append(
|
|
|
|
|
|
{
|
|
|
|
|
|
"df": df,
|
|
|
|
|
|
"clmns": clmns,
|
|
|
|
|
|
"clmn_tys": clmn_tys,
|
|
|
|
|
|
"clmns_map": clmns_map,
|
|
|
|
|
|
"py_clmns": py_clmns,
|
|
|
|
|
|
"field_map": field_map,
|
|
|
|
|
|
}
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
merged_field_map = {}
|
|
|
|
|
|
merged_table_column_names = []
|
|
|
|
|
|
seen_col = set()
|
|
|
|
|
|
for spec in sheet_specs:
|
|
|
|
|
|
merged_field_map.update(spec["field_map"])
|
|
|
|
|
|
for col in spec["clmns"]:
|
|
|
|
|
|
if col not in seen_col:
|
|
|
|
|
|
seen_col.add(col)
|
|
|
|
|
|
merged_table_column_names.append(col)
|
|
|
|
|
|
|
|
|
|
|
|
logging.debug(f"Field map (merged across sheets): {merged_field_map}")
|
|
|
|
|
|
kb_id = kwargs.get("kb_id")
|
|
|
|
|
|
if kb_id:
|
|
|
|
|
|
KnowledgebaseService.update_parser_config(
|
|
|
|
|
|
kb_id,
|
|
|
|
|
|
{"field_map": merged_field_map, "table_column_names": merged_table_column_names},
|
|
|
|
|
|
)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
eng = lang.lower() == "english" # is_english(txts)
|
|
|
|
|
|
for spec in sheet_specs:
|
|
|
|
|
|
df = spec["df"]
|
|
|
|
|
|
clmns = spec["clmns"]
|
|
|
|
|
|
clmn_tys = spec["clmn_tys"]
|
|
|
|
|
|
clmns_map = spec["clmns_map"]
|
|
|
|
|
|
py_clmns = spec["py_clmns"]
|
|
|
|
|
|
_debug_row_idx = 0
|
2024-08-15 09:17:36 +08:00
|
|
|
|
for ii, row in df.iterrows():
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
_debug_row_idx += 1
|
2025-06-10 10:16:38 +08:00
|
|
|
|
d = {"docnm_kwd": filename, "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))}
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
text_fields = [] # indexing + both -> content_with_weight
|
|
|
|
|
|
stored = {} # metadata + both -> chunk_data (Infinity) or typed fields (ES)
|
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
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
col_name = clmns[j]
|
|
|
|
|
|
role = column_roles.get(col_name, "both")
|
|
|
|
|
|
if _debug_row_idx == 1:
|
|
|
|
|
|
logger.debug(f"[TABLE_PARSER_DEBUG] Column '{col_name}' -> role '{role}'")
|
|
|
|
|
|
if role in ("indexing", "vectorize", "both"):
|
|
|
|
|
|
text_fields.append((col_name, row[col_name]))
|
|
|
|
|
|
if role in ("metadata", "both"):
|
|
|
|
|
|
if settings.DOC_ENGINE_INFINITY or settings.DOC_ENGINE_OCEANBASE:
|
|
|
|
|
|
stored[str(col_name)] = row[col_name]
|
|
|
|
|
|
else:
|
|
|
|
|
|
fld = clmns_map[j][0]
|
|
|
|
|
|
if clmn_tys[j] != "text":
|
|
|
|
|
|
stored[fld] = row[col_name]
|
|
|
|
|
|
else:
|
|
|
|
|
|
cell = row[col_name]
|
|
|
|
|
|
stored[fld] = rag_tokenizer.tokenize(cell)
|
|
|
|
|
|
raw_s = str(cell).strip() if cell is not None else ""
|
|
|
|
|
|
if raw_s:
|
|
|
|
|
|
stored[f"{py_clmns[j].lower()}_raw"] = raw_s
|
|
|
|
|
|
if not text_fields and not stored:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
continue
|
2026-01-31 15:11:54 +08:00
|
|
|
|
if settings.DOC_ENGINE_INFINITY or settings.DOC_ENGINE_OCEANBASE:
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
if stored:
|
|
|
|
|
|
d["chunk_data"] = stored
|
|
|
|
|
|
else:
|
|
|
|
|
|
d.update(stored)
|
|
|
|
|
|
formatted_text = "\n".join([f"- {field}: {value}" for field, value in text_fields]) if text_fields else ""
|
2026-01-19 19:35:14 +08:00
|
|
|
|
tokenize(d, formatted_text, eng)
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05:00
|
|
|
|
if _debug_row_idx == 1:
|
|
|
|
|
|
logger.debug(
|
|
|
|
|
|
f"[TABLE_PARSER_DEBUG] Chunk content_with_weight length: {len(d.get('content_with_weight', '') or '')}"
|
|
|
|
|
|
)
|
|
|
|
|
|
_cd = d.get("chunk_data")
|
|
|
|
|
|
logger.debug(
|
|
|
|
|
|
f"[TABLE_PARSER_DEBUG] Chunk chunk_data keys: {list(_cd.keys()) if isinstance(_cd, dict) else 'N/A'}"
|
|
|
|
|
|
)
|
|
|
|
|
|
if not (settings.DOC_ENGINE_INFINITY or settings.DOC_ENGINE_OCEANBASE):
|
|
|
|
|
|
_extra = [k for k in d if k not in ("docnm_kwd", "title_tks", "content_with_weight", "content_ltks", "content_sm_ltks")]
|
|
|
|
|
|
logger.debug(f"[TABLE_PARSER_DEBUG] Chunk ES extra field keys (sample): {_extra[:20]}")
|
2024-08-15 09:17:36 +08:00
|
|
|
|
res.append(d)
|
Feature/table parser column roles (#13710)
### What problem does this PR solve?
The table file parser (CSV/Excel) currently treats all columns
identically — every column is both vectorized (embedded in chunk text)
and stored as filterable metadata. There's no way for users to control
which columns should be searchable by semantic meaning versus which
should only be filterable attributes.
For example, when ingesting a news articles CSV with columns like title,
content, country, category, source, etc., the embedding includes
metadata fields like country: Brazil and source: Reuters in the chunk
text, which dilutes the semantic quality of the embedding without adding
retrieval value.
The RDBMS connector (MySQL/PostgreSQL) already supports content_columns
/ metadata_columns, but this capability was missing for file-based table
ingestion.
This PR adds column-level control (vectorize / metadata / both) for the
table file parser, following RAGFlow's existing patterns.
Backward compatible: Datasets without table_column_roles or with
table_column_mode: auto behave exactly as before (all columns = both).
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
2026-05-11 07:06:04 +05: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)
|