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-11-14 17:13:48 +08:00
|
|
|
|
import logging
|
2024-08-15 09:17:36 +08:00
|
|
|
|
import copy
|
|
|
|
|
|
import re
|
|
|
|
|
|
|
2025-10-21 09:36:27 +08:00
|
|
|
|
from deepdoc.parser.figure_parser import vision_figure_parser_pdf_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 ParserType, MAXIMUM_PAGE_NUMBER
|
2025-12-29 12:01:18 +08:00
|
|
|
|
from rag.nlp import rag_tokenizer, tokenize, tokenize_table, add_positions, bullets_category, title_frequency, \
|
|
|
|
|
|
tokenize_chunks, attach_media_context
|
2025-11-20 19:07:17 +08:00
|
|
|
|
from deepdoc.parser import PdfParser
|
2024-08-15 09:17:36 +08:00
|
|
|
|
import numpy as np
|
2025-11-20 19:07:17 +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
|
2025-11-20 19:07:17 +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.PAPER.value
|
2024-08-15 09:17:36 +08:00
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
|
|
|
|
def __call__(self, filename, binary=None, from_page=0,
|
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
|
|
|
|
to_page=MAXIMUM_PAGE_NUMBER, zoomin=3, callback=None):
|
2024-11-30 18:48:06 +08:00
|
|
|
|
from timeit import default_timer as timer
|
|
|
|
|
|
start = timer()
|
|
|
|
|
|
callback(msg="OCR started")
|
2024-08-15 09:17:36 +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-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
start = timer()
|
|
|
|
|
|
self._layouts_rec(zoomin)
|
2024-11-30 18:48:06 +08:00
|
|
|
|
callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
|
2024-11-14 17:13:48 +08:00
|
|
|
|
logging.debug(f"layouts cost: {timer() - start}s")
|
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.68, "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)
|
|
|
|
|
|
column_width = np.median([b["x1"] - b["x0"] for b in self.boxes])
|
|
|
|
|
|
self._concat_downward()
|
|
|
|
|
|
self._filter_forpages()
|
2024-11-30 18:48:06 +08:00
|
|
|
|
callback(0.75, "Text merged ({:.2f}s)".format(timer() - start))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
# clean mess
|
|
|
|
|
|
if column_width < self.page_images[0].size[0] / zoomin / 2:
|
2024-11-14 17:13:48 +08:00
|
|
|
|
logging.debug("two_column................... {} {}".format(column_width,
|
2025-12-29 12:01:18 +08:00
|
|
|
|
self.page_images[0].size[0] / zoomin / 2))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
self.boxes = self.sort_X_by_page(self.boxes, column_width / 2)
|
|
|
|
|
|
for b in self.boxes:
|
|
|
|
|
|
b["text"] = re.sub(r"([\t ]|\u3000){2,}", " ", b["text"].strip())
|
|
|
|
|
|
|
|
|
|
|
|
def _begin(txt):
|
|
|
|
|
|
return re.match(
|
|
|
|
|
|
"[0-9. 一、i]*(introduction|abstract|摘要|引言|keywords|key words|关键词|background|背景|目录|前言|contents)",
|
|
|
|
|
|
txt.lower().strip())
|
|
|
|
|
|
|
|
|
|
|
|
if from_page > 0:
|
|
|
|
|
|
return {
|
|
|
|
|
|
"title": "",
|
|
|
|
|
|
"authors": "",
|
|
|
|
|
|
"abstract": "",
|
|
|
|
|
|
"sections": [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", "")) for b in self.boxes if
|
|
|
|
|
|
re.match(r"(text|title)", b.get("layoutno", "text"))],
|
|
|
|
|
|
"tables": tbls
|
|
|
|
|
|
}
|
|
|
|
|
|
# get title and authors
|
|
|
|
|
|
title = ""
|
|
|
|
|
|
authors = []
|
|
|
|
|
|
i = 0
|
2025-12-29 12:01:18 +08:00
|
|
|
|
while i < min(32, len(self.boxes) - 1):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
b = self.boxes[i]
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
if b.get("layoutno", "").find("title") >= 0:
|
|
|
|
|
|
title = b["text"]
|
|
|
|
|
|
if _begin(title):
|
|
|
|
|
|
title = ""
|
|
|
|
|
|
break
|
|
|
|
|
|
for j in range(3):
|
2026-02-26 10:24:13 +08:00
|
|
|
|
next_idx = i + j
|
|
|
|
|
|
if next_idx >= len(self.boxes):
|
2024-08-15 09:17:36 +08:00
|
|
|
|
break
|
2026-02-26 10:24:13 +08:00
|
|
|
|
candidate = self.boxes[next_idx]["text"]
|
|
|
|
|
|
if _begin(candidate):
|
|
|
|
|
|
break
|
|
|
|
|
|
if "@" in candidate:
|
|
|
|
|
|
break
|
|
|
|
|
|
authors.append(candidate)
|
2024-08-15 09:17:36 +08:00
|
|
|
|
break
|
|
|
|
|
|
# get abstract
|
|
|
|
|
|
abstr = ""
|
|
|
|
|
|
i = 0
|
|
|
|
|
|
while i + 1 < min(32, len(self.boxes)):
|
|
|
|
|
|
b = self.boxes[i]
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
txt = b["text"].lower().strip()
|
|
|
|
|
|
if re.match("(abstract|摘要)", txt):
|
2024-11-28 13:00:38 +08:00
|
|
|
|
if len(txt.split()) > 32 or len(txt) > 64:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
abstr = txt + self._line_tag(b, zoomin)
|
|
|
|
|
|
break
|
|
|
|
|
|
txt = self.boxes[i]["text"].lower().strip()
|
2024-11-28 13:00:38 +08:00
|
|
|
|
if len(txt.split()) > 32 or len(txt) > 64:
|
2024-08-15 09:17:36 +08:00
|
|
|
|
abstr = txt + self._line_tag(self.boxes[i], zoomin)
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
break
|
|
|
|
|
|
if not abstr:
|
|
|
|
|
|
i = 0
|
|
|
|
|
|
|
|
|
|
|
|
callback(
|
|
|
|
|
|
0.8, "Page {}~{}: Text merging finished".format(
|
|
|
|
|
|
from_page, min(
|
|
|
|
|
|
to_page, self.total_page)))
|
|
|
|
|
|
for b in self.boxes:
|
2024-11-14 17:13:48 +08:00
|
|
|
|
logging.debug("{} {}".format(b["text"], b.get("layoutno")))
|
|
|
|
|
|
logging.debug("{}".format(tbls))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
"title": title,
|
|
|
|
|
|
"authors": " ".join(authors),
|
|
|
|
|
|
"abstract": abstr,
|
|
|
|
|
|
"sections": [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", "")) for b in self.boxes[i:] if
|
|
|
|
|
|
re.match(r"(text|title)", b.get("layoutno", "text"))],
|
|
|
|
|
|
"tables": tbls
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
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,
|
2024-08-15 09:17:36 +08:00
|
|
|
|
lang="Chinese", callback=None, **kwargs):
|
|
|
|
|
|
"""
|
|
|
|
|
|
Only pdf is supported.
|
|
|
|
|
|
The abstract of the paper will be sliced as an entire chunk, and will not be sliced partly.
|
|
|
|
|
|
"""
|
2025-07-30 19:41:09 +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
|
|
|
|
if re.search(r"\.pdf$", filename, re.IGNORECASE):
|
2025-12-17 19:48:24 +08:00
|
|
|
|
layout_recognizer, parser_model_name = normalize_layout_recognizer(
|
|
|
|
|
|
parser_config.get("layout_recognize", "DeepDOC")
|
|
|
|
|
|
)
|
2025-11-27 10:21:44 +08:00
|
|
|
|
|
2025-11-20 19:07:17 +08:00
|
|
|
|
if isinstance(layout_recognizer, bool):
|
|
|
|
|
|
layout_recognizer = "DeepDOC" if layout_recognizer else "Plain Text"
|
|
|
|
|
|
|
|
|
|
|
|
name = layout_recognizer.strip().lower()
|
|
|
|
|
|
pdf_parser = PARSERS.get(name, by_plaintext)
|
|
|
|
|
|
callback(0.1, "Start to parse.")
|
|
|
|
|
|
|
|
|
|
|
|
if name == "deepdoc":
|
|
|
|
|
|
pdf_parser = Pdf()
|
|
|
|
|
|
paper = pdf_parser(filename if not binary else binary,
|
|
|
|
|
|
from_page=from_page, to_page=to_page, callback=callback)
|
2026-01-05 09:55:43 +08:00
|
|
|
|
sections = paper.get("sections", [])
|
2025-11-20 19:07:17 +08:00
|
|
|
|
else:
|
2025-12-17 19:48:24 +08:00
|
|
|
|
kwargs.pop("parse_method", None)
|
|
|
|
|
|
kwargs.pop("mineru_llm_name", None)
|
2025-11-20 19:07:17 +08:00
|
|
|
|
sections, tables, pdf_parser = pdf_parser(
|
|
|
|
|
|
filename=filename,
|
|
|
|
|
|
binary=binary,
|
|
|
|
|
|
from_page=from_page,
|
|
|
|
|
|
to_page=to_page,
|
|
|
|
|
|
lang=lang,
|
|
|
|
|
|
callback=callback,
|
|
|
|
|
|
pdf_cls=Pdf,
|
2025-12-17 19:48:24 +08:00
|
|
|
|
layout_recognizer=layout_recognizer,
|
|
|
|
|
|
mineru_llm_name=parser_model_name,
|
2025-11-20 19:07:17 +08:00
|
|
|
|
parse_method="paper",
|
|
|
|
|
|
**kwargs
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
paper = {
|
|
|
|
|
|
"title": filename,
|
|
|
|
|
|
"authors": " ",
|
|
|
|
|
|
"abstract": "",
|
2025-11-20 19:07:17 +08:00
|
|
|
|
"sections": sections,
|
|
|
|
|
|
"tables": tables
|
2024-08-15 09:17:36 +08:00
|
|
|
|
}
|
2025-11-20 19:07:17 +08:00
|
|
|
|
|
2025-12-29 12:01:18 +08:00
|
|
|
|
tbls = paper["tables"]
|
2026-01-05 09:55:43 +08:00
|
|
|
|
tbls = vision_figure_parser_pdf_wrapper(
|
|
|
|
|
|
tbls=tbls,
|
|
|
|
|
|
sections=sections,
|
|
|
|
|
|
callback=callback,
|
|
|
|
|
|
**kwargs,
|
|
|
|
|
|
)
|
2025-10-21 09:36:27 +08:00
|
|
|
|
paper["tables"] = tbls
|
2024-08-15 09:17:36 +08:00
|
|
|
|
else:
|
|
|
|
|
|
raise NotImplementedError("file type not supported yet(pdf supported)")
|
|
|
|
|
|
|
|
|
|
|
|
doc = {"docnm_kwd": filename, "authors_tks": rag_tokenizer.tokenize(paper["authors"]),
|
|
|
|
|
|
"title_tks": rag_tokenizer.tokenize(paper["title"] if paper["title"] else filename)}
|
|
|
|
|
|
doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
|
|
|
|
|
|
doc["authors_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["authors_tks"])
|
|
|
|
|
|
# is it English
|
|
|
|
|
|
eng = lang.lower() == "english" # pdf_parser.is_english
|
2024-11-14 17:13:48 +08:00
|
|
|
|
logging.debug("It's English.....{}".format(eng))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
res = tokenize_table(paper["tables"], doc, eng)
|
|
|
|
|
|
|
|
|
|
|
|
if paper["abstract"]:
|
|
|
|
|
|
d = copy.deepcopy(doc)
|
|
|
|
|
|
txt = pdf_parser.remove_tag(paper["abstract"])
|
|
|
|
|
|
d["important_kwd"] = ["abstract", "总结", "概括", "summary", "summarize"]
|
|
|
|
|
|
d["important_tks"] = " ".join(d["important_kwd"])
|
|
|
|
|
|
d["image"], poss = pdf_parser.crop(
|
|
|
|
|
|
paper["abstract"], need_position=True)
|
|
|
|
|
|
add_positions(d, poss)
|
|
|
|
|
|
tokenize(d, txt, eng)
|
|
|
|
|
|
res.append(d)
|
|
|
|
|
|
|
|
|
|
|
|
sorted_sections = paper["sections"]
|
|
|
|
|
|
# set pivot using the most frequent type of title,
|
|
|
|
|
|
# then merge between 2 pivot
|
|
|
|
|
|
bull = bullets_category([txt for txt, _ in sorted_sections])
|
|
|
|
|
|
most_level, levels = title_frequency(bull, sorted_sections)
|
|
|
|
|
|
assert len(sorted_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)
|
2024-11-14 17:13:48 +08:00
|
|
|
|
logging.debug("{} {} {} {}".format(lvl, sorted_sections[i][0], most_level, sid))
|
2024-08-15 09:17:36 +08:00
|
|
|
|
|
|
|
|
|
|
chunks = []
|
|
|
|
|
|
last_sid = -2
|
|
|
|
|
|
for (txt, _), sec_id in zip(sorted_sections, sec_ids):
|
|
|
|
|
|
if sec_id == last_sid:
|
|
|
|
|
|
if chunks:
|
|
|
|
|
|
chunks[-1] += "\n" + txt
|
|
|
|
|
|
continue
|
|
|
|
|
|
chunks.append(txt)
|
|
|
|
|
|
last_sid = sec_id
|
|
|
|
|
|
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)
|
2026-04-03 19:26:45 +08:00
|
|
|
|
|
2024-08-15 09:17:36 +08:00
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
readed = [0] * len(paper["lines"])
|
|
|
|
|
|
# find colon firstly
|
|
|
|
|
|
i = 0
|
|
|
|
|
|
while i + 1 < len(paper["lines"]):
|
|
|
|
|
|
txt = pdf_parser.remove_tag(paper["lines"][i][0])
|
|
|
|
|
|
j = i
|
|
|
|
|
|
if txt.strip("\n").strip()[-1] not in "::":
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
continue
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
while i < len(paper["lines"]) and not paper["lines"][i][0]:
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
if i >= len(paper["lines"]): break
|
|
|
|
|
|
proj = [paper["lines"][i][0].strip()]
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
while i < len(paper["lines"]) and paper["lines"][i][0].strip()[0] == proj[-1][0]:
|
|
|
|
|
|
proj.append(paper["lines"][i])
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
for k in range(j, i): readed[k] = True
|
|
|
|
|
|
txt = txt[::-1]
|
|
|
|
|
|
if eng:
|
|
|
|
|
|
r = re.search(r"(.*?) ([\\.;?!]|$)", txt)
|
|
|
|
|
|
txt = r.group(1)[::-1] if r else txt[::-1]
|
|
|
|
|
|
else:
|
|
|
|
|
|
r = re.search(r"(.*?) ([。?;!]|$)", txt)
|
|
|
|
|
|
txt = r.group(1)[::-1] if r else txt[::-1]
|
|
|
|
|
|
for p in proj:
|
|
|
|
|
|
d = copy.deepcopy(doc)
|
|
|
|
|
|
txt += "\n" + pdf_parser.remove_tag(p)
|
|
|
|
|
|
d["image"], poss = pdf_parser.crop(p, need_position=True)
|
|
|
|
|
|
add_positions(d, poss)
|
|
|
|
|
|
tokenize(d, txt, eng)
|
|
|
|
|
|
res.append(d)
|
|
|
|
|
|
|
|
|
|
|
|
i = 0
|
|
|
|
|
|
chunk = []
|
|
|
|
|
|
tk_cnt = 0
|
|
|
|
|
|
def add_chunk():
|
|
|
|
|
|
nonlocal chunk, res, doc, pdf_parser, tk_cnt
|
|
|
|
|
|
d = copy.deepcopy(doc)
|
|
|
|
|
|
ck = "\n".join(chunk)
|
|
|
|
|
|
tokenize(d, pdf_parser.remove_tag(ck), pdf_parser.is_english)
|
|
|
|
|
|
d["image"], poss = pdf_parser.crop(ck, need_position=True)
|
|
|
|
|
|
add_positions(d, poss)
|
|
|
|
|
|
res.append(d)
|
|
|
|
|
|
chunk = []
|
|
|
|
|
|
tk_cnt = 0
|
|
|
|
|
|
|
|
|
|
|
|
while i < len(paper["lines"]):
|
|
|
|
|
|
if tk_cnt > 128:
|
|
|
|
|
|
add_chunk()
|
|
|
|
|
|
if readed[i]:
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
continue
|
|
|
|
|
|
readed[i] = True
|
|
|
|
|
|
txt, layouts = paper["lines"][i]
|
|
|
|
|
|
txt_ = pdf_parser.remove_tag(txt)
|
|
|
|
|
|
i += 1
|
|
|
|
|
|
cnt = num_tokens_from_string(txt_)
|
|
|
|
|
|
if any([
|
|
|
|
|
|
layouts.find("title") >= 0 and chunk,
|
|
|
|
|
|
cnt + tk_cnt > 128 and tk_cnt > 32,
|
|
|
|
|
|
]):
|
|
|
|
|
|
add_chunk()
|
|
|
|
|
|
chunk = [txt]
|
|
|
|
|
|
tk_cnt = cnt
|
|
|
|
|
|
else:
|
|
|
|
|
|
chunk.append(txt)
|
|
|
|
|
|
tk_cnt += cnt
|
|
|
|
|
|
|
|
|
|
|
|
if chunk: add_chunk()
|
|
|
|
|
|
for i, d in enumerate(res):
|
|
|
|
|
|
print(d)
|
|
|
|
|
|
# d["image"].save(f"./logs/{i}.jpg")
|
|
|
|
|
|
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)
|